From e40ac850a2f3df43b6dd89e4e7f050d81de1856e Mon Sep 17 00:00:00 2001 From: Michael Adams Date: Thu, 14 Jul 2022 12:40:10 -0700 Subject: [PATCH 1/5] Add linters Add linters --- src/.editorconfig | 66 ++++++++++++++++++- src/Greenshot.Base/Greenshot.Base.csproj | 14 ++++ src/Greenshot.Editor/Greenshot.Editor.csproj | 17 +++++ .../Greenshot.Plugin.Box.csproj | 18 +++++ .../Greenshot.Plugin.Confluence.csproj | 18 +++++ .../Greenshot.Plugin.Dropbox.csproj | 18 +++++ .../Greenshot.Plugin.ExternalCommand.csproj | 17 +++++ .../Greenshot.Plugin.Flickr.csproj | 18 +++++ .../Greenshot.Plugin.GooglePhotos.csproj | 18 +++++ .../Greenshot.Plugin.Imgur.csproj | 17 +++++ .../Greenshot.Plugin.Jira.csproj | 14 ++++ .../Greenshot.Plugin.Office.csproj | 15 +++++ .../Greenshot.Plugin.Photobucket.csproj | 17 +++++ .../Greenshot.Plugin.Win10.csproj | 14 ++++ src/Greenshot/Greenshot.csproj | 12 ++++ 15 files changed, 291 insertions(+), 2 deletions(-) diff --git a/src/.editorconfig b/src/.editorconfig index 0141618f9..599fc2144 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -14,7 +14,7 @@ indent_size = 4 # Xml project files [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] -indent_size = 2 +indent_size = 4 # Xml config files [*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] @@ -44,6 +44,12 @@ dotnet_style_collection_initializer = true:suggestion dotnet_style_coalesce_expression = true:suggestion dotnet_style_null_propagation = true:suggestion dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +end_of_line = crlf +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion # CSharp code style settings: [*.cs] @@ -70,4 +76,60 @@ csharp_new_line_before_else = true csharp_new_line_before_catch = true csharp_new_line_before_finally = true csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_members_in_anonymous_types = true \ No newline at end of file +csharp_new_line_before_members_in_anonymous_types = true +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_prefer_braces = true:silent +csharp_style_namespace_declarations = block_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_top_level_statements = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +[*.{cs,vb}] +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case diff --git a/src/Greenshot.Base/Greenshot.Base.csproj b/src/Greenshot.Base/Greenshot.Base.csproj index a698b8e0b..198145a4e 100644 --- a/src/Greenshot.Base/Greenshot.Base.csproj +++ b/src/Greenshot.Base/Greenshot.Base.csproj @@ -14,6 +14,14 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -21,4 +29,10 @@ + + + all + runtime; build; native; contentfiles; analyzers + + diff --git a/src/Greenshot.Editor/Greenshot.Editor.csproj b/src/Greenshot.Editor/Greenshot.Editor.csproj index 7da9d555d..06a1e6475 100644 --- a/src/Greenshot.Editor/Greenshot.Editor.csproj +++ b/src/Greenshot.Editor/Greenshot.Editor.csproj @@ -7,6 +7,16 @@ PreserveNewest + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + @@ -84,4 +94,11 @@ ImageEditorForm.cs + + + + all + runtime; build; native; contentfiles; analyzers + + \ No newline at end of file diff --git a/src/Greenshot.Plugin.Box/Greenshot.Plugin.Box.csproj b/src/Greenshot.Plugin.Box/Greenshot.Plugin.Box.csproj index fced869ad..a76cf281f 100644 --- a/src/Greenshot.Plugin.Box/Greenshot.Plugin.Box.csproj +++ b/src/Greenshot.Plugin.Box/Greenshot.Plugin.Box.csproj @@ -9,7 +9,25 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers + + \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Greenshot.Plugin.Confluence.csproj b/src/Greenshot.Plugin.Confluence/Greenshot.Plugin.Confluence.csproj index d885ea3f5..302b43132 100644 --- a/src/Greenshot.Plugin.Confluence/Greenshot.Plugin.Confluence.csproj +++ b/src/Greenshot.Plugin.Confluence/Greenshot.Plugin.Confluence.csproj @@ -9,6 +9,17 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + Never @@ -32,4 +43,11 @@ + + + + all + runtime; build; native; contentfiles; analyzers + + \ No newline at end of file diff --git a/src/Greenshot.Plugin.Dropbox/Greenshot.Plugin.Dropbox.csproj b/src/Greenshot.Plugin.Dropbox/Greenshot.Plugin.Dropbox.csproj index 09eb988a5..08d5c4f19 100644 --- a/src/Greenshot.Plugin.Dropbox/Greenshot.Plugin.Dropbox.csproj +++ b/src/Greenshot.Plugin.Dropbox/Greenshot.Plugin.Dropbox.csproj @@ -9,7 +9,25 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers + + \ No newline at end of file diff --git a/src/Greenshot.Plugin.ExternalCommand/Greenshot.Plugin.ExternalCommand.csproj b/src/Greenshot.Plugin.ExternalCommand/Greenshot.Plugin.ExternalCommand.csproj index 50e39b62a..9b51c94f8 100644 --- a/src/Greenshot.Plugin.ExternalCommand/Greenshot.Plugin.ExternalCommand.csproj +++ b/src/Greenshot.Plugin.ExternalCommand/Greenshot.Plugin.ExternalCommand.csproj @@ -4,8 +4,25 @@ PreserveNewest + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + diff --git a/src/Greenshot.Plugin.Flickr/Greenshot.Plugin.Flickr.csproj b/src/Greenshot.Plugin.Flickr/Greenshot.Plugin.Flickr.csproj index 5bc629bf1..f264e006e 100644 --- a/src/Greenshot.Plugin.Flickr/Greenshot.Plugin.Flickr.csproj +++ b/src/Greenshot.Plugin.Flickr/Greenshot.Plugin.Flickr.csproj @@ -9,7 +9,25 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers + + \ No newline at end of file diff --git a/src/Greenshot.Plugin.GooglePhotos/Greenshot.Plugin.GooglePhotos.csproj b/src/Greenshot.Plugin.GooglePhotos/Greenshot.Plugin.GooglePhotos.csproj index f2bfb8be5..7c933ecc7 100644 --- a/src/Greenshot.Plugin.GooglePhotos/Greenshot.Plugin.GooglePhotos.csproj +++ b/src/Greenshot.Plugin.GooglePhotos/Greenshot.Plugin.GooglePhotos.csproj @@ -9,7 +9,25 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers + + \ No newline at end of file diff --git a/src/Greenshot.Plugin.Imgur/Greenshot.Plugin.Imgur.csproj b/src/Greenshot.Plugin.Imgur/Greenshot.Plugin.Imgur.csproj index e0696e270..b1f4e2c7f 100644 --- a/src/Greenshot.Plugin.Imgur/Greenshot.Plugin.Imgur.csproj +++ b/src/Greenshot.Plugin.Imgur/Greenshot.Plugin.Imgur.csproj @@ -4,8 +4,25 @@ PreserveNewest + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + \ No newline at end of file diff --git a/src/Greenshot.Plugin.Jira/Greenshot.Plugin.Jira.csproj b/src/Greenshot.Plugin.Jira/Greenshot.Plugin.Jira.csproj index 40f2caf2d..4727708e5 100644 --- a/src/Greenshot.Plugin.Jira/Greenshot.Plugin.Jira.csproj +++ b/src/Greenshot.Plugin.Jira/Greenshot.Plugin.Jira.csproj @@ -8,5 +8,19 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers + \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/Greenshot.Plugin.Office.csproj b/src/Greenshot.Plugin.Office/Greenshot.Plugin.Office.csproj index 347a58339..a9f5fa142 100644 --- a/src/Greenshot.Plugin.Office/Greenshot.Plugin.Office.csproj +++ b/src/Greenshot.Plugin.Office/Greenshot.Plugin.Office.csproj @@ -102,6 +102,14 @@ True runtime + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + True runtime @@ -112,4 +120,11 @@ + + + all + runtime; build; native; contentfiles; analyzers + + + diff --git a/src/Greenshot.Plugin.Photobucket/Greenshot.Plugin.Photobucket.csproj b/src/Greenshot.Plugin.Photobucket/Greenshot.Plugin.Photobucket.csproj index 50e39b62a..9b51c94f8 100644 --- a/src/Greenshot.Plugin.Photobucket/Greenshot.Plugin.Photobucket.csproj +++ b/src/Greenshot.Plugin.Photobucket/Greenshot.Plugin.Photobucket.csproj @@ -4,8 +4,25 @@ PreserveNewest + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers + + diff --git a/src/Greenshot.Plugin.Win10/Greenshot.Plugin.Win10.csproj b/src/Greenshot.Plugin.Win10/Greenshot.Plugin.Win10.csproj index c1c1729e0..aac32724d 100644 --- a/src/Greenshot.Plugin.Win10/Greenshot.Plugin.Win10.csproj +++ b/src/Greenshot.Plugin.Win10/Greenshot.Plugin.Win10.csproj @@ -7,9 +7,23 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + all + runtime; build; native; contentfiles; analyzers + + diff --git a/src/Greenshot/Greenshot.csproj b/src/Greenshot/Greenshot.csproj index fc4dd90d1..41ad0af6c 100644 --- a/src/Greenshot/Greenshot.csproj +++ b/src/Greenshot/Greenshot.csproj @@ -17,6 +17,14 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -47,6 +55,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers + From 6721fac9b32c64da9ef28e78cde96f6974340c07 Mon Sep 17 00:00:00 2001 From: Michael Adams Date: Thu, 14 Jul 2022 12:48:45 -0700 Subject: [PATCH 2/5] Refined linting rules --- src/.editorconfig | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/.editorconfig b/src/.editorconfig index 599fc2144..26c4b4cb2 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -86,6 +86,15 @@ csharp_style_prefer_method_group_conversion = true:silent csharp_style_prefer_top_level_statements = true:silent csharp_style_expression_bodied_lambdas = true:silent csharp_style_expression_bodied_local_functions = false:silent +dotnet_diagnostic.S125.severity = silent +dotnet_diagnostic.RCS1075.severity = suggestion +dotnet_diagnostic.S1075.severity = suggestion +dotnet_diagnostic.S112.severity = suggestion +dotnet_diagnostic.S4136.severity = silent + +# IDE1006: Naming Styles +dotnet_diagnostic.IDE1006.severity = none + [*.{cs,vb}] #### Naming styles #### From ab75c506cda04d667d555b1ce1e62bcee4f3181e Mon Sep 17 00:00:00 2001 From: Michael Adams Date: Thu, 14 Jul 2022 13:16:36 -0700 Subject: [PATCH 3/5] Deal with suggested fixes --- src/.editorconfig | 2 +- src/Greenshot.Base/Controls/AnimatingForm.cs | 7 +- src/Greenshot.Base/Controls/BackgroundForm.cs | 2 +- .../Controls/ExtendedWebBrowser.cs | 4 +- .../Controls/GreenshotColumnSorter.cs | 36 +-- .../Controls/GreenshotComboBox.cs | 4 +- src/Greenshot.Base/Controls/GreenshotForm.cs | 46 +-- src/Greenshot.Base/Controls/HotkeyControl.cs | 66 ++-- .../Controls/SaveImageFileDialog.cs | 6 +- src/Greenshot.Base/Controls/ThumbnailForm.cs | 4 +- .../Core/AbstractDestination.cs | 34 +- src/Greenshot.Base/Core/AbstractProcessor.cs | 11 +- src/Greenshot.Base/Core/AccessibleHelper.cs | 13 +- src/Greenshot.Base/Core/AnimationHelpers.cs | 71 ++--- src/Greenshot.Base/Core/BinaryStructHelper.cs | 2 +- src/Greenshot.Base/Core/Cache.cs | 8 +- src/Greenshot.Base/Core/Capture.cs | 24 +- src/Greenshot.Base/Core/CaptureDetails.cs | 9 +- src/Greenshot.Base/Core/ClipboardHelper.cs | 77 ++--- src/Greenshot.Base/Core/CoreConfiguration.cs | 16 +- src/Greenshot.Base/Core/CredentialsHelper.cs | 6 +- src/Greenshot.Base/Core/DestinationHelper.cs | 10 +- src/Greenshot.Base/Core/EffectConverter.cs | 33 +- src/Greenshot.Base/Core/EnvironmentInfo.cs | 38 +-- src/Greenshot.Base/Core/FastBitmap.cs | 40 +-- .../Core/FileDescriptorReader.cs | 20 +- .../FileFormatHandlerExtensions.cs | 13 +- src/Greenshot.Base/Core/FilenameHelper.cs | 31 +- src/Greenshot.Base/Core/Fraction.cs | 26 +- src/Greenshot.Base/Core/GreenshotResources.cs | 6 +- src/Greenshot.Base/Core/IEHelper.cs | 13 +- src/Greenshot.Base/Core/ImageHelper.cs | 134 ++++---- src/Greenshot.Base/Core/ImageIO.cs | 32 +- src/Greenshot.Base/Core/JSONHelper.cs | 18 +- src/Greenshot.Base/Core/Language.cs | 69 +---- src/Greenshot.Base/Core/LanguageFile.cs | 2 +- src/Greenshot.Base/Core/LogHelper.cs | 9 +- src/Greenshot.Base/Core/NetworkHelper.cs | 23 +- .../Core/OAuth/LocalJsonReceiver.cs | 6 +- .../Core/OAuth/LocalServerCodeReceiver.cs | 15 +- src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs | 24 +- src/Greenshot.Base/Core/OAuth/OAuthSession.cs | 42 +-- src/Greenshot.Base/Core/ObjectExtensions.cs | 2 +- src/Greenshot.Base/Core/PluginUtils.cs | 2 +- src/Greenshot.Base/Core/QuantizerHelper.cs | 64 ++-- .../Core/RegistryKeyExtensions.cs | 6 +- .../Core/SimpleServiceProvider.cs | 7 +- src/Greenshot.Base/Core/StringExtensions.cs | 17 +- src/Greenshot.Base/Core/WindowCapture.cs | 8 +- src/Greenshot.Base/Core/WindowDetails.cs | 120 +++----- src/Greenshot.Base/Core/WindowsVersion.cs | 4 +- .../Core/WmInputLangChangeRequestFilter.cs | 2 +- .../Effects/ReduceColorsEffect.cs | 2 +- src/Greenshot.Base/Help/HelpFileLoader.cs | 6 +- .../IEInterop/IHTMLDocument2.cs | 3 +- .../IEInterop/IHTMLFrameBase.cs | 82 ++--- src/Greenshot.Base/IEInterop/IHTMLStyle.cs | 243 ++++++++++----- src/Greenshot.Base/IEInterop/IHTMLTxtRange.cs | 3 +- src/Greenshot.Base/IEInterop/IWebBrowser2.cs | 20 +- src/Greenshot.Base/IniFile/IniConfig.cs | 28 +- src/Greenshot.Base/IniFile/IniSection.cs | 15 +- src/Greenshot.Base/IniFile/IniValue.cs | 109 +++---- .../Interfaces/ICaptureHelper.cs | 2 +- .../Interfaces/IFileFormatHandler.cs | 2 +- .../Interfaces/Ocr/OcrInformation.cs | 2 +- .../Plugin/SurfaceOutputSettings.cs | 7 +- .../SurfaceBackgroundColorEventHandler.cs | 2 +- .../SurfaceForegroundColorEventHandler.cs | 2 +- .../SurfaceLineThicknessEventHandler.cs | 2 +- .../Interfaces/SurfaceShadowEventHandler.cs | 2 +- src/Greenshot.Base/Interop/COMWrapper.cs | 91 +++--- .../Interop/ComProgIdAttribute.cs | 13 +- .../Configuration/EditorConfiguration.cs | 10 +- .../BindableToolStripDropDownButton.cs | 6 +- .../Controls/FontFamilyComboBox.cs | 10 +- src/Greenshot.Editor/Controls/MenuStripEx.cs | 15 +- src/Greenshot.Editor/Controls/Pipette.cs | 13 +- src/Greenshot.Editor/Controls/ToolStripEx.cs | 14 +- .../Controls/ToolStripNumericUpDown.cs | 1 - .../Destinations/EditorDestination.cs | 13 +- .../Drawing/Adorners/AbstractAdorner.cs | 2 +- .../Drawing/Adorners/TargetAdorner.cs | 4 +- .../Drawing/ArrowContainer.cs | 28 +- src/Greenshot.Editor/Drawing/CropContainer.cs | 12 +- .../Drawing/CursorContainer.cs | 12 +- .../Drawing/DrawableContainer.cs | 22 +- .../Drawing/DrawableContainerList.cs | 123 ++++---- .../Drawing/EllipseContainer.cs | 18 +- .../Drawing/Fields/AbstractFieldHolder.cs | 3 +- .../Fields/AbstractFieldHolderWithChildren.cs | 11 +- .../Binding/AbstractBindingConverter.cs | 20 +- .../Fields/Binding/BidirectionalBinding.cs | 19 +- src/Greenshot.Editor/Drawing/Fields/Field.cs | 7 +- .../Drawing/Fields/FieldAggregator.cs | 10 +- .../Drawing/Fields/FieldType.cs | 8 +- .../Drawing/FilterContainer.cs | 10 +- .../Drawing/Filters/AbstractFilter.cs | 2 +- .../Drawing/Filters/GrayscaleFilter.cs | 4 +- .../Drawing/Filters/MagnifierFilter.cs | 2 +- .../Drawing/Filters/PixelizationFilter.cs | 2 +- .../Drawing/FreehandContainer.cs | 21 +- .../Drawing/HighlightContainer.cs | 2 +- src/Greenshot.Editor/Drawing/IconContainer.cs | 6 +- .../Drawing/ImageContainer.cs | 3 +- src/Greenshot.Editor/Drawing/LineContainer.cs | 13 +- .../Drawing/MetafileContainer.cs | 12 +- .../Drawing/ObfuscateContainer.cs | 2 +- src/Greenshot.Editor/Drawing/Positions.cs | 2 +- .../Drawing/RectangleContainer.cs | 13 +- .../Drawing/SpeechbubbleContainer.cs | 39 ++- .../Drawing/StepLabelContainer.cs | 36 +-- src/Greenshot.Editor/Drawing/Surface.cs | 291 ++++++++---------- src/Greenshot.Editor/Drawing/SvgContainer.cs | 6 +- src/Greenshot.Editor/Drawing/TextContainer.cs | 24 +- .../Drawing/VectorGraphicsContainer.cs | 11 +- .../AbstractFileFormatHandler.cs | 2 +- .../DefaultFileFormatHandler.cs | 2 +- .../DibFileFormatHandler.cs | 6 +- .../GreenshotFileFormatHandler.cs | 8 +- .../IconFileFormatHandler.cs | 12 +- .../MetaFileFormatHandler.cs | 2 +- .../WpfFileFormatHandler.cs | 4 +- src/Greenshot.Editor/Forms/ColorDialog.cs | 12 +- .../Forms/ColorPickerToolStripButton.cs | 5 +- .../Forms/DropShadowSettingsForm.cs | 8 +- src/Greenshot.Editor/Forms/ImageEditorForm.cs | 112 +++---- .../Forms/MovableShowColorForm.cs | 2 +- .../Forms/ResizeSettingsForm.cs | 10 +- .../Forms/TornEdgeSettingsForm.cs | 15 +- src/Greenshot.Editor/Helpers/Colors.cs | 7 +- .../Helpers/GeometryHelper.cs | 2 +- src/Greenshot.Editor/Helpers/ScaleHelper.cs | 36 +-- .../Helpers/ShapeAngleRoundBehavior.cs | 2 +- .../Helpers/ToolStripItemEndisabler.cs | 4 +- .../Memento/AddElementMemento.cs | 2 +- .../Memento/ChangeFieldHolderMemento.cs | 6 +- .../Memento/SurfaceBackgroundChangeMemento.cs | 2 +- .../Memento/TextChangeMemento.cs | 6 +- src/Greenshot.Plugin.Box/BoxConfiguration.cs | 7 +- src/Greenshot.Plugin.Box/BoxDestination.cs | 6 +- src/Greenshot.Plugin.Box/BoxPlugin.cs | 6 +- src/Greenshot.Plugin.Box/BoxUtils.cs | 3 +- src/Greenshot.Plugin.Confluence/Confluence.cs | 2 +- .../ConfluenceDestination.cs | 21 +- .../ConfluencePlugin.cs | 4 +- .../ConfluenceUtils.cs | 12 +- .../EnumDisplayer.cs | 10 +- .../Forms/ConfluencePagePicker.xaml.cs | 2 +- .../Forms/ConfluenceSearch.xaml.cs | 4 +- .../Forms/ConfluenceTreePicker.xaml.cs | 10 +- .../Forms/ConfluenceUpload.xaml.cs | 6 +- .../Support/LanguageChangedEventManager.cs | 6 +- .../Support/LanguageXMLTranslationProvider.cs | 9 +- .../Support/TranslateExtension.cs | 12 +- .../Support/TranslationManager.cs | 7 +- .../DropboxConfiguration.cs | 7 +- .../DropboxDestination.cs | 6 +- src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs | 4 +- src/Greenshot.Plugin.Dropbox/DropboxUtils.cs | 2 +- .../ExternalCommandConfiguration.cs | 2 +- .../ExternalCommandDestination.cs | 10 +- .../SettingsForm.cs | 16 +- .../FlickrConfiguration.cs | 8 +- .../FlickrDestination.cs | 6 +- src/Greenshot.Plugin.Flickr/FlickrPlugin.cs | 4 +- src/Greenshot.Plugin.Flickr/FlickrUtils.cs | 4 +- .../GooglePhotosConfiguration.cs | 7 +- .../GooglePhotosDestination.cs | 6 +- .../GooglePhotosPlugin.cs | 4 +- .../GooglePhotosUtils.cs | 6 +- .../Forms/ImgurHistory.cs | 13 +- .../ImgurConfiguration.cs | 4 +- .../ImgurDestination.cs | 6 +- src/Greenshot.Plugin.Imgur/ImgurInfo.cs | 4 +- src/Greenshot.Plugin.Imgur/ImgurPlugin.cs | 8 +- src/Greenshot.Plugin.Imgur/ImgurUtils.cs | 19 +- src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs | 6 +- src/Greenshot.Plugin.Jira/Forms/JiraForm.cs | 4 +- src/Greenshot.Plugin.Jira/JiraDestination.cs | 8 +- src/Greenshot.Plugin.Jira/JiraMonitor.cs | 14 +- src/Greenshot.Plugin.Jira/JiraPlugin.cs | 9 +- src/Greenshot.Plugin.Jira/Log4NetLogger.cs | 23 +- .../Com/DisposableCom.cs | 7 +- src/Greenshot.Plugin.Office/Com/Ole32Api.cs | 9 +- .../Com/OleAut32Api.cs | 7 +- .../Destinations/ExcelDestination.cs | 2 +- .../Destinations/OneNoteDestination.cs | 13 +- .../Destinations/OutlookDestination.cs | 12 +- .../Destinations/PowerpointDestination.cs | 22 +- .../Destinations/WordDestination.cs | 6 +- .../OfficeExport/Entities/OneNotePage.cs | 9 +- .../OfficeExport/ExcelExporter.cs | 10 +- .../OfficeExport/OneNoteExporter.cs | 33 +- .../OfficeExport/OutlookEmailExporter.cs | 55 ++-- .../OfficeExport/PowerpointExporter.cs | 10 +- .../OfficeExport/WordExporter.cs | 8 +- src/Greenshot.Plugin.Office/OfficePlugin.cs | 1 - .../PhotobucketConfiguration.cs | 7 +- .../PhotobucketDestination.cs | 13 +- .../PhotobucketInfo.cs | 4 +- .../PhotobucketPlugin.cs | 4 +- .../PhotobucketUtils.cs | 6 +- .../Properties/AssemblyInfo.cs | 1 - .../Destinations/Win10ShareDestination.cs | 2 +- .../Internal/MemoryRandomAccessStream.cs | 12 +- .../Native/DataTransferManagerHelper.cs | 2 +- .../ToastNotificationService.cs | 9 +- .../Win10OcrProvider.cs | 4 +- ...ontextMenuToolStripProfessionalRenderer.cs | 2 +- .../Destinations/ClipboardDestination.cs | 2 +- .../Destinations/EmailDestination.cs | 2 +- .../Destinations/FileWithDialogDestination.cs | 3 +- .../Destinations/PickerDestination.cs | 3 +- .../Destinations/PrinterDestination.cs | 32 +- src/Greenshot/Forms/AboutForm.cs | 18 +- src/Greenshot/Forms/BugReportForm.cs | 2 +- src/Greenshot/Forms/CaptureForm.cs | 97 +++--- src/Greenshot/Forms/MainForm.cs | 139 ++++----- src/Greenshot/Forms/PrintOptionsDialog.cs | 1 - src/Greenshot/Forms/SettingsForm.cs | 49 ++- .../Forms/ToolStripMenuSelectList.cs | 6 +- src/Greenshot/Helpers/CaptureHelper.cs | 82 +++-- src/Greenshot/Helpers/CopyData.cs | 42 ++- src/Greenshot/Helpers/IECaptureHelper.cs | 31 +- .../Helpers/IEInterop/IEContainer.cs | 116 +++---- src/Greenshot/Helpers/MailHelper.cs | 14 +- .../Helpers/NotifyIconNotificationService.cs | 2 +- src/Greenshot/Helpers/PluginHelper.cs | 11 +- src/Greenshot/Helpers/PrintHelper.cs | 24 +- src/Greenshot/Helpers/SoundHelper.cs | 8 +- src/Greenshot/Helpers/UpdateService.cs | 7 +- src/Greenshot/Processors/TitleFixProcessor.cs | 4 +- 232 files changed, 1875 insertions(+), 2496 deletions(-) diff --git a/src/.editorconfig b/src/.editorconfig index 26c4b4cb2..ecc46e465 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -89,7 +89,7 @@ csharp_style_expression_bodied_local_functions = false:silent dotnet_diagnostic.S125.severity = silent dotnet_diagnostic.RCS1075.severity = suggestion dotnet_diagnostic.S1075.severity = suggestion -dotnet_diagnostic.S112.severity = suggestion +dotnet_diagnostic.S112.severity = silent dotnet_diagnostic.S4136.severity = silent # IDE1006: Naming Styles diff --git a/src/Greenshot.Base/Controls/AnimatingForm.cs b/src/Greenshot.Base/Controls/AnimatingForm.cs index cde3997ae..44f2389d8 100644 --- a/src/Greenshot.Base/Controls/AnimatingForm.cs +++ b/src/Greenshot.Base/Controls/AnimatingForm.cs @@ -57,12 +57,7 @@ namespace Greenshot.Base.Controls protected int FramesForMillis(int milliseconds) { // If we are in a Terminal Server Session we return 1 - if (IsTerminalServerSession) - { - return 1; - } - - return milliseconds / VRefresh; + return IsTerminalServerSession ? 1 : milliseconds / VRefresh; } /// diff --git a/src/Greenshot.Base/Controls/BackgroundForm.cs b/src/Greenshot.Base/Controls/BackgroundForm.cs index b0ccee3a9..fed465e5e 100644 --- a/src/Greenshot.Base/Controls/BackgroundForm.cs +++ b/src/Greenshot.Base/Controls/BackgroundForm.cs @@ -64,7 +64,7 @@ namespace Greenshot.Base.Controls if (!positioned) { - Location = new Point(Cursor.Position.X - Width / 2, Cursor.Position.Y - Height / 2); + Location = new Point(Cursor.Position.X - (Width / 2), Cursor.Position.Y - (Height / 2)); } } diff --git a/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs b/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs index f53e0b489..05cc4c88a 100644 --- a/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs +++ b/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs @@ -31,10 +31,10 @@ namespace Greenshot.Base.Controls { private const int OLECMDID_SHOWSCRIPTERROR = 40; - private static readonly Guid CGID_DocHostCommandHandler = new Guid("F38BC242-B950-11D1-8918-00C04FC2C836"); + private static readonly Guid CGID_DocHostCommandHandler = new("F38BC242-B950-11D1-8918-00C04FC2C836"); private const int S_OK = 0; - private const int OLECMDERR_E_NOTSUPPORTED = (-2147221248); + private const int OLECMDERR_E_NOTSUPPORTED = -2147221248; public ExtendedWebBrowserSite(WebBrowser wb) : base(wb) { diff --git a/src/Greenshot.Base/Controls/GreenshotColumnSorter.cs b/src/Greenshot.Base/Controls/GreenshotColumnSorter.cs index 77b262105..cd7b00ed5 100644 --- a/src/Greenshot.Base/Controls/GreenshotColumnSorter.cs +++ b/src/Greenshot.Base/Controls/GreenshotColumnSorter.cs @@ -29,16 +29,6 @@ namespace Greenshot.Base.Controls /// public class GreenshotColumnSorter : IComparer { - /// - /// Specifies the column to be sorted - /// - private int _columnToSort; - - /// - /// Specifies the order in which to sort (i.e. 'Ascending'). - /// - private SortOrder _orderOfSort; - /// /// Case insensitive comparer object /// @@ -50,10 +40,10 @@ namespace Greenshot.Base.Controls public GreenshotColumnSorter() { // Initialize the column to '0' - _columnToSort = 0; + SortColumn = 0; // Initialize the sort order to 'none' - _orderOfSort = SortOrder.None; + Order = SortOrder.None; // Initialize the CaseInsensitiveComparer object _objectCompare = new CaseInsensitiveComparer(); @@ -83,20 +73,20 @@ namespace Greenshot.Base.Controls } // Cast the objects to be compared to ListViewItem objects - var listviewX = (ListViewItem) x; - var listviewY = (ListViewItem) y; + var listviewX = (ListViewItem)x; + var listviewY = (ListViewItem)y; // Compare the two items - var compareResult = _objectCompare.Compare(listviewX.SubItems[_columnToSort].Text, listviewY.SubItems[_columnToSort].Text); + var compareResult = _objectCompare.Compare(listviewX.SubItems[SortColumn].Text, listviewY.SubItems[SortColumn].Text); // Calculate correct return value based on object comparison - if (_orderOfSort == SortOrder.Ascending) + if (Order == SortOrder.Ascending) { // Ascending sort is selected, return normal result of compare operation return compareResult; } - if (_orderOfSort == SortOrder.Descending) + if (Order == SortOrder.Descending) { // Descending sort is selected, return negative result of compare operation return -compareResult; @@ -109,19 +99,11 @@ namespace Greenshot.Base.Controls /// /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0'). /// - public int SortColumn - { - set { _columnToSort = value; } - get { return _columnToSort; } - } + public int SortColumn { set; get; } /// /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending'). /// - public SortOrder Order - { - set { _orderOfSort = value; } - get { return _orderOfSort; } - } + public SortOrder Order { set; get; } } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/GreenshotComboBox.cs b/src/Greenshot.Base/Controls/GreenshotComboBox.cs index 88c2e29f5..c82da65f4 100644 --- a/src/Greenshot.Base/Controls/GreenshotComboBox.cs +++ b/src/Greenshot.Base/Controls/GreenshotComboBox.cs @@ -65,7 +65,7 @@ namespace Greenshot.Base.Controls Items.Clear(); foreach (var enumValue in availableValues) { - Items.Add(Language.Translate((Enum) enumValue)); + Items.Add(Language.Translate((Enum)enumValue)); } } @@ -101,7 +101,7 @@ namespace Greenshot.Base.Controls } } - _selectedEnum = (Enum) returnValue; + _selectedEnum = (Enum)returnValue; } /// diff --git a/src/Greenshot.Base/Controls/GreenshotForm.cs b/src/Greenshot.Base/Controls/GreenshotForm.cs index 85bc6bd4d..f8de3d6cd 100644 --- a/src/Greenshot.Base/Controls/GreenshotForm.cs +++ b/src/Greenshot.Base/Controls/GreenshotForm.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ - #if DEBUG using System.ComponentModel; using System.ComponentModel.Design; @@ -48,9 +47,8 @@ namespace Greenshot.Base.Controls private bool _isDesignModeLanguageSet; private IDictionary _designTimeControls; private IDictionary _designTimeToolStripItems; + #endif - private bool _applyLanguageManually; - private bool _storeFieldsManually; static GreenshotForm() { @@ -79,23 +77,15 @@ namespace Greenshot.Base.Controls get { return (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1) || - (Application.ExecutablePath.IndexOf("sharpdevelop.exe", StringComparison.OrdinalIgnoreCase) > -1 || - (Application.ExecutablePath.IndexOf("wdexpress.exe", StringComparison.OrdinalIgnoreCase) > -1)); + Application.ExecutablePath.IndexOf("sharpdevelop.exe", StringComparison.OrdinalIgnoreCase) > -1 || + (Application.ExecutablePath.IndexOf("wdexpress.exe", StringComparison.OrdinalIgnoreCase) > -1); } } #endif - protected bool ManualLanguageApply - { - get { return _applyLanguageManually; } - set { _applyLanguageManually = value; } - } + protected bool ManualLanguageApply { get; set; } - protected bool ManualStoreFields - { - get { return _storeFieldsManually; } - set { _storeFieldsManually = value; } - } + protected bool ManualStoreFields { get; set; } /// /// When this is set, the form will be brought to the foreground as soon as it is shown. @@ -127,14 +117,12 @@ namespace Greenshot.Base.Controls _designTimeToolStripItems = new Dictionary(); try { - ITypeResolutionService typeResService = GetService(typeof(ITypeResolutionService)) as ITypeResolutionService; - // Add a hard-path if you are using SharpDevelop // Language.AddLanguageFilePath(@"C:\Greenshot\Greenshot\Languages"); // this "type" Assembly currentAssembly = GetType().Assembly; - if (typeResService == null) return; + if (GetService(typeof(ITypeResolutionService)) is not ITypeResolutionService typeResService) return; string assemblyPath = typeResService.GetPathOfAssembly(currentAssembly.GetName()); string assemblyDirectory = Path.GetDirectoryName(assemblyPath); @@ -189,7 +177,7 @@ namespace Greenshot.Base.Controls if (!DesignMode) { #endif - if (!_applyLanguageManually) + if (!ManualLanguageApply) { ApplyLanguage(); } @@ -227,7 +215,7 @@ namespace Greenshot.Base.Controls /// protected override void OnClosed(EventArgs e) { - if (!DesignMode && !_storeFieldsManually) + if (!DesignMode && !ManualStoreFields) { if (DialogResult == DialogResult.OK) { @@ -255,7 +243,7 @@ namespace Greenshot.Base.Controls // Set the new Site value. base.Site = value; - m_changeService = (IComponentChangeService) GetService(typeof(IComponentChangeService)); + m_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService)); // Register event handlers for component change events. RegisterChangeNotifications(); @@ -266,7 +254,7 @@ namespace Greenshot.Base.Controls { // The m_changeService value is null when not in design mode, // as the IComponentChangeService is only available at design time. - m_changeService = (IComponentChangeService) GetService(typeof(IComponentChangeService)); + m_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService)); // Clear our the component change events to prepare for re-siting. if (m_changeService != null) @@ -293,19 +281,19 @@ namespace Greenshot.Base.Controls /// private void OnComponentChanged(object sender, ComponentChangedEventArgs ce) { - if (((IComponent) ce.Component)?.Site == null || ce.Member == null) return; + if (((IComponent)ce.Component)?.Site == null || ce.Member == null) return; if (!"LanguageKey".Equals(ce.Member.Name)) return; if (ce.Component is Control control) { LOG.InfoFormat("Changing LanguageKey for {0} to {1}", control.Name, ce.NewValue); - ApplyLanguage(control, (string) ce.NewValue); + ApplyLanguage(control, (string)ce.NewValue); } else { if (ce.Component is ToolStripItem item) { LOG.InfoFormat("Changing LanguageKey for {0} to {1}", item.Name, ce.NewValue); - ApplyLanguage(item, (string) ce.NewValue); + ApplyLanguage(item, (string)ce.NewValue); } else { @@ -556,14 +544,14 @@ namespace Greenshot.Base.Controls if (controlObject is CheckBox checkBox) { - checkBox.Checked = (bool) iniValue.Value; + checkBox.Checked = (bool)iniValue.Value; checkBox.Enabled = !iniValue.IsFixed; continue; } if (controlObject is RadioButton radíoButton) { - radíoButton.Checked = (bool) iniValue.Value; + radíoButton.Checked = (bool)iniValue.Value; radíoButton.Enabled = !iniValue.IsFixed; continue; } @@ -572,7 +560,7 @@ namespace Greenshot.Base.Controls { if (controlObject is HotkeyControl hotkeyControl) { - string hotkeyValue = (string) iniValue.Value; + string hotkeyValue = (string)iniValue.Value; if (!string.IsNullOrEmpty(hotkeyValue)) { hotkeyControl.SetHotkey(hotkeyValue); @@ -590,7 +578,7 @@ namespace Greenshot.Base.Controls if (controlObject is GreenshotComboBox comboxBox) { comboxBox.Populate(iniValue.ValueType); - comboxBox.SetValue((Enum) iniValue.Value); + comboxBox.SetValue((Enum)iniValue.Value); comboxBox.Enabled = !iniValue.IsFixed; } } diff --git a/src/Greenshot.Base/Controls/HotkeyControl.cs b/src/Greenshot.Base/Controls/HotkeyControl.cs index 678b6522e..bb6fa857f 100644 --- a/src/Greenshot.Base/Controls/HotkeyControl.cs +++ b/src/Greenshot.Base/Controls/HotkeyControl.cs @@ -40,7 +40,7 @@ namespace Greenshot.Base.Controls { private static readonly ILog Log = LogManager.GetLogger(typeof(HotkeyControl)); - private static readonly EventDelay EventDelay = new EventDelay(TimeSpan.FromMilliseconds(600).Ticks); + private static readonly EventDelay EventDelay = new(TimeSpan.FromMilliseconds(600).Ticks); private static readonly bool IsWindows7OrOlder = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1; // Holds the list of hotkeys @@ -102,7 +102,7 @@ namespace Greenshot.Base.Controls private readonly IList _needNonShiftModifier = new List(); private readonly IList _needNonAltGrModifier = new List(); - private readonly ContextMenuStrip _dummy = new ContextMenuStrip(); + private readonly ContextMenuStrip _dummy = new(); /// /// Used to make sure that there is no right-click menu available @@ -151,43 +151,43 @@ namespace Greenshot.Base.Controls // Shift + 0 - 9, A - Z for (Keys k = Keys.D0; k <= Keys.Z; k++) { - _needNonShiftModifier.Add((int) k); + _needNonShiftModifier.Add((int)k); } // Shift + Numpad keys for (Keys k = Keys.NumPad0; k <= Keys.NumPad9; k++) { - _needNonShiftModifier.Add((int) k); + _needNonShiftModifier.Add((int)k); } // Shift + Misc (,;<./ etc) for (Keys k = Keys.Oem1; k <= Keys.OemBackslash; k++) { - _needNonShiftModifier.Add((int) k); + _needNonShiftModifier.Add((int)k); } // Shift + Space, PgUp, PgDn, End, Home for (Keys k = Keys.Space; k <= Keys.Home; k++) { - _needNonShiftModifier.Add((int) k); + _needNonShiftModifier.Add((int)k); } // Misc keys that we can't loop through - _needNonShiftModifier.Add((int) Keys.Insert); - _needNonShiftModifier.Add((int) Keys.Help); - _needNonShiftModifier.Add((int) Keys.Multiply); - _needNonShiftModifier.Add((int) Keys.Add); - _needNonShiftModifier.Add((int) Keys.Subtract); - _needNonShiftModifier.Add((int) Keys.Divide); - _needNonShiftModifier.Add((int) Keys.Decimal); - _needNonShiftModifier.Add((int) Keys.Return); - _needNonShiftModifier.Add((int) Keys.Escape); - _needNonShiftModifier.Add((int) Keys.NumLock); + _needNonShiftModifier.Add((int)Keys.Insert); + _needNonShiftModifier.Add((int)Keys.Help); + _needNonShiftModifier.Add((int)Keys.Multiply); + _needNonShiftModifier.Add((int)Keys.Add); + _needNonShiftModifier.Add((int)Keys.Subtract); + _needNonShiftModifier.Add((int)Keys.Divide); + _needNonShiftModifier.Add((int)Keys.Decimal); + _needNonShiftModifier.Add((int)Keys.Return); + _needNonShiftModifier.Add((int)Keys.Escape); + _needNonShiftModifier.Add((int)Keys.NumLock); // Ctrl+Alt + 0 - 9 for (Keys k = Keys.D0; k <= Keys.D9; k++) { - _needNonAltGrModifier.Add((int) k); + _needNonAltGrModifier.Add((int)k); } } @@ -339,12 +339,12 @@ namespace Greenshot.Base.Controls if (bCalledProgramatically == false) { // No modifier or shift only, AND a hotkey that needs another modifier - if ((_modifiers == Keys.Shift || _modifiers == Keys.None) && _needNonShiftModifier.Contains((int) _hotkey)) + if ((_modifiers == Keys.Shift || _modifiers == Keys.None) && _needNonShiftModifier.Contains((int)_hotkey)) { if (_modifiers == Keys.None) { // Set Ctrl+Alt as the modifier unless Ctrl+Alt+ won't work... - if (_needNonAltGrModifier.Contains((int) _hotkey) == false) + if (_needNonAltGrModifier.Contains((int)_hotkey) == false) { _modifiers = Keys.Alt | Keys.Control; } @@ -365,7 +365,7 @@ namespace Greenshot.Base.Controls } // Check all Ctrl+Alt keys - if ((_modifiers == (Keys.Alt | Keys.Control)) && _needNonAltGrModifier.Contains((int) _hotkey)) + if ((_modifiers == (Keys.Alt | Keys.Control)) && _needNonAltGrModifier.Contains((int)_hotkey)) { // Ctrl+Alt+4 etc won't work; reset hotkey and tell the user _hotkey = Keys.None; @@ -403,7 +403,7 @@ namespace Greenshot.Base.Controls public static string HotkeyModifiersToString(Keys modifierKeyCode) { - StringBuilder hotkeyString = new StringBuilder(); + StringBuilder hotkeyString = new(); if ((modifierKeyCode & Keys.Alt) > 0) { hotkeyString.Append("Alt").Append(" + "); @@ -427,7 +427,6 @@ namespace Greenshot.Base.Controls return hotkeyString.ToString(); } - public static string HotkeyToLocalizedString(Keys modifierKeyCode, Keys virtualKeyCode) { return HotkeyModifiersToLocalizedString(modifierKeyCode) + GetKeyName(virtualKeyCode); @@ -435,7 +434,7 @@ namespace Greenshot.Base.Controls public static string HotkeyModifiersToLocalizedString(Keys modifierKeyCode) { - StringBuilder hotkeyString = new StringBuilder(); + StringBuilder hotkeyString = new(); if ((modifierKeyCode & Keys.Alt) > 0) { hotkeyString.Append(GetKeyName(Keys.Alt)).Append(" + "); @@ -459,7 +458,6 @@ namespace Greenshot.Base.Controls return hotkeyString.ToString(); } - public static Keys HotkeyModifiersFromString(string modifiersString) { Keys modifiers = Keys.None; @@ -499,7 +497,7 @@ namespace Greenshot.Base.Controls hotkey = hotkey.Remove(0, hotkey.LastIndexOf('+') + 1).Trim(); } - key = (Keys) Enum.Parse(typeof(Keys), hotkey); + key = (Keys)Enum.Parse(typeof(Keys), hotkey); } return key; @@ -529,31 +527,31 @@ namespace Greenshot.Base.Controls uint modifiers = 0; if ((modifierKeyCode & Keys.Alt) > 0) { - modifiers |= (uint) Modifiers.ALT; + modifiers |= (uint)Modifiers.ALT; } if ((modifierKeyCode & Keys.Control) > 0) { - modifiers |= (uint) Modifiers.CTRL; + modifiers |= (uint)Modifiers.CTRL; } if ((modifierKeyCode & Keys.Shift) > 0) { - modifiers |= (uint) Modifiers.SHIFT; + modifiers |= (uint)Modifiers.SHIFT; } if (modifierKeyCode == Keys.LWin || modifierKeyCode == Keys.RWin) { - modifiers |= (uint) Modifiers.WIN; + modifiers |= (uint)Modifiers.WIN; } // Disable repeating hotkey for Windows 7 and beyond, as described in #1559 if (IsWindows7OrOlder) { - modifiers |= (uint) Modifiers.NO_REPEAT; + modifiers |= (uint)Modifiers.NO_REPEAT; } - if (RegisterHotKey(_hotkeyHwnd, _hotKeyCounter, modifiers, (uint) virtualKeyCode)) + if (RegisterHotKey(_hotkeyHwnd, _hotKeyCounter, modifiers, (uint)virtualKeyCode)) { KeyHandlers.Add(_hotKeyCounter, handler); return _hotKeyCounter++; @@ -592,7 +590,7 @@ namespace Greenshot.Base.Controls return true; } - if (KeyHandlers.TryGetValue((int) m.WParam, out var handler)) + if (KeyHandlers.TryGetValue((int)m.WParam, out var handler)) { handler(); } @@ -602,7 +600,7 @@ namespace Greenshot.Base.Controls public static string GetKeyName(Keys givenKey) { - StringBuilder keyName = new StringBuilder(); + StringBuilder keyName = new(); const uint numpad = 55; Keys virtualKey = givenKey; @@ -641,7 +639,7 @@ namespace Greenshot.Base.Controls return keyString + " /"; } - uint scanCode = MapVirtualKey((uint) virtualKey, (uint) MapType.MAPVK_VK_TO_VSC); + uint scanCode = MapVirtualKey((uint)virtualKey, (uint)MapType.MAPVK_VK_TO_VSC); // because MapVirtualKey strips the extended bit for some keys switch (virtualKey) diff --git a/src/Greenshot.Base/Controls/SaveImageFileDialog.cs b/src/Greenshot.Base/Controls/SaveImageFileDialog.cs index 091152d64..0f3052bcf 100644 --- a/src/Greenshot.Base/Controls/SaveImageFileDialog.cs +++ b/src/Greenshot.Base/Controls/SaveImageFileDialog.cs @@ -121,13 +121,13 @@ namespace Greenshot.Base.Controls private void PrepareFilterOptions() { // TODO: Change to the FileFormatHandlerRegistry to look for all the supported extensions - OutputFormat[] supportedImageFormats = (OutputFormat[]) Enum.GetValues(typeof(OutputFormat)); + OutputFormat[] supportedImageFormats = (OutputFormat[])Enum.GetValues(typeof(OutputFormat)); _filterOptions = new FilterOption[supportedImageFormats.Length]; for (int i = 0; i < _filterOptions.Length; i++) { string ifo = supportedImageFormats[i].ToString(); if (ifo.ToLower().Equals("jpeg")) ifo = "Jpg"; // we dont want no jpeg files, so let the dialog check for jpg - FilterOption fo = new FilterOption + FilterOption fo = new() { Label = ifo.ToUpper(), Extension = ifo.ToLower() @@ -221,7 +221,7 @@ namespace Greenshot.Base.Controls // fix for bug #3379053 try { - if (_eagerlyCreatedDirectory != null && _eagerlyCreatedDirectory.GetFiles().Length == 0 && _eagerlyCreatedDirectory.GetDirectories().Length == 0) + if (_eagerlyCreatedDirectory?.GetFiles().Length == 0 && _eagerlyCreatedDirectory.GetDirectories().Length == 0) { _eagerlyCreatedDirectory.Delete(); _eagerlyCreatedDirectory = null; diff --git a/src/Greenshot.Base/Controls/ThumbnailForm.cs b/src/Greenshot.Base/Controls/ThumbnailForm.cs index d5b8c50e8..a79e5fb8b 100644 --- a/src/Greenshot.Base/Controls/ThumbnailForm.cs +++ b/src/Greenshot.Base/Controls/ThumbnailForm.cs @@ -103,11 +103,11 @@ namespace Greenshot.Base.Controls } int thumbnailHeight = 200; - int thumbnailWidth = (int) (thumbnailHeight * (sourceSize.Width / (float) sourceSize.Height)); + int thumbnailWidth = (int)(thumbnailHeight * (sourceSize.Width / (float)sourceSize.Height)); if (parentControl != null && thumbnailWidth > parentControl.Width) { thumbnailWidth = parentControl.Width; - thumbnailHeight = (int) (thumbnailWidth * (sourceSize.Height / (float) sourceSize.Width)); + thumbnailHeight = (int)(thumbnailWidth * (sourceSize.Height / (float)sourceSize.Width)); } Width = thumbnailWidth; diff --git a/src/Greenshot.Base/Core/AbstractDestination.cs b/src/Greenshot.Base/Core/AbstractDestination.cs index c76574bab..803e6a783 100644 --- a/src/Greenshot.Base/Core/AbstractDestination.cs +++ b/src/Greenshot.Base/Core/AbstractDestination.cs @@ -49,12 +49,9 @@ namespace Greenshot.Base.Core return 1; } - if (Priority == other.Priority) - { - return string.Compare(Description, other.Description, StringComparison.Ordinal); - } - - return Priority - other.Priority; + return Priority == other.Priority + ? string.CompareOrdinal(Description, other.Description) + : Priority - other.Priority; } public abstract string Designation { get; } @@ -93,12 +90,7 @@ namespace Greenshot.Base.Core { get { - if (CoreConfig.ExcludeDestinations != null && CoreConfig.ExcludeDestinations.Contains(Designation)) - { - return false; - } - - return true; + return (CoreConfig.ExcludeDestinations?.Contains(Designation)) != true; } } @@ -111,7 +103,7 @@ namespace Greenshot.Base.Core /// public void ProcessExport(ExportInformation exportInformation, ISurface surface) { - if (exportInformation != null && exportInformation.ExportMade) + if (exportInformation?.ExportMade == true) { if (!string.IsNullOrEmpty(exportInformation.Uri)) { @@ -176,7 +168,7 @@ namespace Greenshot.Base.Core public ExportInformation ShowPickerMenu(bool addDynamics, ISurface surface, ICaptureDetails captureDetails, IEnumerable destinations) { // Generate an empty ExportInformation object, for when nothing was selected. - ExportInformation exportInformation = new ExportInformation(Designation, Language.GetString("settings_destination_picker")); + ExportInformation exportInformation = new(Designation, Language.GetString("settings_destination_picker")); var menu = new ContextMenuStrip { ImageScalingSize = CoreConfig.IconSize, @@ -196,7 +188,7 @@ namespace Greenshot.Base.Core menu.ResumeLayout(); }; - menu.Closing += delegate(object source, ToolStripDropDownClosingEventArgs eventArgs) + menu.Closing += delegate (object source, ToolStripDropDownClosingEventArgs eventArgs) { Log.DebugFormat("Close reason: {0}", eventArgs.CloseReason); switch (eventArgs.CloseReason) @@ -243,10 +235,10 @@ namespace Greenshot.Base.Core { // Fix foreach loop variable for the delegate ToolStripMenuItem item = destination.GetMenuItem(addDynamics, menu, - delegate(object sender, EventArgs e) + delegate (object sender, EventArgs e) { ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem; - IDestination clickedDestination = (IDestination) toolStripMenuItem?.Tag; + IDestination clickedDestination = (IDestination)toolStripMenuItem?.Tag; if (clickedDestination == null) { return; @@ -255,7 +247,7 @@ namespace Greenshot.Base.Core menu.Tag = clickedDestination.Designation; // Export exportInformation = clickedDestination.ExportCapture(true, surface, captureDetails); - if (exportInformation != null && exportInformation.ExportMade) + if (exportInformation?.ExportMade == true) { Log.InfoFormat("Export to {0} success, closing menu", exportInformation.DestinationDescription); // close menu if the destination wasn't the editor @@ -288,7 +280,7 @@ namespace Greenshot.Base.Core // Close menu.Items.Add(new ToolStripSeparator()); - ToolStripMenuItem closeItem = new ToolStripMenuItem(Language.GetString("editor_close")) + ToolStripMenuItem closeItem = new(Language.GetString("editor_close")) { Image = GreenshotResources.GetImage("Close.Image") }; @@ -307,7 +299,7 @@ namespace Greenshot.Base.Core ShowMenuAtCursor(menu); return exportInformation; } - + /// /// This method will show the supplied context menu at the mouse cursor, also makes sure it has focus and it's not visible in the taskbar. /// @@ -374,7 +366,7 @@ namespace Greenshot.Base.Core { if (basisMenuItem.DropDownItems.Count == 0) { - List subDestinations = new List(); + List subDestinations = new(); // Fixing Bug #3536968 by catching the COMException (every exception) and not displaying the "subDestinations" try { diff --git a/src/Greenshot.Base/Core/AbstractProcessor.cs b/src/Greenshot.Base/Core/AbstractProcessor.cs index bbffae8f3..20c4d0670 100644 --- a/src/Greenshot.Base/Core/AbstractProcessor.cs +++ b/src/Greenshot.Base/Core/AbstractProcessor.cs @@ -31,17 +31,14 @@ namespace Greenshot.Base.Core { public virtual int CompareTo(object obj) { - if (!(obj is IProcessor other)) + if (obj is not IProcessor other) { return 1; } - if (Priority == other.Priority) - { - return string.Compare(Description, other.Description, StringComparison.Ordinal); - } - - return Priority - other.Priority; + return Priority == other.Priority + ? string.CompareOrdinal(Description, other.Description) + : Priority - other.Priority; } public abstract string Designation { get; } diff --git a/src/Greenshot.Base/Core/AccessibleHelper.cs b/src/Greenshot.Base/Core/AccessibleHelper.cs index 08c40956e..1b26fffb1 100644 --- a/src/Greenshot.Base/Core/AccessibleHelper.cs +++ b/src/Greenshot.Base/Core/AccessibleHelper.cs @@ -37,8 +37,8 @@ namespace Greenshot.Base.Core { var guid = new Guid("{618736e0-3c3d-11cf-810c-00aa00389b71}"); // IAccessible object obj = null; - int num = AccessibleObjectFromWindow(hWnd, (uint) idObject, ref guid, ref obj); - acc = (IAccessible) obj; + int num = AccessibleObjectFromWindow(hWnd, (uint)idObject, ref guid, ref obj); + acc = (IAccessible)obj; return num; } @@ -67,13 +67,13 @@ namespace Greenshot.Base.Core { get { - object[] res = GetAccessibleChildren(accessible, out var num); + object[] res = GetAccessibleChildren(accessible, out _); if (res == null) { return new Accessible[0]; } - List list = new List(res.Length); + List list = new(res.Length); foreach (object obj in res) { if (obj is IAccessible acc) @@ -143,7 +143,7 @@ namespace Greenshot.Base.Core { object tabIndex = tab.accessible.get_accState(0); - if ((int) tabIndex == IE_ACTIVE_TAB) + if ((int)tabIndex == IE_ACTIVE_TAB) { return tab.Name; } @@ -182,7 +182,6 @@ namespace Greenshot.Base.Core } } - public IEnumerable IETabUrls { get @@ -193,7 +192,7 @@ namespace Greenshot.Base.Core { foreach (var tab in child.Children) { - object tabIndex = tab.accessible.get_accState(CHILDID_SELF); + _ = tab.accessible.get_accState(CHILDID_SELF); var description = tab.accessible.get_accDescription(CHILDID_SELF); if (!string.IsNullOrEmpty(description)) { diff --git a/src/Greenshot.Base/Core/AnimationHelpers.cs b/src/Greenshot.Base/Core/AnimationHelpers.cs index fd693683f..0fbbe9469 100644 --- a/src/Greenshot.Base/Core/AnimationHelpers.cs +++ b/src/Greenshot.Base/Core/AnimationHelpers.cs @@ -67,7 +67,7 @@ namespace Greenshot.Base.Core /// Type for the animation, like Point/Rectangle/Size public abstract class AnimatorBase : IAnimator { - private readonly Queue> _queue = new Queue>(); + private readonly Queue> _queue = new(); /// /// Constructor @@ -77,7 +77,7 @@ namespace Greenshot.Base.Core /// /// /// - public AnimatorBase(T first, T last, int frames, EasingType easingType, EasingMode easingMode) + protected AnimatorBase(T first, T last, int frames, EasingType easingType, EasingMode easingMode) { First = first; Last = last; @@ -114,12 +114,7 @@ namespace Greenshot.Base.Core { get { - if (_queue.Count == 0) - { - return Last; - } - - return _queue.ToArray()[_queue.Count - 1].Destination; + return _queue.Count == 0 ? Last : _queue.ToArray()[_queue.Count - 1].Destination; } } @@ -186,7 +181,7 @@ namespace Greenshot.Base.Core /// public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType, EasingMode easingMode) { - AnimationLeg leg = new AnimationLeg + AnimationLeg leg = new() { Destination = queuedDestination, Frames = frames, @@ -214,10 +209,10 @@ namespace Greenshot.Base.Core 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) }; } @@ -239,7 +234,7 @@ namespace Greenshot.Base.Core return true; } - if (_queue.Count <= 0) + if (_queue.Count == 0) { return false; } @@ -251,7 +246,6 @@ namespace Greenshot.Base.Core EasingType = nextLeg.EasingType; EasingMode = nextLeg.EasingMode; return true; - } } @@ -262,12 +256,7 @@ namespace Greenshot.Base.Core { get { - if (CurrentFrameNr < Frames) - { - return true; - } - - return _queue.Count > 0; + return CurrentFrameNr < Frames || _queue.Count > 0; } } @@ -312,12 +301,12 @@ namespace Greenshot.Base.Core double dx = Last.X - First.X; double dy = Last.Y - First.Y; - int x = First.X + (int) (easingValue * dx); - int y = First.Y + (int) (easingValue * dy); + int x = First.X + (int)(easingValue * dx); + int y = First.Y + (int)(easingValue * dy); double dw = Last.Width - First.Width; double dh = Last.Height - First.Height; - int width = First.Width + (int) (easingValue * dw); - int height = First.Height + (int) (easingValue * dh); + int width = First.Width + (int)(easingValue * dw); + int height = First.Height + (int)(easingValue * dh); Current = new NativeRect(x, y, width, height); return Current; @@ -356,8 +345,8 @@ namespace Greenshot.Base.Core double dx = Last.X - First.X; double dy = Last.Y - First.Y; - int x = First.X + (int) (easingValue * dx); - int y = First.Y + (int) (easingValue * dy); + int x = First.X + (int)(easingValue * dx); + int y = First.Y + (int)(easingValue * dy); Current = new NativePoint(x, y); } @@ -396,8 +385,8 @@ namespace Greenshot.Base.Core double easingValue = EasingValue; double dw = Last.Width - First.Width; double dh = Last.Height - First.Height; - int width = First.Width + (int) (easingValue * dw); - int height = First.Height + (int) (easingValue * dh); + int width = First.Width + (int)(easingValue * dw); + int height = First.Height + (int)(easingValue * dh); Current = new NativeSize(width, height); } @@ -438,10 +427,10 @@ namespace Greenshot.Base.Core double dr = Last.R - First.R; double dg = Last.G - First.G; double db = Last.B - First.B; - int a = First.A + (int) (easingValue * da); - int r = First.R + (int) (easingValue * dr); - int g = First.G + (int) (easingValue * dg); - int b = First.B + (int) (easingValue * db); + int a = First.A + (int)(easingValue * da); + int r = First.R + (int)(easingValue * dr); + int g = First.G + (int)(easingValue * dg); + int b = First.B + (int)(easingValue * db); Current = Color.FromArgb(a, r, g, b); } @@ -479,7 +468,7 @@ namespace Greenshot.Base.Core { double easingValue = EasingValue; double delta = Last - First; - Current = First + (int) (easingValue * delta); + Current = First + (int)(easingValue * delta); } return Current; @@ -497,13 +486,13 @@ namespace Greenshot.Base.Core { double easedStep = acceleration > 0 ? EaseIn(linearStep, type) : acceleration < 0 ? EaseOut(linearStep, type) : linearStep; // Lerp: - return ((easedStep - linearStep) * Math.Abs(acceleration) + linearStep); + return ((easedStep - linearStep) * Math.Abs(acceleration)) + linearStep; } public static double EaseIn(double linearStep, EasingType type) => type switch { - EasingType.Step => (linearStep < 0.5 ? 0 : 1), + EasingType.Step => linearStep < 0.5 ? 0 : 1, EasingType.Linear => linearStep, EasingType.Sine => Sine.EaseIn(linearStep), EasingType.Quadratic => Power.EaseIn(linearStep, 2), @@ -516,7 +505,7 @@ namespace Greenshot.Base.Core public static double EaseOut(double linearStep, EasingType type) => type switch { - EasingType.Step => (linearStep < 0.5 ? 0 : 1), + EasingType.Step => linearStep < 0.5 ? 0 : 1, EasingType.Linear => linearStep, EasingType.Sine => Sine.EaseOut(linearStep), EasingType.Quadratic => Power.EaseOut(linearStep, 2), @@ -534,7 +523,7 @@ namespace Greenshot.Base.Core public static double EaseInOut(double linearStep, EasingType type) => type switch { - EasingType.Step => (linearStep < 0.5 ? 0 : 1), + EasingType.Step => linearStep < 0.5 ? 0 : 1, EasingType.Linear => linearStep, EasingType.Sine => Sine.EaseInOut(linearStep), EasingType.Quadratic => Power.EaseInOut(linearStep, 2), @@ -548,7 +537,7 @@ namespace Greenshot.Base.Core { public static double EaseIn(double s) { - return Math.Sin(s * (Math.PI / 2) - (Math.PI / 2)) + 1; + return Math.Sin((s * (Math.PI / 2)) - (Math.PI / 2)) + 1; } public static double EaseOut(double s) @@ -558,7 +547,7 @@ namespace Greenshot.Base.Core public static double EaseInOut(double s) { - return Math.Sin(s * Math.PI - (Math.PI / 2) + 1) / 2; + return Math.Sin((s * Math.PI) - (Math.PI / 2) + 1) / 2; } } @@ -584,7 +573,7 @@ namespace Greenshot.Base.Core } var sign = power % 2 == 0 ? -1 : 1; - return (sign / 2.0 * (Math.Pow(s - 2, power) + sign * 2)); + return sign / 2.0 * (Math.Pow(s - 2, power) + (sign * 2)); } } } diff --git a/src/Greenshot.Base/Core/BinaryStructHelper.cs b/src/Greenshot.Base/Core/BinaryStructHelper.cs index 68ef884dd..2f9825a40 100644 --- a/src/Greenshot.Base/Core/BinaryStructHelper.cs +++ b/src/Greenshot.Base/Core/BinaryStructHelper.cs @@ -63,7 +63,7 @@ namespace Greenshot.Base.Core public static T FromIntPtr(IntPtr intPtr) where T : struct { object obj = Marshal.PtrToStructure(intPtr, typeof(T)); - return (T) obj; + return (T)obj; } /// diff --git a/src/Greenshot.Base/Core/Cache.cs b/src/Greenshot.Base/Core/Cache.cs index 384f5f15c..bf92bb557 100644 --- a/src/Greenshot.Base/Core/Cache.cs +++ b/src/Greenshot.Base/Core/Cache.cs @@ -27,7 +27,7 @@ using log4net; namespace Greenshot.Base.Core { /// - /// Cache class + /// Cache class /// /// Type of key /// Type of value @@ -35,7 +35,7 @@ namespace Greenshot.Base.Core { private static readonly ILog Log = LogManager.GetLogger(typeof(Cache)); private readonly IDictionary _internalCache = new Dictionary(); - private readonly object _lockObject = new object(); + private readonly object _lockObject = new(); private readonly int _secondsToExpire = 10; private readonly CacheObjectExpired _expiredCallback; @@ -83,7 +83,7 @@ namespace Greenshot.Base.Core { get { - List elements = new List(); + List elements = new(); lock (_lockObject) { @@ -156,7 +156,7 @@ namespace Greenshot.Base.Core lock (_lockObject) { var cachedItem = new CachedItem(key, value, secondsToExpire ?? _secondsToExpire); - cachedItem.Expired += delegate(TK cacheKey, TV cacheValue) + cachedItem.Expired += delegate (TK cacheKey, TV cacheValue) { if (_internalCache.ContainsKey(cacheKey)) { diff --git a/src/Greenshot.Base/Core/Capture.cs b/src/Greenshot.Base/Core/Capture.cs index 0be688727..2a761dd29 100644 --- a/src/Greenshot.Base/Core/Capture.cs +++ b/src/Greenshot.Base/Core/Capture.cs @@ -113,7 +113,7 @@ namespace Greenshot.Base.Core set { _cursor?.Dispose(); - _cursor = (Icon) value.Clone(); + _cursor = (Icon)value.Clone(); } } @@ -127,27 +127,15 @@ namespace Greenshot.Base.Core /// public bool CursorVisible { get; set; } - private NativePoint _cursorLocation = NativePoint.Empty; - /// /// Get/Set the CursorLocation /// - public NativePoint CursorLocation - { - get => _cursorLocation; - set => _cursorLocation = value; - } - - private NativePoint _location = NativePoint.Empty; + public NativePoint CursorLocation { get; set; } = NativePoint.Empty; /// /// Get/set the Location /// - public NativePoint Location - { - get => _location; - set => _location = value; - } + public NativePoint Location { get; set; } = NativePoint.Empty; private CaptureDetails _captureDetails; @@ -157,7 +145,7 @@ namespace Greenshot.Base.Core public ICaptureDetails CaptureDetails { get => _captureDetails; - set => _captureDetails = (CaptureDetails) value; + set => _captureDetails = (CaptureDetails)value; } /// @@ -226,7 +214,7 @@ namespace Greenshot.Base.Core return false; } - _location = cropRectangle.Location; + Location = cropRectangle.Location; // Change mouse location according to the cropRectangle (including screenbounds) offset MoveMouseLocation(-cropRectangle.Location.X, -cropRectangle.Location.Y); // Move all the elements @@ -248,7 +236,7 @@ namespace Greenshot.Base.Core /// y coordinates to move the mouse public void MoveMouseLocation(int x, int y) { - _cursorLocation = _cursorLocation.Offset(x, y); + CursorLocation = CursorLocation.Offset(x, y); } // TODO: Enable when the elements are usable again. diff --git a/src/Greenshot.Base/Core/CaptureDetails.cs b/src/Greenshot.Base/Core/CaptureDetails.cs index ac6f8d364..048fcf32c 100644 --- a/src/Greenshot.Base/Core/CaptureDetails.cs +++ b/src/Greenshot.Base/Core/CaptureDetails.cs @@ -56,14 +56,7 @@ namespace Greenshot.Base.Core /// public void AddMetaData(string key, string value) { - if (MetaData.ContainsKey(key)) - { - MetaData[key] = value; - } - else - { - MetaData.Add(key, value); - } + MetaData[key] = value; } /// diff --git a/src/Greenshot.Base/Core/ClipboardHelper.cs b/src/Greenshot.Base/Core/ClipboardHelper.cs index ed9f2c3e9..770e293f6 100644 --- a/src/Greenshot.Base/Core/ClipboardHelper.cs +++ b/src/Greenshot.Base/Core/ClipboardHelper.cs @@ -52,7 +52,7 @@ namespace Greenshot.Base.Core public static class ClipboardHelper { private static readonly ILog Log = LogManager.GetLogger(typeof(ClipboardHelper)); - private static readonly object ClipboardLockObject = new object(); + private static readonly object ClipboardLockObject = new(); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); private static readonly string FORMAT_FILECONTENTS = "FileContents"; private static readonly string FORMAT_HTML = "text/html"; @@ -384,7 +384,7 @@ EndSelection:<<<<<<<4 /// /// IDataObject /// IEnumerable{(MemoryStream,string)} - private static IEnumerable<(MemoryStream stream,string filename)> IterateClipboardContent(IDataObject dataObject) + private static IEnumerable<(MemoryStream stream, string filename)> IterateClipboardContent(IDataObject dataObject) { var fileDescriptors = AvailableFileDescriptors(dataObject); if (fileDescriptors == null) yield break; @@ -402,7 +402,7 @@ EndSelection:<<<<<<<4 /// IEnumerable{FileDescriptor} private static IEnumerable AvailableFileDescriptors(IDataObject dataObject) { - var fileDescriptor = (MemoryStream) dataObject.GetData("FileGroupDescriptorW"); + var fileDescriptor = (MemoryStream)dataObject.GetData("FileGroupDescriptorW"); if (fileDescriptor != null) { try @@ -544,7 +544,6 @@ EndSelection:<<<<<<<4 { continue; } - } catch (Exception ex) { @@ -569,7 +568,7 @@ EndSelection:<<<<<<<4 } Bitmap bitmap = null; - using FileStream fileStream = new FileStream(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream fileStream = new(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read); try { if (!fileFormatHandlers.TryLoadFromStream(fileStream, extension, out bitmap)) @@ -643,7 +642,7 @@ EndSelection:<<<<<<<4 { continue; } - using FileStream fileStream = new FileStream(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream fileStream = new(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read); IEnumerable drawableContainers; try { @@ -677,7 +676,7 @@ EndSelection:<<<<<<<4 // Found a weird bug, where PNG's from Outlook 2010 are clipped // So I build some special logic to get the best format: - if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib)) + if (formats?.Contains(FORMAT_PNG_OFFICEART) == true && formats.Contains(DataFormats.Dib)) { // Outlook ?? Log.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front..."); @@ -698,7 +697,7 @@ EndSelection:<<<<<<<4 foreach (string currentFormat in retrieveFormats) { - if (formats != null && formats.Contains(currentFormat)) + if (formats?.Contains(currentFormat) == true) { Log.InfoFormat("Found {0}, trying to retrieve.", currentFormat); returnImage = GetImageForFormat(currentFormat, dataObject); @@ -732,7 +731,7 @@ EndSelection:<<<<<<<4 // Found a weird bug, where PNG's from Outlook 2010 are clipped // So I build some special logic to get the best format: - if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib)) + if (formats?.Contains(FORMAT_PNG_OFFICEART) == true && formats.Contains(DataFormats.Dib)) { // Outlook ?? Log.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front..."); @@ -753,7 +752,7 @@ EndSelection:<<<<<<<4 foreach (string currentFormat in retrieveFormats) { - if (formats != null && formats.Contains(currentFormat)) + if (formats?.Contains(currentFormat) == true) { Log.InfoFormat("Found {0}, trying to retrieve.", currentFormat); returnImage = GetDrawableForFormat(currentFormat, dataObject); @@ -782,8 +781,7 @@ EndSelection:<<<<<<<4 /// Bitmap or null private static Bitmap GetImageForFormat(string format, IDataObject dataObject) { - Bitmap bitmap = null; - + Bitmap bitmap; if (format == FORMAT_HTML) { var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8); @@ -818,11 +816,7 @@ EndSelection:<<<<<<<4 var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances(); // From here, imageStream is a valid stream - if (fileFormatHandlers.TryLoadFromStream(imageStream, format, out bitmap)) - { - return bitmap; - } - return null; + return fileFormatHandlers.TryLoadFromStream(imageStream, format, out bitmap) ? bitmap : null; } /// @@ -835,8 +829,6 @@ EndSelection:<<<<<<<4 /// IDrawableContainer or null private static IDrawableContainer GetDrawableForFormat(string format, IDataObject dataObject) { - IDrawableContainer drawableContainer = null; - if (format == FORMAT_HTML) { var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8); @@ -852,7 +844,7 @@ EndSelection:<<<<<<<4 var srcAttribute = imgNode.Attributes["src"]; var imageUrl = srcAttribute.Value; Log.Debug(imageUrl); - drawableContainer = NetworkHelper.DownloadImageAsDrawableContainer(imageUrl); + IDrawableContainer drawableContainer = NetworkHelper.DownloadImageAsDrawableContainer(imageUrl); if (drawableContainer != null) { return drawableContainer; @@ -895,12 +887,7 @@ EndSelection:<<<<<<<4 /// string if there is text on the clipboard public static string GetText(IDataObject dataObject) { - if (ContainsText(dataObject)) - { - return (string) dataObject.GetData(DataFormats.Text); - } - - return null; + return ContainsText(dataObject) ? (string)dataObject.GetData(DataFormats.Text) : null; } /// @@ -920,12 +907,12 @@ EndSelection:<<<<<<<4 utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${width}", surface.Image.Width.ToString()); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${height}", surface.Image.Height.ToString()); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${file}", filename.Replace("\\", "/")); - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append(utf8EncodedHtmlString); sb.Replace("<<<<<<<1", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8")); - sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8")); + sb.Replace("<<<<<<<2", utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal).ToString("D8")); sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8")); - sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8")); + sb.Replace("<<<<<<<4", utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal).ToString("D8")); return sb.ToString(); } @@ -935,13 +922,13 @@ EndSelection:<<<<<<<4 utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${width}", surface.Image.Width.ToString()); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${height}", surface.Image.Height.ToString()); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${format}", "png"); - utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${data}", Convert.ToBase64String(pngStream.GetBuffer(), 0, (int) pngStream.Length)); - StringBuilder sb = new StringBuilder(); + utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${data}", Convert.ToBase64String(pngStream.GetBuffer(), 0, (int)pngStream.Length)); + StringBuilder sb = new(); sb.Append(utf8EncodedHtmlString); sb.Replace("<<<<<<<1", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8")); - sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8")); + sb.Replace("<<<<<<<2", utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal).ToString("D8")); sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8")); - sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8")); + sb.Replace("<<<<<<<4", utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal).ToString("D8")); return sb.ToString(); } @@ -956,7 +943,7 @@ EndSelection:<<<<<<<4 /// public static void SetClipboardData(ISurface surface) { - DataObject dataObject = new DataObject(); + DataObject dataObject = new(); // This will work for Office and most other applications //ido.SetData(DataFormats.Bitmap, true, image); @@ -968,7 +955,7 @@ EndSelection:<<<<<<<4 bool disposeImage = false; try { - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false); + SurfaceOutputSettings outputSettings = new(OutputFormat.png, 100, false); // Create the image which is going to be saved so we don't create it multiple times disposeImage = ImageIO.CreateImageFromSurface(surface, outputSettings, out imageToSave); try @@ -978,7 +965,7 @@ EndSelection:<<<<<<<4 { pngStream = new MemoryStream(); // PNG works for e.g. Powerpoint - SurfaceOutputSettings pngOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false); + SurfaceOutputSettings pngOutputSettings = new(OutputFormat.png, 100, false); ImageIO.SaveToStream(imageToSave, null, pngStream, pngOutputSettings); pngStream.Seek(0, SeekOrigin.Begin); // Set the PNG stream @@ -1034,7 +1021,7 @@ EndSelection:<<<<<<<4 // As we have specified BI_COMPRESSION.BI_BITFIELDS, the BitfieldColorMask needs to be added // This also makes sure the default values are set - BitfieldColorMask colorMask = new BitfieldColorMask(); + BitfieldColorMask colorMask = new(); // Create the byte[] from the struct byte[] colorMaskBytes = BinaryStructHelper.ToByteArray(colorMask); Array.Reverse(colorMaskBytes); @@ -1042,7 +1029,7 @@ EndSelection:<<<<<<<4 dibV5Stream.Write(colorMaskBytes, 0, colorMaskBytes.Length); // Create the raw bytes for the pixels only - byte[] bitmapBytes = BitmapToByteArray((Bitmap) imageToSave); + byte[] bitmapBytes = BitmapToByteArray((Bitmap)imageToSave); // Write to the stream dibV5Stream.Write(bitmapBytes, 0, bitmapBytes.Length); @@ -1065,9 +1052,9 @@ EndSelection:<<<<<<<4 else if (CoreConfig.ClipboardFormats.Contains(ClipboardFormat.HTMLDATAURL)) { string html; - using (MemoryStream tmpPngStream = new MemoryStream()) + using (MemoryStream tmpPngStream = new()) { - SurfaceOutputSettings pngOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false) + SurfaceOutputSettings pngOutputSettings = new(OutputFormat.png, 100, false) { // Do not allow to reduce the colors, some applications dislike 256 color images // reported with bug #3594681 @@ -1136,7 +1123,7 @@ EndSelection:<<<<<<<4 for (int i = 0; i < bitmap.Height; i++) { - IntPtr pointer = new IntPtr(ptr + (bmpData.Stride * i)); + IntPtr pointer = new(ptr + (bmpData.Stride * i)); Marshal.Copy(pointer, rgbValues, absStride * (bitmap.Height - i - 1), absStride); } @@ -1243,12 +1230,7 @@ EndSelection:<<<<<<<4 /// object from IDataObject public static object GetFromDataObject(IDataObject dataObj, Type type) { - if (type != null) - { - return GetFromDataObject(dataObj, type.FullName); - } - - return null; + return type != null ? GetFromDataObject(dataObj, type.FullName) : null; } /// @@ -1267,7 +1249,6 @@ EndSelection:<<<<<<<4 .Where(filename => !string.IsNullOrEmpty(filename)) .Where(Path.HasExtension) .Where(filename => supportedExtensions.Contains(Path.GetExtension(filename))); - } /// diff --git a/src/Greenshot.Base/Core/CoreConfiguration.cs b/src/Greenshot.Base/Core/CoreConfiguration.cs index 3e085bc9b..7a1c7ef06 100644 --- a/src/Greenshot.Base/Core/CoreConfiguration.cs +++ b/src/Greenshot.Base/Core/CoreConfiguration.cs @@ -349,7 +349,7 @@ namespace Greenshot.Base.Core newSize.Width = 256; } - newSize.Width = (newSize.Width / 16) * 16; + newSize.Width = newSize.Width / 16 * 16; if (newSize.Height < 16) { newSize.Height = 16; @@ -359,7 +359,7 @@ namespace Greenshot.Base.Core newSize.Height = 256; } - newSize.Height = (newSize.Height / 16) * 16; + newSize.Height = newSize.Height / 16 * 16; } if (_iconSize != newSize) @@ -369,7 +369,7 @@ namespace Greenshot.Base.Core } } } - + [IniProperty("WebRequestTimeout", Description = "The connect timeout value for web requests, these are seconds", DefaultValue = "100")] public int WebRequestTimeout { get; set; } @@ -385,7 +385,7 @@ namespace Greenshot.Base.Core /// public bool IsExperimentalFeatureEnabled(string experimentalFeature) { - return ExperimentalFeatures != null && ExperimentalFeatures.Contains(experimentalFeature); + return ExperimentalFeatures?.Contains(experimentalFeature) == true; } private string CreateOutputFilePath() @@ -414,7 +414,7 @@ namespace Greenshot.Base.Core return Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } - + /// /// Supply values we can't put as defaults /// @@ -445,7 +445,7 @@ namespace Greenshot.Base.Core }, _ => null }; - + /// /// This method will be called before converting the property, making to possible to correct a certain value /// Can be used when migration is needed @@ -528,9 +528,9 @@ namespace Greenshot.Base.Core } // Enable OneNote if upgrading from 1.1 - if (ExcludeDestinations != null && ExcludeDestinations.Contains("OneNote")) + if (ExcludeDestinations?.Contains("OneNote") == true) { - if (LastSaveWithVersion != null && LastSaveWithVersion.StartsWith("1.1")) + if (LastSaveWithVersion?.StartsWith("1.1") == true) { ExcludeDestinations.Remove("OneNote"); } diff --git a/src/Greenshot.Base/Core/CredentialsHelper.cs b/src/Greenshot.Base/Core/CredentialsHelper.cs index 24063b7a8..a08e61d42 100644 --- a/src/Greenshot.Base/Core/CredentialsHelper.cs +++ b/src/Greenshot.Base/Core/CredentialsHelper.cs @@ -325,10 +325,10 @@ namespace Greenshot.Base.Core private DialogResult ShowDialog(IWin32Window owner) { // set the api call parameters - StringBuilder name = new StringBuilder(CredUi.MAX_USERNAME_LENGTH); + StringBuilder name = new(CredUi.MAX_USERNAME_LENGTH); name.Append(Name); - StringBuilder password = new StringBuilder(CredUi.MAX_PASSWORD_LENGTH); + StringBuilder password = new(CredUi.MAX_PASSWORD_LENGTH); password.Append(Password); int saveChecked = Convert.ToInt32(SaveChecked); @@ -365,7 +365,7 @@ namespace Greenshot.Base.Core /// The System.Windows.Forms.IWin32Window the dialog will display in front of. private CredUi.INFO GetInfo(IWin32Window owner) { - CredUi.INFO info = new CredUi.INFO(); + CredUi.INFO info = new(); if (owner != null) info.hWndParent = owner.Handle; info.pszCaptionText = Caption; info.pszMessageText = Message; diff --git a/src/Greenshot.Base/Core/DestinationHelper.cs b/src/Greenshot.Base/Core/DestinationHelper.cs index 641b29bbc..d80bb694d 100644 --- a/src/Greenshot.Base/Core/DestinationHelper.cs +++ b/src/Greenshot.Base/Core/DestinationHelper.cs @@ -41,8 +41,7 @@ namespace Greenshot.Base.Core { return SimpleServiceProvider.Current.GetAllInstances() .Where(destination => destination.IsActive) - .Where(destination => CoreConfig.ExcludeDestinations == null || - !CoreConfig.ExcludeDestinations.Contains(destination.Designation)).OrderBy(p => p.Priority).ThenBy(p => p.Description); + .Where(destination => CoreConfig.ExcludeDestinations?.Contains(destination.Designation) != true).OrderBy(p => p.Priority).ThenBy(p => p.Description); } /// @@ -90,12 +89,7 @@ namespace Greenshot.Base.Core public static ExportInformation ExportCapture(bool manuallyInitiated, string designation, ISurface surface, ICaptureDetails captureDetails) { IDestination destination = GetDestination(designation); - if (destination != null && destination.IsActive) - { - return destination.ExportCapture(manuallyInitiated, surface, captureDetails); - } - - return null; + return destination?.IsActive == true ? destination.ExportCapture(manuallyInitiated, surface, captureDetails) : null; } } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/EffectConverter.cs b/src/Greenshot.Base/Core/EffectConverter.cs index e5742b803..6f333a683 100644 --- a/src/Greenshot.Base/Core/EffectConverter.cs +++ b/src/Greenshot.Base/Core/EffectConverter.cs @@ -12,7 +12,7 @@ namespace Greenshot.Base.Core public class EffectConverter : TypeConverter { // Fix to prevent BUG-1753 - private readonly NumberFormatInfo _numberFormatInfo = new NumberFormatInfo(); + private readonly NumberFormatInfo _numberFormatInfo = new(); public EffectConverter() { @@ -22,12 +22,7 @@ namespace Greenshot.Base.Core public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(string)) - { - return true; - } - - return base.CanConvertFrom(context, sourceType); + return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) @@ -42,12 +37,7 @@ namespace Greenshot.Base.Core return true; } - if (destinationType == typeof(TornEdgeEffect)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); + return destinationType == typeof(TornEdgeEffect) || base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) @@ -55,7 +45,7 @@ namespace Greenshot.Base.Core // to string if (destinationType == typeof(string)) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (value.GetType() == typeof(DropShadowEffect)) { DropShadowEffect effect = value as DropShadowEffect; @@ -79,14 +69,14 @@ namespace Greenshot.Base.Core string settings = value as string; if (destinationType == typeof(DropShadowEffect)) { - DropShadowEffect effect = new DropShadowEffect(); + DropShadowEffect effect = new(); ApplyDropShadowEffectValues(settings, effect); return effect; } if (destinationType == typeof(TornEdgeEffect)) { - TornEdgeEffect effect = new TornEdgeEffect(); + TornEdgeEffect effect = new(); ApplyDropShadowEffectValues(settings, effect); ApplyTornEdgeEffectValues(settings, effect); return effect; @@ -100,12 +90,9 @@ namespace Greenshot.Base.Core { if (value is string settings) { - if (settings.Contains("ToothHeight")) - { - return ConvertTo(context, culture, settings, typeof(TornEdgeEffect)); - } - - return ConvertTo(context, culture, settings, typeof(DropShadowEffect)); + return settings.Contains("ToothHeight") + ? ConvertTo(context, culture, settings, typeof(TornEdgeEffect)) + : ConvertTo(context, culture, settings, typeof(DropShadowEffect)); } return base.ConvertFrom(context, culture, value); @@ -138,7 +125,7 @@ namespace Greenshot.Base.Core break; case "ShadowOffset": - NativePoint shadowOffset = new NativePoint(); + NativePoint shadowOffset = new(); string[] coordinates = pair[1].Split(','); if (int.TryParse(coordinates[0], out var shadowOffsetX)) { diff --git a/src/Greenshot.Base/Core/EnvironmentInfo.cs b/src/Greenshot.Base/Core/EnvironmentInfo.cs index 30811fb69..c99f05e77 100644 --- a/src/Greenshot.Base/Core/EnvironmentInfo.cs +++ b/src/Greenshot.Base/Core/EnvironmentInfo.cs @@ -99,13 +99,13 @@ namespace Greenshot.Base.Core public static string EnvironmentToString(bool newline) { StringBuilder environment = new(); - environment.Append("Software version: " + GetGreenshotVersion()); + environment.Append("Software version: ").Append(GetGreenshotVersion()); if (IniConfig.IsPortable) { environment.Append(" Portable"); } - environment.Append(" (" + OsInfo.Bits + " bit)"); + environment.Append(" (").Append(OsInfo.Bits).Append(" bit)"); if (newline) { @@ -116,7 +116,7 @@ namespace Greenshot.Base.Core environment.Append(", "); } - environment.Append(".NET runtime version: " + Environment.Version); + environment.Append(".NET runtime version: ").Append(Environment.Version); if (IsNet45OrNewer()) { environment.Append("+"); @@ -131,7 +131,7 @@ namespace Greenshot.Base.Core environment.Append(", "); } - environment.Append("Time: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zzz")); + environment.Append("Time: ").Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zzz")); if (IsWindows) { @@ -144,19 +144,19 @@ namespace Greenshot.Base.Core environment.Append(", "); } - environment.Append($"OS: {OsInfo.Name}"); + environment.Append("OS: ").Append(OsInfo.Name); if (!string.IsNullOrEmpty(OsInfo.Edition)) { - environment.Append($" {OsInfo.Edition}"); + environment.Append(' ').Append(OsInfo.Edition); } if (!string.IsNullOrEmpty(OsInfo.ServicePack)) { - environment.Append($" {OsInfo.ServicePack}"); + environment.Append(' ').Append(OsInfo.ServicePack); } - environment.Append($" x{OsInfo.Bits}"); - environment.Append($" {OsInfo.VersionString}"); + environment.Append(" x").Append(OsInfo.Bits); + environment.Append(' ').Append(OsInfo.VersionString); if (newline) { environment.AppendLine(); @@ -214,8 +214,8 @@ namespace Greenshot.Base.Core StringBuilder report = new(); - report.AppendLine("Exception: " + ex.GetType()); - report.AppendLine("Message: " + ex.Message); + report.Append("Exception: ").Append(ex.GetType()).AppendLine(); + report.Append("Message: ").AppendLine(ex.Message); if (ex.Data.Count > 0) { report.AppendLine(); @@ -225,7 +225,7 @@ namespace Greenshot.Base.Core object data = ex.Data[key]; if (data != null) { - report.AppendLine(key + " : " + data); + report.Append(key).Append(" : ").Append(data).AppendLine(); } } } @@ -233,7 +233,7 @@ namespace Greenshot.Base.Core if (ex is ExternalException externalException) { // e.g. COMException - report.AppendLine().AppendLine("ErrorCode: 0x" + externalException.ErrorCode.ToString("X")); + report.AppendLine().Append("ErrorCode: 0x").AppendLine(externalException.ErrorCode.ToString("X")); } report.AppendLine().AppendLine("Stack:").AppendLine(ex.StackTrace); @@ -316,7 +316,6 @@ namespace Greenshot.Base.Core edition = (suiteMask & WindowsSuites.Enterprise) != 0 ? "Enterprise Server" : "Standard Server"; } } - else if (majorVersion == 5) { if (productType == WindowsProductTypes.VER_NT_WORKSTATION) @@ -377,7 +376,6 @@ namespace Greenshot.Base.Core } } } - else if (majorVersion == 6) { if (Kernel32Api.GetProductInfo(majorVersion, minorVersion, osVersionInfo.ServicePackMajor, osVersionInfo.ServicePackMinor, out var windowsProduct)) @@ -562,13 +560,9 @@ namespace Greenshot.Base.Core return $"build {Environment.OSVersion.Version.Build}"; } - if (Environment.OSVersion.Version.Revision != 0) - { - return - $"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor} build {Environment.OSVersion.Version.Build} revision {Environment.OSVersion.Version.Revision:X}"; - } - - return $"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor} build {Environment.OSVersion.Version.Build}"; + return Environment.OSVersion.Version.Revision != 0 + ? $"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor} build {Environment.OSVersion.Version.Build} revision {Environment.OSVersion.Version.Revision:X}" + : $"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor} build {Environment.OSVersion.Version.Build}"; } } } diff --git a/src/Greenshot.Base/Core/FastBitmap.cs b/src/Greenshot.Base/Core/FastBitmap.cs index c0309763f..b5e0c058e 100644 --- a/src/Greenshot.Base/Core/FastBitmap.cs +++ b/src/Greenshot.Base/Core/FastBitmap.cs @@ -412,12 +412,7 @@ namespace Greenshot.Base.Core { get { - if (Area == NativeRect.Empty) - { - return Bitmap.Size; - } - - return Area.Size; + return Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : Area.Size; } } @@ -428,12 +423,7 @@ namespace Greenshot.Base.Core { get { - if (Area == NativeRect.Empty) - { - return Bitmap.Width; - } - - return Area.Width; + return Area == NativeRect.Empty ? Bitmap.Width : Area.Width; } } @@ -444,12 +434,7 @@ namespace Greenshot.Base.Core { get { - if (Area == NativeRect.Empty) - { - return Bitmap.Height; - } - - return Area.Height; + return Area == NativeRect.Empty ? Bitmap.Height : Area.Height; } } @@ -574,7 +559,7 @@ namespace Greenshot.Base.Core BitsLocked = true; IntPtr scan0 = BmData.Scan0; - Pointer = (byte*) (void*) scan0; + Pointer = (byte*)(void*)scan0; Stride = BmData.Stride; } @@ -637,14 +622,7 @@ namespace Greenshot.Base.Core bool IFastBitmapWithClip.Contains(int x, int y) { bool contains = Clip.Contains(x, y); - if (InvertClip) - { - return !contains; - } - else - { - return contains; - } + return InvertClip ? !contains : contains; } void IFastBitmapWithClip.SetColorAt(int x, int y, byte[] color) @@ -716,7 +694,7 @@ namespace Greenshot.Base.Core { // Used for indexed images private readonly Color[] _colorEntries; - private readonly Dictionary _colorCache = new Dictionary(); + private readonly Dictionary _colorCache = new(); public FastChunkyBitmap(Bitmap source, NativeRect area) : base(source, area) { @@ -1039,9 +1017,9 @@ namespace Greenshot.Base.Core { // As the request is to get without alpha, we blend. int rem = 255 - a; - red = (red * a + BackgroundBlendColor.R * rem) / 255; - green = (green * a + BackgroundBlendColor.G * rem) / 255; - blue = (blue * a + BackgroundBlendColor.B * rem) / 255; + red = ((red * a) + (BackgroundBlendColor.R * rem)) / 255; + green = ((green * a) + (BackgroundBlendColor.G * rem)) / 255; + blue = ((blue * a) + (BackgroundBlendColor.B * rem)) / 255; } return Color.FromArgb(255, red, green, blue); diff --git a/src/Greenshot.Base/Core/FileDescriptorReader.cs b/src/Greenshot.Base/Core/FileDescriptorReader.cs index 69ad0af7d..e895e8d40 100644 --- a/src/Greenshot.Base/Core/FileDescriptorReader.cs +++ b/src/Greenshot.Base/Core/FileDescriptorReader.cs @@ -29,7 +29,7 @@ namespace Greenshot.Base.Core { /// /// Specifies which fields are valid in a FileDescriptor Structure - /// + /// [Flags] public enum FileDescriptorFlags : uint { @@ -67,7 +67,7 @@ namespace Greenshot.Base.Core var count = reader.ReadUInt32(); while (count > 0) { - FileDescriptor descriptor = new FileDescriptor(reader); + FileDescriptor descriptor = new(reader); yield return descriptor.FileName; @@ -78,7 +78,7 @@ namespace Greenshot.Base.Core internal static MemoryStream GetFileContents(System.Windows.Forms.IDataObject dataObject, int index) { //cast the default IDataObject to a com IDataObject - var comDataObject = (IDataObject) dataObject; + var comDataObject = (IDataObject)dataObject; var format = System.Windows.DataFormats.GetDataFormat("FileContents"); if (format == null) @@ -87,13 +87,13 @@ namespace Greenshot.Base.Core } //create STGMEDIUM to output request results into - var medium = new STGMEDIUM(); - + _ = new STGMEDIUM(); + STGMEDIUM medium; unchecked { var formatetc = new FORMATETC { - cfFormat = (short) format.Id, + cfFormat = (short)format.Id, dwAspect = DVASPECT.DVASPECT_CONTENT, lindex = index, tymed = TYMED.TYMED_ISTREAM | TYMED.TYMED_HGLOBAL @@ -113,13 +113,13 @@ namespace Greenshot.Base.Core private static MemoryStream GetIStream(STGMEDIUM medium) { //marshal the returned pointer to a IStream object - IStream iStream = (IStream) Marshal.GetObjectForIUnknown(medium.unionmember); + IStream iStream = (IStream)Marshal.GetObjectForIUnknown(medium.unionmember); Marshal.Release(medium.unionmember); //get the STATSTG of the IStream to determine how many bytes are in it - var iStreamStat = new System.Runtime.InteropServices.ComTypes.STATSTG(); - iStream.Stat(out iStreamStat, 0); - int iStreamSize = (int) iStreamStat.cbSize; + _ = new System.Runtime.InteropServices.ComTypes.STATSTG(); + iStream.Stat(out System.Runtime.InteropServices.ComTypes.STATSTG iStreamStat, 0); + int iStreamSize = (int)iStreamStat.cbSize; //read the data from the IStream into a managed byte array byte[] iStreamContent = new byte[iStreamSize]; diff --git a/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs b/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs index 8941c7184..918bf1a64 100644 --- a/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs +++ b/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs @@ -39,7 +39,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers /// /// string /// string - public static string NormalizeExtension(string extension) + public static string NormalizeExtension(string extension) { if (string.IsNullOrEmpty(extension)) { @@ -93,7 +93,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers .Where(ffh => ffh.Supports(FileFormatHandlerActions.LoadFromStream, extension)) .OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadFromStream, extension)).ToList(); - if (!saveFileFormatHandlers.Any()) + if (saveFileFormatHandlers.Count == 0) { return false; } @@ -126,12 +126,9 @@ namespace Greenshot.Base.Core.FileFormatHandlers .OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadDrawableFromStream, extension)) .FirstOrDefault(); - if (loadfileFormatHandler != null) - { - return loadfileFormatHandler.LoadDrawablesFromStream(stream, extension, parentSurface); - } - - return Enumerable.Empty(); + return loadfileFormatHandler != null + ? loadfileFormatHandler.LoadDrawablesFromStream(stream, extension, parentSurface) + : Enumerable.Empty(); } /// diff --git a/src/Greenshot.Base/Core/FilenameHelper.cs b/src/Greenshot.Base/Core/FilenameHelper.cs index 4c6864547..83cb0d4ec 100644 --- a/src/Greenshot.Base/Core/FilenameHelper.cs +++ b/src/Greenshot.Base/Core/FilenameHelper.cs @@ -42,15 +42,15 @@ namespace Greenshot.Base.Core // If a parameters needs to be supplied, than a ":" should follow the name... everything from the : until the } is considered to be part of the parameters. // The parameter format is a single alpha followed by the value belonging to the parameter, e.g. : // ${capturetime:d"yyyy-MM-dd HH_mm_ss"} - private static readonly Regex VarRegexp = new Regex(@"\${(?[^:}]+)[:]?(?[^}]*)}", RegexOptions.Compiled); - private static readonly Regex CmdVarRegexp = new Regex(@"%(?[^%]+)%", RegexOptions.Compiled); + private static readonly Regex VarRegexp = new(@"\${(?[^:}]+)[:]?(?[^}]*)}", RegexOptions.Compiled); + private static readonly Regex CmdVarRegexp = new("%(?[^%]+)%", RegexOptions.Compiled); - private static readonly Regex SplitRegexp = new Regex(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled); + private static readonly Regex SplitRegexp = new(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled); private const int MaxTitleLength = 80; private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); private const string UnsafeReplacement = "_"; - private static readonly Random RandomNumberGen = new Random(); - private static readonly Regex RandRegexp = new Regex("^R+$", RegexOptions.Compiled); + private static readonly Random RandomNumberGen = new(); + private static readonly Regex RandRegexp = new("^R+$", RegexOptions.Compiled); /// /// Remove invalid characters from the fully qualified filename @@ -141,7 +141,6 @@ namespace Greenshot.Base.Core return GetFilenameFromPattern(pattern, format, captureDetails); } - /// /// This method will be called by the regexp.replace as a MatchEvaluator delegate! /// Will delegate this to the MatchVarEvaluatorInternal and catch any exceptions @@ -191,7 +190,7 @@ namespace Greenshot.Base.Core string replaceValue = string.Empty; string variable = match.Groups["variable"].Value; string parameters = match.Groups["parameters"].Value; - string randomChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + const string randomChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; if (parameters.Length > 0) { @@ -222,7 +221,7 @@ namespace Greenshot.Base.Core // r, case "r": string[] replaceParameters = parameter.Substring(1).Split(','); - if (replaceParameters != null && replaceParameters.Length == 2) + if (replaceParameters?.Length == 2) { replacements.Add(replaceParameters[0], replaceParameters[1]); } @@ -277,25 +276,25 @@ namespace Greenshot.Base.Core } } - if (processVars != null && processVars.Contains(variable)) + if (processVars?.Contains(variable) == true) { - replaceValue = (string) processVars[variable]; + replaceValue = (string)processVars[variable]; if (filenameSafeMode) { replaceValue = MakePathSafe(replaceValue); } } - else if (userVars != null && userVars.Contains(variable)) + else if (userVars?.Contains(variable) == true) { - replaceValue = (string) userVars[variable]; + replaceValue = (string)userVars[variable]; if (filenameSafeMode) { replaceValue = MakePathSafe(replaceValue); } } - else if (machineVars != null && machineVars.Contains(variable)) + else if (machineVars?.Contains(variable) == true) { - replaceValue = (string) machineVars[variable]; + replaceValue = (string)machineVars[variable]; if (filenameSafeMode) { replaceValue = MakePathSafe(replaceValue); @@ -675,7 +674,7 @@ namespace Greenshot.Base.Core var forbiddenChars = Path.GetInvalidPathChars(); foreach (var forbiddenChar in forbiddenChars) { - if (directoryName == null || directoryName.Contains(forbiddenChar.ToString())) + if (directoryName?.Contains(forbiddenChar.ToString()) != false) { return false; } @@ -694,7 +693,7 @@ namespace Greenshot.Base.Core var forbiddenChars = Path.GetInvalidFileNameChars(); foreach (var forbiddenChar in forbiddenChars) { - if (filename == null || filename.Contains(forbiddenChar.ToString())) + if (filename?.Contains(forbiddenChar.ToString()) != false) { return false; } diff --git a/src/Greenshot.Base/Core/Fraction.cs b/src/Greenshot.Base/Core/Fraction.cs index e7d999445..a538b5211 100644 --- a/src/Greenshot.Base/Core/Fraction.cs +++ b/src/Greenshot.Base/Core/Fraction.cs @@ -31,11 +31,11 @@ namespace Greenshot.Base.Core } public Fraction Inverse() - => new Fraction(Denominator, Numerator); + => new(Denominator, Numerator); #region Parse - private static readonly Regex PARSE_REGEX = new Regex(@"^([1-9][0-9]*)\/([1-9][0-9]*)$", RegexOptions.Compiled); + private static readonly Regex PARSE_REGEX = new(@"^([1-9][0-9]*)\/([1-9][0-9]*)$", RegexOptions.Compiled); public static bool TryParse(string str, out Fraction result) { @@ -75,14 +75,14 @@ namespace Greenshot.Base.Core unchecked { int hashCode = -1534900553; - hashCode = hashCode * -1521134295 + Numerator.GetHashCode(); - hashCode = hashCode * -1521134295 + Denominator.GetHashCode(); + hashCode = (hashCode * -1521134295) + Numerator.GetHashCode(); + hashCode = (hashCode * -1521134295) + Denominator.GetHashCode(); return hashCode; } } public int CompareTo(Fraction other) - => (int) (Numerator * other.Denominator) - (int) (other.Numerator * Denominator); + => (int)(Numerator * other.Denominator) - (int)(other.Numerator * Denominator); #endregion @@ -115,22 +115,22 @@ namespace Greenshot.Base.Core #region Scale operators public static Fraction operator *(Fraction left, Fraction right) - => new Fraction(left.Numerator * right.Numerator, left.Denominator * right.Denominator); + => new(left.Numerator * right.Numerator, left.Denominator * right.Denominator); public static Fraction operator *(Fraction left, uint right) - => new Fraction(left.Numerator * right, left.Denominator); + => new(left.Numerator * right, left.Denominator); public static Fraction operator *(uint left, Fraction right) - => new Fraction(left * right.Numerator, right.Denominator); + => new(left * right.Numerator, right.Denominator); public static Fraction operator /(Fraction left, Fraction right) - => new Fraction(left.Numerator * right.Denominator, left.Denominator * right.Numerator); + => new(left.Numerator * right.Denominator, left.Denominator * right.Numerator); public static Fraction operator /(Fraction left, uint right) - => new Fraction(left.Numerator, left.Denominator * right); + => new(left.Numerator, left.Denominator * right); public static Fraction operator /(uint left, Fraction right) - => new Fraction(left * right.Denominator, right.Numerator); + => new(left * right.Denominator, right.Numerator); #endregion @@ -143,10 +143,10 @@ namespace Greenshot.Base.Core => 1.0f * fraction.Numerator / fraction.Denominator; public static implicit operator Fraction(uint number) - => new Fraction(number, 1u); + => new(number, 1u); public static implicit operator Fraction((uint numerator, uint demoninator) tuple) - => new Fraction(tuple.numerator, tuple.demoninator); + => new(tuple.numerator, tuple.demoninator); #endregion diff --git a/src/Greenshot.Base/Core/GreenshotResources.cs b/src/Greenshot.Base/Core/GreenshotResources.cs index 1276ee3f6..36f102f26 100644 --- a/src/Greenshot.Base/Core/GreenshotResources.cs +++ b/src/Greenshot.Base/Core/GreenshotResources.cs @@ -29,16 +29,16 @@ namespace Greenshot.Base.Core /// public static class GreenshotResources { - private static readonly ComponentResourceManager GreenshotResourceManager = new ComponentResourceManager(typeof(GreenshotResources)); + private static readonly ComponentResourceManager GreenshotResourceManager = new(typeof(GreenshotResources)); public static Image GetImage(string imageName) { - return (Image) GreenshotResourceManager.GetObject(imageName); + return (Image)GreenshotResourceManager.GetObject(imageName); } public static Icon GetIcon(string imageName) { - return (Icon) GreenshotResourceManager.GetObject(imageName); + return (Icon)GreenshotResourceManager.GetObject(imageName); } public static Icon GetGreenshotIcon() diff --git a/src/Greenshot.Base/Core/IEHelper.cs b/src/Greenshot.Base/Core/IEHelper.cs index f7fa3242b..a03d09902 100644 --- a/src/Greenshot.Base/Core/IEHelper.cs +++ b/src/Greenshot.Base/Core/IEHelper.cs @@ -85,15 +85,10 @@ namespace Greenshot.Base.Core if (ieVersion > 9) { - return ieVersion * 1000 + (ignoreDoctype ? 1 : 0); + return (ieVersion * 1000) + (ignoreDoctype ? 1 : 0); } - if (ieVersion > 7) - { - return ieVersion * 1111; - } - - return 7000; + return ieVersion > 7 ? ieVersion * 1111 : 7000; } /// @@ -128,7 +123,7 @@ namespace Greenshot.Base.Core { ModifyRegistry("HKEY_CURRENT_USER", applicationName + ".exe", ieVersion); #if DEBUG - ModifyRegistry("HKEY_CURRENT_USER", applicationName + ".vshost.exe", ieVersion); + ModifyRegistry("HKEY_CURRENT_USER", applicationName + ".vshost.exe", ieVersion); #endif } @@ -191,7 +186,7 @@ namespace Greenshot.Base.Core WindowDetails directUIWD = GetDirectUI(ieWindow); if (directUIWD != null) { - Accessible ieAccessible = new Accessible(directUIWD.Handle); + Accessible ieAccessible = new(directUIWD.Handle); foreach (string url in ieAccessible.IETabUrls) { yield return url; diff --git a/src/Greenshot.Base/Core/ImageHelper.cs b/src/Greenshot.Base/Core/ImageHelper.cs index f75cc9def..458d5a4b4 100644 --- a/src/Greenshot.Base/Core/ImageHelper.cs +++ b/src/Greenshot.Base/Core/ImageHelper.cs @@ -51,7 +51,6 @@ namespace Greenshot.Base.Core private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); private const int ExifOrientationId = 0x0112; - /// /// Make sure the image is orientated correctly /// @@ -75,7 +74,7 @@ namespace Greenshot.Base.Core PropertyItem item = image.GetPropertyItem(ExifOrientationId); - ExifOrientations orientation = (ExifOrientations) item.Value[0]; + ExifOrientations orientation = (ExifOrientations)item.Value[0]; // Orient the image. switch (orientation) { @@ -106,7 +105,7 @@ namespace Greenshot.Base.Core } // Set the orientation to be normal, as we rotated the image. - item.Value[0] = (byte) ExifOrientations.TopLeft; + item.Value[0] = (byte)ExifOrientations.TopLeft; image.SetPropertyItem(item); } catch (Exception orientEx) @@ -130,34 +129,34 @@ namespace Greenshot.Base.Core int srcHeight = image.Height; if (thumbHeight < 0) { - thumbHeight = (int) (thumbWidth * (srcHeight / (float) srcWidth)); + thumbHeight = (int)(thumbWidth * (srcHeight / (float)srcWidth)); } if (thumbWidth < 0) { - thumbWidth = (int) (thumbHeight * (srcWidth / (float) srcHeight)); + thumbWidth = (int)(thumbHeight * (srcWidth / (float)srcHeight)); } if (maxWidth > 0 && thumbWidth > maxWidth) { thumbWidth = Math.Min(thumbWidth, maxWidth); - thumbHeight = (int) (thumbWidth * (srcHeight / (float) srcWidth)); + thumbHeight = (int)(thumbWidth * (srcHeight / (float)srcWidth)); } if (maxHeight > 0 && thumbHeight > maxHeight) { thumbHeight = Math.Min(thumbHeight, maxHeight); - thumbWidth = (int) (thumbHeight * (srcWidth / (float) srcHeight)); + thumbWidth = (int)(thumbHeight * (srcWidth / (float)srcHeight)); } - Bitmap bmp = new Bitmap(thumbWidth, thumbHeight); + Bitmap bmp = new(thumbWidth, thumbHeight); using (Graphics graphics = Graphics.FromImage(bmp)) { graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - NativeRect rectDestination = new NativeRect(0, 0, thumbWidth, thumbHeight); + NativeRect rectDestination = new(0, 0, thumbWidth, thumbHeight); graphics.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel); } @@ -200,8 +199,8 @@ namespace Greenshot.Base.Core area ??= new NativeRect(0, 0, fastBitmap.Width, fastBitmap.Height); NativeRect cropNativeRect = NativeRect.Empty; Color referenceColor = fastBitmap.GetColorAt(colorPoint.X, colorPoint.Y); - NativePoint min = new NativePoint(int.MaxValue, int.MaxValue); - NativePoint max = new NativePoint(int.MinValue, int.MinValue); + NativePoint min = new(int.MaxValue, int.MaxValue); + NativePoint max = new(int.MinValue, int.MinValue); if (cropDifference > 0) { @@ -279,7 +278,7 @@ namespace Greenshot.Base.Core // Bottom Left // Top Right // Bottom Right - using (IFastBitmap fastBitmap = FastBitmap.Create((Bitmap) image)) + using (IFastBitmap fastBitmap = FastBitmap.Create((Bitmap)image)) { // find biggest area foreach (var checkPoint in checkPoints) @@ -369,9 +368,9 @@ namespace Greenshot.Base.Core Image returnImage = CreateEmpty(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb, Color.Empty, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); using (var path = new GraphicsPath()) { - Random random = new Random(); - int horizontalRegions = (int) Math.Round((float) sourceImage.Width / horizontalToothRange); - int verticalRegions = (int) Math.Round((float) sourceImage.Height / verticalToothRange); + Random random = new(); + int horizontalRegions = (int)Math.Round((float)sourceImage.Width / horizontalToothRange); + int verticalRegions = (int)Math.Round((float)sourceImage.Height / verticalToothRange); var topLeft = new NativePoint(0, 0); var topRight = new NativePoint(sourceImage.Width, 0); @@ -429,7 +428,7 @@ namespace Greenshot.Base.Core { for (int i = 1; i < horizontalRegions - 1; i++) { - points.Add(new NativePoint(sourceImage.Width - i * horizontalToothRange, sourceImage.Height - random.Next(1, toothHeight))); + points.Add(new NativePoint(sourceImage.Width - (i * horizontalToothRange), sourceImage.Height - random.Next(1, toothHeight))); } points.Add(new NativePoint(random.Next(1, toothHeight), sourceImage.Height - random.Next(1, toothHeight))); @@ -575,7 +574,7 @@ namespace Greenshot.Base.Core if (x >= targetFastBitmap.Left) { - newColors[x - targetFastBitmap.Left] = Color.FromArgb(255, (byte) (r / hits), (byte) (g / hits), (byte) (b / hits)); + newColors[x - targetFastBitmap.Left] = Color.FromArgb(255, (byte)(r / hits), (byte)(g / hits), (byte)(b / hits)); } } @@ -634,7 +633,7 @@ namespace Greenshot.Base.Core if (x >= targetFastBitmap.Left) { - newColors[x - targetFastBitmap.Left] = Color.FromArgb((byte) (a / hits), (byte) (r / hits), (byte) (g / hits), (byte) (b / hits)); + newColors[x - targetFastBitmap.Left] = Color.FromArgb((byte)(a / hits), (byte)(r / hits), (byte)(g / hits), (byte)(b / hits)); } } @@ -690,7 +689,7 @@ namespace Greenshot.Base.Core if (y >= targetFastBitmap.Top) { - newColors[y - targetFastBitmap.Top] = Color.FromArgb(255, (byte) (r / hits), (byte) (g / hits), (byte) (b / hits)); + newColors[y - targetFastBitmap.Top] = Color.FromArgb(255, (byte)(r / hits), (byte)(g / hits), (byte)(b / hits)); } } @@ -750,7 +749,7 @@ namespace Greenshot.Base.Core if (y >= targetFastBitmap.Top) { - newColors[y - targetFastBitmap.Top] = Color.FromArgb((byte) (a / hits), (byte) (r / hits), (byte) (g / hits), (byte) (b / hits)); + newColors[y - targetFastBitmap.Top] = Color.FromArgb((byte)(a / hits), (byte)(r / hits), (byte)(g / hits), (byte)(b / hits)); } } @@ -772,18 +771,15 @@ namespace Greenshot.Base.Core /// NativeRect public static NativeRect CreateIntersectRectangle(NativeSize applySize, NativeRect rect, bool invert) { - NativeRect myRect; if (invert) { - myRect = new NativeRect(0, 0, applySize.Width, applySize.Height); + return new NativeRect(0, 0, applySize.Width, applySize.Height); } else { - NativeRect applyRect = new NativeRect(0, 0, applySize.Width, applySize.Height); - myRect = new NativeRect(rect.X, rect.Y, rect.Width, rect.Height).Intersect(applyRect); + NativeRect applyRect = new(0, 0, applySize.Width, applySize.Height); + return new NativeRect(rect.X, rect.Y, rect.Width, rect.Height).Intersect(applyRect); } - - return myRect; } /// @@ -801,7 +797,7 @@ namespace Greenshot.Base.Core NativePoint offset = shadowOffset.Offset(shadowSize - 1, shadowSize - 1); matrix.Translate(offset.X, offset.Y, MatrixOrder.Append); // Create a new "clean" image - Bitmap returnImage = CreateEmpty(sourceBitmap.Width + shadowSize * 2, sourceBitmap.Height + shadowSize * 2, targetPixelformat, Color.Empty, + Bitmap returnImage = CreateEmpty(sourceBitmap.Width + (shadowSize * 2), sourceBitmap.Height + (shadowSize * 2), targetPixelformat, Color.Empty, sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution); // Make sure the shadow is odd, there is no reason for an even blur! if ((shadowSize & 1) == 0) @@ -811,7 +807,7 @@ namespace Greenshot.Base.Core bool useGdiBlur = GdiPlusApi.IsBlurPossible(shadowSize); // Create "mask" for the shadow - ColorMatrix maskMatrix = new ColorMatrix + ColorMatrix maskMatrix = new() { Matrix00 = 0, Matrix11 = 0, @@ -826,14 +822,14 @@ namespace Greenshot.Base.Core maskMatrix.Matrix33 = darkness; } - NativeRect shadowNativeRect = new NativeRect(new NativePoint(shadowSize, shadowSize), sourceBitmap.Size); - ApplyColorMatrix((Bitmap) sourceBitmap, NativeRect.Empty, returnImage, shadowNativeRect, maskMatrix); + NativeRect shadowNativeRect = new(new NativePoint(shadowSize, shadowSize), sourceBitmap.Size); + ApplyColorMatrix((Bitmap)sourceBitmap, NativeRect.Empty, returnImage, shadowNativeRect, maskMatrix); // blur "shadow", apply to whole new image if (useGdiBlur) { // Use GDI Blur - NativeRect newImageNativeRect = new NativeRect(0, 0, returnImage.Width, returnImage.Height); + NativeRect newImageNativeRect = new(0, 0, returnImage.Width, returnImage.Height); GdiPlusApi.ApplyBlur(returnImage, newImageNativeRect, shadowSize + 1, false); } else @@ -868,8 +864,8 @@ namespace Greenshot.Base.Core /// Negative bitmap public static Bitmap CreateNegative(Image sourceImage) { - Bitmap clone = (Bitmap) Clone(sourceImage); - ColorMatrix invertMatrix = new ColorMatrix(new[] + Bitmap clone = (Bitmap)Clone(sourceImage); + ColorMatrix invertMatrix = new(new[] { new float[] { @@ -916,7 +912,7 @@ namespace Greenshot.Base.Core /// ColorMatrix to apply public static void ApplyColorMatrix(Bitmap source, NativeRect sourceRect, Bitmap dest, NativeRect destRect, ColorMatrix colorMatrix) { - using ImageAttributes imageAttributes = new ImageAttributes(); + using ImageAttributes imageAttributes = new(); imageAttributes.ClearColorMatrix(); imageAttributes.SetColorMatrix(colorMatrix); ApplyImageAttributes(source, sourceRect, dest, destRect, imageAttributes); @@ -993,11 +989,11 @@ namespace Greenshot.Base.Core public static Image CreateBorder(Image sourceImage, int borderSize, Color borderColor, PixelFormat targetPixelformat, Matrix matrix) { // "return" the shifted offset, so the caller can e.g. move elements - NativePoint offset = new NativePoint(borderSize, borderSize); + NativePoint offset = new(borderSize, borderSize); matrix.Translate(offset.X, offset.Y, MatrixOrder.Append); // Create a new "clean" image - Bitmap newImage = CreateEmpty(sourceImage.Width + borderSize * 2, sourceImage.Height + borderSize * 2, targetPixelformat, Color.Empty, sourceImage.HorizontalResolution, + Bitmap newImage = CreateEmpty(sourceImage.Width + (borderSize * 2), sourceImage.Height + (borderSize * 2), targetPixelformat, Color.Empty, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); using (Graphics graphics = Graphics.FromImage(newImage)) { @@ -1006,10 +1002,10 @@ namespace Greenshot.Base.Core graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - using (GraphicsPath path = new GraphicsPath()) + using (GraphicsPath path = new()) { path.AddRectangle(new NativeRect(borderSize >> 1, borderSize >> 1, newImage.Width - borderSize, newImage.Height - borderSize)); - using Pen pen = new Pen(borderColor, borderSize) + using Pen pen = new(borderColor, borderSize) { LineJoin = LineJoin.Round, StartCap = LineCap.Round, @@ -1038,7 +1034,7 @@ namespace Greenshot.Base.Core public static ImageAttributes CreateAdjustAttributes(float brightness, float contrast, float gamma) { float adjustedBrightness = brightness - 1.0f; - ColorMatrix applyColorMatrix = new ColorMatrix( + ColorMatrix applyColorMatrix = new( new[] { new[] @@ -1064,7 +1060,7 @@ namespace Greenshot.Base.Core }); //create some image attributes - ImageAttributes attributes = new ImageAttributes(); + ImageAttributes attributes = new(); attributes.ClearColorMatrix(); attributes.SetColorMatrix(applyColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); attributes.SetGamma(gamma, ColorAdjustType.Bitmap); @@ -1088,7 +1084,7 @@ namespace Greenshot.Base.Core sourceImage.VerticalResolution); using (ImageAttributes adjustAttributes = CreateAdjustAttributes(brightness, contrast, gamma)) { - ApplyImageAttributes((Bitmap) sourceImage, NativeRect.Empty, newBitmap, NativeRect.Empty, adjustAttributes); + ApplyImageAttributes((Bitmap)sourceImage, NativeRect.Empty, newBitmap, NativeRect.Empty, adjustAttributes); } return newBitmap; @@ -1101,8 +1097,8 @@ namespace Greenshot.Base.Core /// Bitmap with grayscale public static Image CreateGrayscale(Image sourceImage) { - Bitmap clone = (Bitmap) Clone(sourceImage); - ColorMatrix grayscaleMatrix = new ColorMatrix(new[] + Bitmap clone = (Bitmap)Clone(sourceImage); + ColorMatrix grayscaleMatrix = new(new[] { new[] { @@ -1149,12 +1145,7 @@ namespace Greenshot.Base.Core /// Bitmap with clone image data public static Image Clone(Image sourceImage) { - if (sourceImage is Metafile) - { - return (Image) sourceImage.Clone(); - } - - return CloneArea(sourceImage, NativeRect.Empty, PixelFormat.DontCare); + return sourceImage is Metafile ? (Image)sourceImage.Clone() : CloneArea(sourceImage, NativeRect.Empty, PixelFormat.DontCare); } /// @@ -1182,7 +1173,7 @@ namespace Greenshot.Base.Core public static Bitmap CloneArea(Image sourceImage, NativeRect sourceRect, PixelFormat targetFormat) { Bitmap newImage; - NativeRect bitmapRect = new NativeRect(0, 0, sourceImage.Width, sourceImage.Height); + NativeRect bitmapRect = new(0, 0, sourceImage.Width, sourceImage.Height); // Make sure the source is not NativeRect.Empty if (NativeRect.Empty.Equals(sourceRect)) @@ -1322,7 +1313,7 @@ namespace Greenshot.Base.Core public static Bitmap CreateEmpty(int width, int height, PixelFormat format, Color backgroundColor, float horizontalResolution = 96f, float verticalResolution = 96f) { // Create a new "clean" image - Bitmap newImage = new Bitmap(width, height, format); + Bitmap newImage = new(width, height, format); newImage.SetResolution(horizontalResolution, verticalResolution); if (format != PixelFormat.Format8bppIndexed) { @@ -1399,7 +1390,7 @@ namespace Greenshot.Base.Core toCount &= 0xffffff; } - using IFastBitmap bb = FastBitmap.Create((Bitmap) sourceImage); + using IFastBitmap bb = FastBitmap.Create((Bitmap)sourceImage); for (int y = 0; y < bb.Height; y++) { for (int x = 0; x < bb.Width; x++) @@ -1436,32 +1427,32 @@ namespace Greenshot.Base.Core int destX = 0; int destY = 0; - var nPercentW = newWidth / (float) sourceImage.Width; - var nPercentH = newHeight / (float) sourceImage.Height; + var nPercentW = newWidth / (float)sourceImage.Width; + var nPercentH = newHeight / (float)sourceImage.Height; if (maintainAspectRatio) { - if ((int) nPercentW == 1) + if ((int)nPercentW == 1) { nPercentW = nPercentH; if (canvasUseNewSize) { - destX = Math.Max(0, Convert.ToInt32((newWidth - sourceImage.Width * nPercentW) / 2)); + destX = Math.Max(0, Convert.ToInt32((newWidth - (sourceImage.Width * nPercentW)) / 2)); } } - else if ((int) nPercentH == 1) + else if ((int)nPercentH == 1) { nPercentH = nPercentW; if (canvasUseNewSize) { - destY = Math.Max(0, Convert.ToInt32((newHeight - sourceImage.Height * nPercentH) / 2)); + destY = Math.Max(0, Convert.ToInt32((newHeight - (sourceImage.Height * nPercentH)) / 2)); } } - else if ((int) nPercentH != 0 && nPercentH < nPercentW) + else if ((int)nPercentH != 0 && nPercentH < nPercentW) { nPercentW = nPercentH; if (canvasUseNewSize) { - destX = Math.Max(0, Convert.ToInt32((newWidth - sourceImage.Width * nPercentW) / 2)); + destX = Math.Max(0, Convert.ToInt32((newWidth - (sourceImage.Width * nPercentW)) / 2)); } } else @@ -1469,13 +1460,13 @@ namespace Greenshot.Base.Core nPercentH = nPercentW; if (canvasUseNewSize) { - destY = Math.Max(0, Convert.ToInt32((newHeight - sourceImage.Height * nPercentH) / 2)); + destY = Math.Max(0, Convert.ToInt32((newHeight - (sourceImage.Height * nPercentH)) / 2)); } } } - int destWidth = (int) (sourceImage.Width * nPercentW); - int destHeight = (int) (sourceImage.Height * nPercentH); + int destWidth = (int)(sourceImage.Width * nPercentW); + int destHeight = (int)(sourceImage.Height * nPercentH); if (newWidth == 0) { newWidth = destWidth; @@ -1490,25 +1481,25 @@ namespace Greenshot.Base.Core if (maintainAspectRatio && canvasUseNewSize) { newImage = CreateEmpty(newWidth, newHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); - matrix?.Scale((float) newWidth / sourceImage.Width, (float) newHeight / sourceImage.Height, MatrixOrder.Append); + matrix?.Scale((float)newWidth / sourceImage.Width, (float)newHeight / sourceImage.Height, MatrixOrder.Append); } else { newImage = CreateEmpty(destWidth, destHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); - matrix?.Scale((float) destWidth / sourceImage.Width, (float) destHeight / sourceImage.Height, MatrixOrder.Append); + matrix?.Scale((float)destWidth / sourceImage.Width, (float)destHeight / sourceImage.Height, MatrixOrder.Append); } using (Graphics graphics = Graphics.FromImage(newImage)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - using ImageAttributes wrapMode = new ImageAttributes(); + using ImageAttributes wrapMode = new(); wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(sourceImage, new NativeRect(destX, destY, destWidth, destHeight), 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel, wrapMode); } return newImage; } - + /// /// Rotate the image /// @@ -1562,12 +1553,7 @@ namespace Greenshot.Base.Core { return PixelFormat.Format24bppRgb; } - if (pixelFormat == PixelFormats.Bgr32) - { - return PixelFormat.Format32bppRgb; - } - - throw new NotSupportedException($"Can't map {pixelFormat}."); + return pixelFormat == PixelFormats.Bgr32 ? PixelFormat.Format32bppRgb : throw new NotSupportedException($"Can't map {pixelFormat}."); } /// @@ -1605,7 +1591,7 @@ namespace Greenshot.Base.Core { var pixelFormat = bitmapSource.Format.Map(); - Bitmap bitmap = new Bitmap(bitmapSource.PixelWidth, bitmapSource.PixelHeight, pixelFormat); + Bitmap bitmap = new(bitmapSource.PixelWidth, bitmapSource.PixelHeight, pixelFormat); BitmapData data = bitmap.LockBits(new NativeRect(NativePoint.Empty, bitmap.Size), ImageLockMode.WriteOnly, pixelFormat); bitmapSource.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bitmap.UnlockBits(data); diff --git a/src/Greenshot.Base/Core/ImageIO.cs b/src/Greenshot.Base/Core/ImageIO.cs index 9d6bbf1cd..260f886f9 100644 --- a/src/Greenshot.Base/Core/ImageIO.cs +++ b/src/Greenshot.Base/Core/ImageIO.cs @@ -48,7 +48,7 @@ namespace Greenshot.Base.Core private static readonly ILog Log = LogManager.GetLogger(typeof(ImageIO)); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131; - private static readonly Cache TmpFileCache = new Cache(10 * 60 * 60, RemoveExpiredTmpFile); + private static readonly Cache TmpFileCache = new(10 * 60 * 60, RemoveExpiredTmpFile); /// /// Creates a PropertyItem (Metadata) to store with the image. @@ -66,7 +66,7 @@ namespace Greenshot.Base.Core ConstructorInfo ci = typeof(PropertyItem).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new Type[] { }, null); - propertyItem = (PropertyItem) ci.Invoke(null); + propertyItem = (PropertyItem)ci.Invoke(null); // Make sure it's of type string propertyItem.Type = 2; // Set the ID @@ -182,10 +182,10 @@ namespace Greenshot.Base.Core } Image tmpImage; - if (outputSettings.Effects != null && outputSettings.Effects.Count > 0) + if (outputSettings.Effects?.Count > 0) { // apply effects, if there are any - using (Matrix matrix = new Matrix()) + using (Matrix matrix = new()) { tmpImage = ImageHelper.ApplyEffects(imageToSave, outputSettings.Effects, matrix); } @@ -211,7 +211,7 @@ namespace Greenshot.Base.Core bool isAlpha = Image.IsAlphaPixelFormat(imageToSave.PixelFormat); if (outputSettings.ReduceColors || (!isAlpha && CoreConfig.OutputFileAutoReduceColors)) { - using var quantizer = new WuQuantizer((Bitmap) imageToSave); + using var quantizer = new WuQuantizer((Bitmap)imageToSave); int colorCount = quantizer.GetColorCount(); Log.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount); if (!outputSettings.ReduceColors && colorCount >= 256) @@ -304,7 +304,7 @@ namespace Greenshot.Base.Core // check whether path exists - if not create it if (path != null) { - DirectoryInfo di = new DirectoryInfo(path); + DirectoryInfo di = new(path); if (!di.Exists) { Directory.CreateDirectory(di.FullName); @@ -313,14 +313,14 @@ namespace Greenshot.Base.Core if (!allowOverwrite && File.Exists(fullPath)) { - ArgumentException throwingException = new ArgumentException("File '" + fullPath + "' already exists."); + ArgumentException throwingException = new("File '" + fullPath + "' already exists."); throwingException.Data.Add("fullPath", fullPath); throw throwingException; } Log.DebugFormat("Saving surface to {0}", fullPath); // Create the stream and call SaveToStream - using (FileStream stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) + using (FileStream stream = new(fullPath, FileMode.Create, FileAccess.Write)) { SaveToStream(surface, stream, outputSettings); } @@ -343,7 +343,7 @@ namespace Greenshot.Base.Core OutputFormat format = OutputFormat.png; try { - format = (OutputFormat) Enum.Parse(typeof(OutputFormat), extension.ToLower()); + format = (OutputFormat)Enum.Parse(typeof(OutputFormat), extension.ToLower()); } catch (ArgumentException ae) { @@ -362,17 +362,17 @@ namespace Greenshot.Base.Core public static string SaveWithDialog(ISurface surface, ICaptureDetails captureDetails) { string returnValue = null; - using (SaveImageFileDialog saveImageFileDialog = new SaveImageFileDialog(captureDetails)) + using (SaveImageFileDialog saveImageFileDialog = new(captureDetails)) { DialogResult dialogResult = saveImageFileDialog.ShowDialog(); if (!dialogResult.Equals(DialogResult.OK)) return returnValue; try { string fileNameWithExtension = saveImageFileDialog.FileNameWithExtension; - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(FormatForFilename(fileNameWithExtension)); + SurfaceOutputSettings outputSettings = new(FormatForFilename(fileNameWithExtension)); if (CoreConfig.OutputFilePromptQuality) { - QualityDialog qualityDialog = new QualityDialog(outputSettings); + QualityDialog qualityDialog = new(outputSettings); qualityDialog.ShowDialog(); } @@ -410,7 +410,7 @@ namespace Greenshot.Base.Core // Prevent problems with "other characters", which causes a problem in e.g. Outlook 2007 or break our HTML filename = Regex.Replace(filename, @"[^\d\w\.]", "_"); // Remove multiple "_" - filename = Regex.Replace(filename, @"_+", "_"); + filename = Regex.Replace(filename, "_+", "_"); string tmpFile = Path.Combine(Path.GetTempPath(), filename); Log.Debug("Creating TMP File: " + tmpFile); @@ -495,7 +495,7 @@ namespace Greenshot.Base.Core /// /// Cleanup all created tmpfiles - /// + /// public static void RemoveTmpFiles() { foreach (string tmpFile in TmpFileCache.Elements) @@ -625,7 +625,7 @@ namespace Greenshot.Base.Core // Start at -14 read "GreenshotXX.YY" (XX=Major, YY=Minor) const int markerSize = 14; surfaceFileStream.Seek(-markerSize, SeekOrigin.End); - using (StreamReader streamReader = new StreamReader(surfaceFileStream)) + using (StreamReader streamReader = new(surfaceFileStream)) { var greenshotMarker = streamReader.ReadToEnd(); if (!greenshotMarker.StartsWith("Greenshot")) @@ -636,7 +636,7 @@ namespace Greenshot.Base.Core Log.InfoFormat("Greenshot file format: {0}", greenshotMarker); const int filesizeLocation = 8 + markerSize; surfaceFileStream.Seek(-filesizeLocation, SeekOrigin.End); - using BinaryReader reader = new BinaryReader(surfaceFileStream); + using BinaryReader reader = new(surfaceFileStream); long bytesWritten = reader.ReadInt64(); surfaceFileStream.Seek(-(bytesWritten + filesizeLocation), SeekOrigin.End); returnSurface.LoadElementsFromStream(surfaceFileStream); diff --git a/src/Greenshot.Base/Core/JSONHelper.cs b/src/Greenshot.Base/Core/JSONHelper.cs index 7e7ac97eb..df08540c0 100644 --- a/src/Greenshot.Base/Core/JSONHelper.cs +++ b/src/Greenshot.Base/Core/JSONHelper.cs @@ -17,10 +17,10 @@ namespace Greenshot.Base.Core /// /// This parses a JSON response, a modified version of the code found at: /// See: https://techblog.procurios.nl/k/n618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html - /// + /// /// This file is under the MIT License, which is GPL Compatible and according to: https://en.wikipedia.org/wiki/MIT_License /// can be used under the GPL "umbrella". - /// + /// /// TODO: code should be replaced when upgrading to .NET 3.5 or higher!! /// public class JSONHelper @@ -80,7 +80,7 @@ namespace Greenshot.Base.Core // { NextToken(json, ref index); - bool done = false; + const bool done = false; while (!done) { token = LookAhead(json, index); @@ -138,7 +138,7 @@ namespace Greenshot.Base.Core // [ NextToken(json, ref index); - bool done = false; + const bool done = false; while (!done) { int token = LookAhead(json, index); @@ -202,12 +202,12 @@ namespace Greenshot.Base.Core protected static string ParseString(char[] json, ref int index, ref bool success) { - StringBuilder s = new StringBuilder(BUILDER_CAPACITY); + StringBuilder s = new(BUILDER_CAPACITY); EatWhitespace(json, ref index); // " - var c = json[index++]; + _ = json[index++]; bool complete = false; while (!complete) @@ -217,7 +217,7 @@ namespace Greenshot.Base.Core break; } - c = json[index++]; + char c = json[index++]; if (c == '"') { complete = true; @@ -275,7 +275,7 @@ namespace Greenshot.Base.Core } // convert the integer codepoint to a unicode char and add to string - s.Append(char.ConvertFromUtf32((int) codePoint)); + s.Append(char.ConvertFromUtf32((int)codePoint)); // skip 4 chars index += 4; } @@ -305,7 +305,7 @@ namespace Greenshot.Base.Core EatWhitespace(json, ref index); int lastIndex = GetLastIndexOfNumber(json, index); - int charLength = (lastIndex - index) + 1; + int charLength = lastIndex - index + 1; success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out var number); diff --git a/src/Greenshot.Base/Core/Language.cs b/src/Greenshot.Base/Core/Language.cs index 4627a10fc..5a413eb24 100644 --- a/src/Greenshot.Base/Core/Language.cs +++ b/src/Greenshot.Base/Core/Language.cs @@ -43,10 +43,10 @@ namespace Greenshot.Base.Core private static readonly Dictionary> LanguageFiles = new(); private static readonly Dictionary HelpFiles = new(); private const string DefaultLanguage = "en-US"; - private const string HelpFilenamePattern = @"help-*.html"; - private const string LanguageFilenamePattern = @"language*.xml"; - private static readonly Regex PrefixRegexp = new(@"language_([a-zA-Z0-9]+).*"); - private static readonly Regex IetfRegexp = new(@"^.*([a-zA-Z]{2,3}-([a-zA-Z]{1,2})|[a-zA-Z]{2,3}-x-[a-zA-Z]+)$"); + private const string HelpFilenamePattern = "help-*.html"; + private const string LanguageFilenamePattern = "language*.xml"; + private static readonly Regex PrefixRegexp = new("language_([a-zA-Z0-9]+).*"); + private static readonly Regex IetfRegexp = new("^.*([a-zA-Z]{2,3}-([a-zA-Z]{1,2})|[a-zA-Z]{2,3}-x-[a-zA-Z]+)$"); private const string LanguageGroupsKey = @"SYSTEM\CurrentControlSet\Control\Nls\Language Groups"; private static readonly List UnsupportedLanguageGroups = new(); private static readonly Dictionary Resources = new(); @@ -88,7 +88,7 @@ namespace Greenshot.Base.Core // Startup path if (applicationFolder != null) { - AddPath(Path.Combine(applicationFolder, @"Languages")); + AddPath(Path.Combine(applicationFolder, "Languages")); } } catch (Exception pathException) @@ -104,7 +104,7 @@ namespace Greenshot.Base.Core string[] groups = languageGroupsKey.GetValueNames(); foreach (string group in groups) { - string groupValue = (string) languageGroupsKey.GetValue(group); + string groupValue = (string)languageGroupsKey.GetValue(group); bool isGroupNotInstalled = "0".Equals(groupValue); if (isGroupNotInstalled) { @@ -218,7 +218,7 @@ namespace Greenshot.Base.Core { Resources.Clear(); LoadFiles(DefaultLanguage); - if (_currentLanguage != null && !_currentLanguage.Equals(DefaultLanguage)) + if (_currentLanguage?.Equals(DefaultLanguage) == false) { LoadFiles(_currentLanguage); } @@ -239,7 +239,7 @@ namespace Greenshot.Base.Core } else { - if (_currentLanguage == null || !_currentLanguage.Equals(ietf)) + if (_currentLanguage?.Equals(ietf) != true) { _currentLanguage = ietf; Reload(); @@ -332,12 +332,7 @@ namespace Greenshot.Base.Core { get { - if (HelpFiles.ContainsKey(_currentLanguage)) - { - return HelpFiles[_currentLanguage]; - } - - return HelpFiles[DefaultLanguage]; + return HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage]; } } @@ -350,7 +345,7 @@ namespace Greenshot.Base.Core Log.InfoFormat("Loading language file {0}", languageFile.Filepath); try { - XmlDocument xmlDocument = new XmlDocument(); + XmlDocument xmlDocument = new(); xmlDocument.Load(languageFile.Filepath); XmlNodeList resourceNodes = xmlDocument.GetElementsByTagName("resource"); foreach (XmlNode resourceNode in resourceNodes) @@ -571,7 +566,7 @@ namespace Greenshot.Base.Core } return null; } - + /// /// Check if a resource with prefix.key exists /// @@ -590,12 +585,7 @@ namespace Greenshot.Base.Core /// true if available public static bool HasKey(string key) { - if (key == null) - { - return false; - } - - return Resources.ContainsKey(key); + return key != null && Resources.ContainsKey(key); } /// @@ -642,12 +632,7 @@ namespace Greenshot.Base.Core { string typename = key.GetType().Name; string enumKey = typename + "." + key; - if (HasKey(enumKey)) - { - return GetString(enumKey); - } - - return key.ToString(); + return HasKey(enumKey) ? GetString(enumKey) : key.ToString(); } /// @@ -657,12 +642,7 @@ namespace Greenshot.Base.Core /// resource or a "string ###key### not found" public static string GetString(Enum key) { - if (key == null) - { - return null; - } - - return GetString(key.ToString()); + return key == null ? null : GetString(key.ToString()); } /// @@ -673,12 +653,7 @@ namespace Greenshot.Base.Core /// resource or a "string ###prefix.key### not found" public static string GetString(string prefix, Enum key) { - if (key == null) - { - return null; - } - - return GetString(prefix + "." + key); + return key == null ? null : GetString(prefix + "." + key); } /// @@ -704,12 +679,7 @@ namespace Greenshot.Base.Core return null; } - if (!Resources.TryGetValue(key, out var returnValue)) - { - return "string ###" + key + "### not found"; - } - - return returnValue; + return !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : returnValue; } /// @@ -755,12 +725,7 @@ namespace Greenshot.Base.Core /// formatted resource or a "string ###key### not found" public static string GetFormattedString(string key, object param) { - if (!Resources.TryGetValue(key, out var returnValue)) - { - return "string ###" + key + "### not found"; - } - - return string.Format(returnValue, param); + return !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : string.Format(returnValue, param); } } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/LanguageFile.cs b/src/Greenshot.Base/Core/LanguageFile.cs index b9f8a57c4..5b362d032 100644 --- a/src/Greenshot.Base/Core/LanguageFile.cs +++ b/src/Greenshot.Base/Core/LanguageFile.cs @@ -57,7 +57,7 @@ namespace Greenshot.Base.Core return false; } } - else if (other != null && other.Version != null) + else if (other?.Version != null) { return false; } diff --git a/src/Greenshot.Base/Core/LogHelper.cs b/src/Greenshot.Base/Core/LogHelper.cs index 42cabddd4..290431a47 100644 --- a/src/Greenshot.Base/Core/LogHelper.cs +++ b/src/Greenshot.Base/Core/LogHelper.cs @@ -88,12 +88,11 @@ namespace Greenshot.Base.Core // Get the logfile name try { - if (((Hierarchy) LogManager.GetRepository()).Root.Appenders.Count > 0) + if (((Hierarchy)LogManager.GetRepository()).Root.Appenders.Count > 0) { - foreach (IAppender appender in ((Hierarchy) LogManager.GetRepository()).Root.Appenders) + foreach (IAppender appender in ((Hierarchy)LogManager.GetRepository()).Root.Appenders) { - var fileAppender = appender as FileAppender; - if (fileAppender != null) + if (appender is FileAppender fileAppender) { return fileAppender.File; } @@ -117,7 +116,7 @@ namespace Greenshot.Base.Core { protected override void Convert(TextWriter writer, object state) { - Environment.SpecialFolder specialFolder = (Environment.SpecialFolder) Enum.Parse(typeof(Environment.SpecialFolder), Option, true); + Environment.SpecialFolder specialFolder = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), Option, true); writer.Write(Environment.GetFolderPath(specialFolder)); } } diff --git a/src/Greenshot.Base/Core/NetworkHelper.cs b/src/Greenshot.Base/Core/NetworkHelper.cs index 88cfff569..01390f094 100644 --- a/src/Greenshot.Base/Core/NetworkHelper.cs +++ b/src/Greenshot.Base/Core/NetworkHelper.cs @@ -77,7 +77,7 @@ namespace Greenshot.Base.Core public static MemoryStream GetAsMemoryStream(string url) { var request = CreateWebRequest(url); - using var response = (HttpWebResponse) request.GetResponse(); + using var response = (HttpWebResponse)request.GetResponse(); var memoryStream = new MemoryStream(); using (var responseStream = response.GetResponseStream()) { @@ -99,7 +99,7 @@ namespace Greenshot.Base.Core var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances(); var extensions = string.Join("|", fileFormatHandlers.ExtensionsFor(FileFormatHandlerActions.LoadFromStream)); - var imageUrlRegex = new Regex($@"(http|https)://.*(?{extensions})"); + var imageUrlRegex = new Regex($"(http|https)://.*(?{extensions})"); var match = imageUrlRegex.Match(url); try { @@ -162,7 +162,7 @@ namespace Greenshot.Base.Core var extensions = string.Join("|", fileFormatHandlers.ExtensionsFor(FileFormatHandlerActions.LoadFromStream)); - var imageUrlRegex = new Regex($@"(http|https)://.*(?{extensions})"); + var imageUrlRegex = new Regex($"(http|https)://.*(?{extensions})"); var match = imageUrlRegex.Match(url); try { @@ -250,7 +250,7 @@ namespace Greenshot.Base.Core /// WebRequest public static HttpWebRequest CreateWebRequest(Uri uri) { - var webRequest = (HttpWebRequest) WebRequest.Create(uri); + var webRequest = (HttpWebRequest)WebRequest.Create(uri); webRequest.Proxy = Config.UseProxy ? CreateProxy(uri) : null; // Make sure the default credentials are available webRequest.Credentials = CredentialCache.DefaultCredentials; @@ -352,7 +352,6 @@ namespace Greenshot.Base.Core } return result.ToString(); - } /// @@ -617,7 +616,7 @@ namespace Greenshot.Base.Core Stream responseStream = response.GetResponseStream(); if (responseStream != null) { - using StreamReader reader = new StreamReader(responseStream, true); + using StreamReader reader = new(responseStream, true); responseData = reader.ReadToEnd(); } } @@ -638,9 +637,9 @@ namespace Greenshot.Base.Core bool isHttpError = false; try { - response = (HttpWebResponse) webRequest.GetResponse(); + response = (HttpWebResponse)webRequest.GetResponse(); Log.InfoFormat("Response status: {0}", response.StatusCode); - isHttpError = (int) response.StatusCode >= 300; + isHttpError = (int)response.StatusCode >= 300; if (isHttpError) { Log.ErrorFormat("HTTP error {0}", response.StatusCode); @@ -655,7 +654,7 @@ namespace Greenshot.Base.Core } catch (WebException e) { - response = (HttpWebResponse) e.Response; + response = (HttpWebResponse)e.Response; HttpStatusCode statusCode = HttpStatusCode.Unused; if (response != null) { @@ -731,9 +730,9 @@ namespace Greenshot.Base.Core /// string public string ToBase64String(Base64FormattingOptions formattingOptions) { - using MemoryStream stream = new MemoryStream(); + using MemoryStream stream = new(); ImageIO.SaveToStream(_surface, stream, _outputSettings); - return Convert.ToBase64String(stream.GetBuffer(), 0, (int) stream.Length, formattingOptions); + return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions); } /// @@ -743,7 +742,7 @@ namespace Greenshot.Base.Core /// byte[] public byte[] ToByteArray() { - using MemoryStream stream = new MemoryStream(); + using MemoryStream stream = new(); ImageIO.SaveToStream(_surface, stream, _outputSettings); return stream.ToArray(); } diff --git a/src/Greenshot.Base/Core/OAuth/LocalJsonReceiver.cs b/src/Greenshot.Base/Core/OAuth/LocalJsonReceiver.cs index ffb6867bf..41c6bfc81 100644 --- a/src/Greenshot.Base/Core/OAuth/LocalJsonReceiver.cs +++ b/src/Greenshot.Base/Core/OAuth/LocalJsonReceiver.cs @@ -39,7 +39,7 @@ namespace Greenshot.Base.Core.OAuth public class LocalJsonReceiver { private static readonly ILog Log = LogManager.GetLogger(typeof(LocalJsonReceiver)); - private readonly ManualResetEvent _ready = new ManualResetEvent(true); + private readonly ManualResetEvent _ready = new(true); private IDictionary _returnValues; /// @@ -121,7 +121,7 @@ namespace Greenshot.Base.Core.OAuth /// IAsyncResult private void ListenerCallback(IAsyncResult result) { - HttpListener listener = (HttpListener) result.AsyncState; + HttpListener listener = (HttpListener)result.AsyncState; //If not listening return immediately as this method is called one last time after Close() if (!listener.IsListening) @@ -192,7 +192,7 @@ namespace Greenshot.Base.Core.OAuth try { listener.Start(); - return ((IPEndPoint) listener.LocalEndpoint).Port; + return ((IPEndPoint)listener.LocalEndpoint).Port; } finally { diff --git a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs index f079598a3..fe9ff0498 100644 --- a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs +++ b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs @@ -38,7 +38,7 @@ namespace Greenshot.Base.Core.OAuth public class LocalServerCodeReceiver { private static readonly ILog Log = LogManager.GetLogger(typeof(LocalServerCodeReceiver)); - private readonly ManualResetEvent _ready = new ManualResetEvent(true); + private readonly ManualResetEvent _ready = new(true); /// /// The call back format. Expects one port parameter. @@ -75,12 +75,7 @@ Greenshot received information from CloudServiceName. You can close this browser { get { - if (!string.IsNullOrEmpty(_redirectUri)) - { - return _redirectUri; - } - - return _redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort()); + return !string.IsNullOrEmpty(_redirectUri) ? _redirectUri : (_redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort())); } } @@ -88,7 +83,6 @@ Greenshot received information from CloudServiceName. You can close this browser private readonly IDictionary _returnValues = new Dictionary(); - /// /// The OAuth code receiver /// @@ -142,7 +136,7 @@ Greenshot received information from CloudServiceName. You can close this browser /// IAsyncResult private void ListenerCallback(IAsyncResult result) { - HttpListener listener = (HttpListener) result.AsyncState; + HttpListener listener = (HttpListener)result.AsyncState; //If not listening return immediately as this method is called one last time after Close() if (!listener.IsListening) @@ -153,7 +147,6 @@ Greenshot received information from CloudServiceName. You can close this browser // Use EndGetContext to complete the asynchronous operation. HttpListenerContext context = listener.EndGetContext(result); - // Handle request HttpListenerRequest request = context.Request; try @@ -199,7 +192,7 @@ Greenshot received information from CloudServiceName. You can close this browser try { listener.Start(); - return ((IPEndPoint) listener.LocalEndpoint).Port; + return ((IPEndPoint)listener.LocalEndpoint).Port; } finally { diff --git a/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs b/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs index 8c77a0fff..d18c2dcf6 100644 --- a/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs +++ b/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs @@ -82,7 +82,7 @@ namespace Greenshot.Base.Core.OAuth throw new Exception($"{refreshTokenResult["error"]} - {refreshTokenResult["error_description"]}"); } - throw new Exception((string) refreshTokenResult["error"]); + throw new Exception((string)refreshTokenResult["error"]); } // gives as described here: https://developers.google.com/identity/protocols/OAuth2InstalledApp @@ -92,12 +92,12 @@ namespace Greenshot.Base.Core.OAuth // "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI" if (refreshTokenResult.ContainsKey(AccessToken)) { - settings.AccessToken = (string) refreshTokenResult[AccessToken]; + settings.AccessToken = (string)refreshTokenResult[AccessToken]; } if (refreshTokenResult.ContainsKey(RefreshToken)) { - settings.RefreshToken = (string) refreshTokenResult[RefreshToken]; + settings.RefreshToken = (string)refreshTokenResult[RefreshToken]; } if (refreshTokenResult.ContainsKey(ExpiresIn)) @@ -105,7 +105,7 @@ namespace Greenshot.Base.Core.OAuth object seconds = refreshTokenResult[ExpiresIn]; if (seconds != null) { - settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double) seconds); + settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double)seconds); } } @@ -187,7 +187,7 @@ namespace Greenshot.Base.Core.OAuth IDictionary accessTokenResult = JSONHelper.JsonDecode(accessTokenJsonResult); if (accessTokenResult.ContainsKey("error")) { - if ("invalid_grant" == (string) accessTokenResult["error"]) + if ((string)accessTokenResult["error"] == "invalid_grant") { // Refresh token has also expired, we need a new one! settings.RefreshToken = null; @@ -202,19 +202,19 @@ namespace Greenshot.Base.Core.OAuth throw new Exception($"{accessTokenResult["error"]} - {accessTokenResult["error_description"]}"); } - throw new Exception((string) accessTokenResult["error"]); + throw new Exception((string)accessTokenResult["error"]); } if (accessTokenResult.ContainsKey(AccessToken)) { - settings.AccessToken = (string) accessTokenResult[AccessToken]; + settings.AccessToken = (string)accessTokenResult[AccessToken]; settings.AccessTokenExpires = DateTimeOffset.MaxValue; } if (accessTokenResult.ContainsKey(RefreshToken)) { // Refresh the refresh token :) - settings.RefreshToken = (string) accessTokenResult[RefreshToken]; + settings.RefreshToken = (string)accessTokenResult[RefreshToken]; } if (accessTokenResult.ContainsKey(ExpiresIn)) @@ -222,7 +222,7 @@ namespace Greenshot.Base.Core.OAuth object seconds = accessTokenResult[ExpiresIn]; if (seconds != null) { - settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double) seconds); + settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double)seconds); } } } @@ -288,7 +288,7 @@ namespace Greenshot.Base.Core.OAuth throw new Exception(errorDescription); } - if ("access_denied" == error) + if (error == "access_denied") { throw new UnauthorizedAccessException("Access denied"); } @@ -324,7 +324,7 @@ namespace Greenshot.Base.Core.OAuth throw new ArgumentNullException(nameof(settings.BrowserSize)); } - OAuthLoginForm loginForm = new OAuthLoginForm($"Authorize {settings.CloudServiceName}", settings.BrowserSize, settings.FormattedAuthUrl, settings.RedirectUrl); + OAuthLoginForm loginForm = new($"Authorize {settings.CloudServiceName}", settings.BrowserSize, settings.FormattedAuthUrl, settings.RedirectUrl); loginForm.ShowDialog(); if (!loginForm.IsOk) return false; if (loginForm.CallbackParameters.TryGetValue(Code, out var code) && !string.IsNullOrEmpty(code)) @@ -362,7 +362,7 @@ namespace Greenshot.Base.Core.OAuth throw new Exception(errorDescription); } - if ("access_denied" == error) + if (error == "access_denied") { throw new UnauthorizedAccessException("Access denied"); } diff --git a/src/Greenshot.Base/Core/OAuth/OAuthSession.cs b/src/Greenshot.Base/Core/OAuth/OAuthSession.cs index d0cc833d8..340c46297 100644 --- a/src/Greenshot.Base/Core/OAuth/OAuthSession.cs +++ b/src/Greenshot.Base/Core/OAuth/OAuthSession.cs @@ -58,11 +58,9 @@ namespace Greenshot.Base.Core.OAuth protected const string HMACSHA1SignatureType = "HMAC-SHA1"; protected const string PlainTextSignatureType = "PLAINTEXT"; - protected static Random random = new Random(); + protected static Random random = new(); protected const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; - - private string _userAgent = "Greenshot"; private IDictionary _requestTokenResponseParameters; public IDictionary RequestTokenParameters { get; } = new Dictionary(); @@ -94,11 +92,7 @@ namespace Greenshot.Base.Core.OAuth public bool UseMultipartFormData { get; set; } - public string UserAgent - { - get { return _userAgent; } - set { _userAgent = value; } - } + public string UserAgent { get; set; } = "Greenshot"; public string CallbackUrl { get; set; } = "https://getgreenshot.org"; @@ -166,7 +160,7 @@ namespace Greenshot.Base.Core.OAuth queryParameters = new SortedDictionary(queryParameters); - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); foreach (string key in queryParameters.Keys) { if (queryParameters[key] is string) @@ -189,7 +183,7 @@ namespace Greenshot.Base.Core.OAuth /// Returns a Url encoded string (unicode) with UTF-8 encoded % values public static string UrlEncode3986(string value) { - StringBuilder result = new StringBuilder(); + StringBuilder result = new(); foreach (char symbol in value) { @@ -269,12 +263,12 @@ namespace Greenshot.Base.Core.OAuth { if (string.IsNullOrEmpty(Token)) { - Exception e = new Exception("The request token is not set, service responded with: " + requestTokenResponse); + Exception e = new("The request token is not set, service responded with: " + requestTokenResponse); throw e; } Log.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink); - OAuthLoginForm oAuthLoginForm = new OAuthLoginForm(LoginTitle, BrowserSize, AuthorizationLink, CallbackUrl); + OAuthLoginForm oAuthLoginForm = new(LoginTitle, BrowserSize, AuthorizationLink, CallbackUrl); oAuthLoginForm.ShowDialog(); if (oAuthLoginForm.IsOk) { @@ -294,12 +288,7 @@ namespace Greenshot.Base.Core.OAuth if (CheckVerifier) { - if (!string.IsNullOrEmpty(Verifier)) - { - return Token; - } - - return null; + return !string.IsNullOrEmpty(Verifier) ? Token : null; } return Token; @@ -313,7 +302,7 @@ namespace Greenshot.Base.Core.OAuth { if (string.IsNullOrEmpty(Token) || (CheckVerifier && string.IsNullOrEmpty(Verifier))) { - Exception e = new Exception("The request token and verifier were not set"); + Exception e = new("The request token and verifier were not set"); throw e; } @@ -490,7 +479,7 @@ namespace Greenshot.Base.Core.OAuth Token = null; TokenSecret = null; // Remove oauth keys, so they aren't added double - List keysToDelete = new List(); + List keysToDelete = new(); foreach (string parameterKey in parametersToSign.Keys) { if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) @@ -529,13 +518,13 @@ namespace Greenshot.Base.Core.OAuth } // Build the signature base - StringBuilder signatureBase = new StringBuilder(); + StringBuilder signatureBase = new(); // Add Method to signature base signatureBase.Append(method).Append("&"); // Add normalized URL - Uri url = new Uri(requestUrl); + Uri url = new(requestUrl); string normalizedUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host); if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443))) { @@ -586,7 +575,7 @@ namespace Greenshot.Base.Core.OAuth break; default: // Generate Signature and add it to the parameters - HMACSHA1 hmacsha1 = new HMACSHA1 + HMACSHA1 hmacsha1 = new() { Key = Encoding.UTF8.GetBytes(key) }; @@ -655,7 +644,7 @@ namespace Greenshot.Base.Core.OAuth // Create webrequest HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestUrl, method); webRequest.ServicePoint.Expect100Continue = false; - webRequest.UserAgent = _userAgent; + webRequest.UserAgent = UserAgent; if (UseHttpHeadersForAuthorization && authHeader != null) { @@ -679,12 +668,11 @@ namespace Greenshot.Base.Core.OAuth } else { - StringBuilder form = new StringBuilder(); + StringBuilder form = new(); foreach (string parameterKey in requestParameters.Keys) { - var binaryParameter = parameters[parameterKey] as IBinaryContainer; form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), - binaryParameter != null ? UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)) : UrlEncode3986($"{parameters[parameterKey]}")); + parameters[parameterKey] is IBinaryContainer binaryParameter ? UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)) : UrlEncode3986($"{parameters[parameterKey]}")); } // Remove trailing & diff --git a/src/Greenshot.Base/Core/ObjectExtensions.cs b/src/Greenshot.Base/Core/ObjectExtensions.cs index 45f0585b1..22bfa00f3 100644 --- a/src/Greenshot.Base/Core/ObjectExtensions.cs +++ b/src/Greenshot.Base/Core/ObjectExtensions.cs @@ -57,7 +57,7 @@ namespace Greenshot.Base.Core using var stream = new MemoryStream(); formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); - return (T) formatter.Deserialize(stream); + return (T)formatter.Deserialize(stream); } /// diff --git a/src/Greenshot.Base/Core/PluginUtils.cs b/src/Greenshot.Base/Core/PluginUtils.cs index d41e545a5..9e51c122c 100644 --- a/src/Greenshot.Base/Core/PluginUtils.cs +++ b/src/Greenshot.Base/Core/PluginUtils.cs @@ -84,7 +84,7 @@ namespace Greenshot.Base.Core if (key != null) { // "" is the default key, which should point to the requested location - return (string) key.GetValue(string.Empty); + return (string)key.GetValue(string.Empty); } } diff --git a/src/Greenshot.Base/Core/QuantizerHelper.cs b/src/Greenshot.Base/Core/QuantizerHelper.cs index ec414968b..efdb78d82 100644 --- a/src/Greenshot.Base/Core/QuantizerHelper.cs +++ b/src/Greenshot.Base/Core/QuantizerHelper.cs @@ -130,7 +130,7 @@ namespace Greenshot.Base.Core { this.sourceBitmap = sourceBitmap; // Make sure the color count variables are reset - BitArray bitArray = new BitArray((int) Math.Pow(2, 24)); + BitArray bitArray = new((int)Math.Pow(2, 24)); colorCount = 0; // creates all the cubes @@ -167,7 +167,6 @@ namespace Greenshot.Base.Core // Use a bitmap to store the initial match, which is just as good as an array and saves us 2x the storage using IFastBitmap sourceFastBitmap = FastBitmap.Create(sourceBitmap); - IFastBitmapWithBlend sourceFastBitmapWithBlend = sourceFastBitmap as IFastBitmapWithBlend; sourceFastBitmap.Lock(); using FastChunkyBitmap destinationFastBitmap = FastBitmap.CreateEmpty(sourceBitmap.Size, PixelFormat.Format8bppIndexed, Color.White) as FastChunkyBitmap; destinationFastBitmap.Lock(); @@ -176,7 +175,7 @@ namespace Greenshot.Base.Core for (int x = 0; x < sourceFastBitmap.Width; x++) { Color color; - if (sourceFastBitmapWithBlend == null) + if (sourceFastBitmap is not IFastBitmapWithBlend sourceFastBitmapWithBlend) { color = sourceFastBitmap.GetColorAt(x, y); } @@ -207,7 +206,7 @@ namespace Greenshot.Base.Core // Store the initial "match" int paletteIndex = (indexRed << 10) + (indexRed << 6) + indexRed + (indexGreen << 5) + indexGreen + indexBlue; - destinationFastBitmap.SetColorIndexAt(x, y, (byte) (paletteIndex & 0xff)); + destinationFastBitmap.SetColorIndexAt(x, y, (byte)(paletteIndex & 0xff)); } } @@ -228,13 +227,12 @@ namespace Greenshot.Base.Core /// Bitmap public Bitmap SimpleReindex() { - List colors = new List(); - Dictionary lookup = new Dictionary(); + List colors = new(); + Dictionary lookup = new(); using (FastChunkyBitmap bbbDest = FastBitmap.Create(resultBitmap) as FastChunkyBitmap) { bbbDest.Lock(); using IFastBitmap bbbSrc = FastBitmap.Create(sourceBitmap); - IFastBitmapWithBlend bbbSrcBlend = bbbSrc as IFastBitmapWithBlend; bbbSrc.Lock(); byte index; @@ -243,7 +241,7 @@ namespace Greenshot.Base.Core for (int x = 0; x < bbbSrc.Width; x++) { Color color; - if (bbbSrcBlend != null) + if (bbbSrc is IFastBitmapWithBlend bbbSrcBlend) { color = bbbSrcBlend.GetBlendedColorAt(x, y); } @@ -259,7 +257,7 @@ namespace Greenshot.Base.Core else { colors.Add(color); - index = (byte) (colors.Count - 1); + index = (byte)(colors.Count - 1); lookup.Add(color, index); } @@ -364,9 +362,9 @@ namespace Greenshot.Base.Core if (weight > 0) { - lookupRed[k] = (int) (Volume(cubes[k], momentsRed) / weight); - lookupGreen[k] = (int) (Volume(cubes[k], momentsGreen) / weight); - lookupBlue[k] = (int) (Volume(cubes[k], momentsBlue) / weight); + lookupRed[k] = (int)(Volume(cubes[k], momentsRed) / weight); + lookupGreen[k] = (int)(Volume(cubes[k], momentsGreen) / weight); + lookupBlue[k] = (int)(Volume(cubes[k], momentsBlue) / weight); } else { @@ -386,14 +384,13 @@ namespace Greenshot.Base.Core using (FastChunkyBitmap dest = FastBitmap.Create(resultBitmap) as FastChunkyBitmap) { using IFastBitmap src = FastBitmap.Create(sourceBitmap); - IFastBitmapWithBlend srcBlend = src as IFastBitmapWithBlend; - Dictionary lookup = new Dictionary(); + Dictionary lookup = new(); for (int y = 0; y < src.Height; y++) { for (int x = 0; x < src.Width; x++) { Color color; - if (srcBlend != null) + if (src is IFastBitmapWithBlend srcBlend) { // WithoutAlpha, this makes it possible to ignore the alpha color = srcBlend.GetBlendedColorAt(x, y); @@ -423,12 +420,12 @@ namespace Greenshot.Base.Core int deltaGreen = color.G - foundGreen; int deltaBlue = color.B - foundBlue; - int distance = deltaRed * deltaRed + deltaGreen * deltaGreen + deltaBlue * deltaBlue; + int distance = (deltaRed * deltaRed) + (deltaGreen * deltaGreen) + (deltaBlue * deltaBlue); if (distance < bestDistance) { bestDistance = distance; - bestMatch = (byte) lookupIndex; + bestMatch = (byte)lookupIndex; } } @@ -450,7 +447,6 @@ namespace Greenshot.Base.Core } } - // generates palette ColorPalette imagePalette = resultBitmap.Palette; Color[] entries = imagePalette.Entries; @@ -565,18 +561,18 @@ namespace Greenshot.Base.Core { return direction switch { - RED => (moment[position, cube.GreenMaximum, cube.BlueMaximum] - + RED => moment[position, cube.GreenMaximum, cube.BlueMaximum] - moment[position, cube.GreenMaximum, cube.BlueMinimum] - moment[position, cube.GreenMinimum, cube.BlueMaximum] + - moment[position, cube.GreenMinimum, cube.BlueMinimum]), - GREEN => (moment[cube.RedMaximum, position, cube.BlueMaximum] - + moment[position, cube.GreenMinimum, cube.BlueMinimum], + GREEN => moment[cube.RedMaximum, position, cube.BlueMaximum] - moment[cube.RedMaximum, position, cube.BlueMinimum] - moment[cube.RedMinimum, position, cube.BlueMaximum] + - moment[cube.RedMinimum, position, cube.BlueMinimum]), - BLUE => (moment[cube.RedMaximum, cube.GreenMaximum, position] - + moment[cube.RedMinimum, position, cube.BlueMinimum], + BLUE => moment[cube.RedMaximum, cube.GreenMaximum, position] - moment[cube.RedMaximum, cube.GreenMinimum, position] - moment[cube.RedMinimum, cube.GreenMaximum, position] + - moment[cube.RedMinimum, cube.GreenMinimum, position]), + moment[cube.RedMinimum, cube.GreenMinimum, position], _ => 0, }; } @@ -588,18 +584,18 @@ namespace Greenshot.Base.Core { return direction switch { - RED => (-moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] + + RED => -moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] + moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]), - GREEN => (-moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], + GREEN => -moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]), - BLUE => (-moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], + BLUE => -moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]), + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], _ => 0 }; } @@ -615,7 +611,7 @@ namespace Greenshot.Base.Core float volumeMoment = VolumeFloat(cube, moments); float volumeWeight = Volume(cube, weights); - float distance = volumeRed * volumeRed + volumeGreen * volumeGreen + volumeBlue * volumeBlue; + float distance = (volumeRed * volumeRed) + (volumeGreen * volumeGreen) + (volumeBlue * volumeBlue); return volumeMoment - (distance / volumeWeight); } @@ -644,7 +640,7 @@ namespace Greenshot.Base.Core // the cube cannot be cut at bottom (this would lead to empty cube) if (halfWeight != 0) { - float halfDistance = (float) halfRed * halfRed + (float) halfGreen * halfGreen + (float) halfBlue * halfBlue; + float halfDistance = ((float)halfRed * halfRed) + ((float)halfGreen * halfGreen) + ((float)halfBlue * halfBlue); float temp = halfDistance / halfWeight; halfRed = wholeRed - halfRed; @@ -654,7 +650,7 @@ namespace Greenshot.Base.Core if (halfWeight != 0) { - halfDistance = (float) halfRed * halfRed + (float) halfGreen * halfGreen + (float) halfBlue * halfBlue; + halfDistance = ((float)halfRed * halfRed) + ((float)halfGreen * halfGreen) + ((float)halfBlue * halfBlue); temp += halfDistance / halfWeight; if (temp > result) @@ -762,7 +758,7 @@ namespace Greenshot.Base.Core { for (int blueIndex = cube.BlueMinimum + 1; blueIndex <= cube.BlueMaximum; ++blueIndex) { - tag[(redIndex << 10) + (redIndex << 6) + redIndex + (greenIndex << 5) + greenIndex + blueIndex] = (byte) label; + tag[(redIndex << 10) + (redIndex << 6) + redIndex + (greenIndex << 5) + greenIndex + blueIndex] = (byte)label; } } } diff --git a/src/Greenshot.Base/Core/RegistryKeyExtensions.cs b/src/Greenshot.Base/Core/RegistryKeyExtensions.cs index 7b5567ce1..0a15f0483 100644 --- a/src/Greenshot.Base/Core/RegistryKeyExtensions.cs +++ b/src/Greenshot.Base/Core/RegistryKeyExtensions.cs @@ -50,7 +50,7 @@ namespace Greenshot.Base.Core if (key != null) { - result = (string) key.GetValue(value); + result = (string)key.GetValue(value); } if (string.IsNullOrEmpty(result)) @@ -67,7 +67,7 @@ namespace Greenshot.Base.Core { if (key != null) { - result = (string) key.GetValue(value); + result = (string)key.GetValue(value); } if (!string.IsNullOrEmpty(result)) return result; @@ -78,7 +78,7 @@ namespace Greenshot.Base.Core { if (key != null) { - result = (string) key.GetValue(value); + result = (string)key.GetValue(value); } } diff --git a/src/Greenshot.Base/Core/SimpleServiceProvider.cs b/src/Greenshot.Base/Core/SimpleServiceProvider.cs index 084f5b1fd..c72d5b9bd 100644 --- a/src/Greenshot.Base/Core/SimpleServiceProvider.cs +++ b/src/Greenshot.Base/Core/SimpleServiceProvider.cs @@ -17,12 +17,7 @@ namespace Greenshot.Base.Core public IReadOnlyList GetAllInstances() { var typeOfService = typeof(TService); - if (!_services.TryGetValue(typeOfService, out var results)) - { - return Array.Empty(); - } - - return results.Cast().ToArray(); + return !_services.TryGetValue(typeOfService, out var results) ? Array.Empty() : (IReadOnlyList)results.Cast().ToArray(); } public TService GetInstance() diff --git a/src/Greenshot.Base/Core/StringExtensions.cs b/src/Greenshot.Base/Core/StringExtensions.cs index 73f7d5169..4db75b166 100644 --- a/src/Greenshot.Base/Core/StringExtensions.cs +++ b/src/Greenshot.Base/Core/StringExtensions.cs @@ -72,7 +72,7 @@ namespace Greenshot.Base.Core } else { - IDictionary dictionary = (IDictionary) value; + IDictionary dictionary = (IDictionary)value; foreach (var propertyKey in dictionary.Keys) { properties.Add(propertyKey, dictionary[propertyKey]); @@ -81,11 +81,11 @@ namespace Greenshot.Base.Core } } - Regex r = new Regex(@"(?\{)+(?[\w\.\[\]]+)(?:[^}]+)?(?\})+", + Regex r = new(@"(?\{)+(?[\w\.\[\]]+)(?:[^}]+)?(?\})+", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - List values = new List(); - string rewrittenFormat = r.Replace(format, delegate(Match m) + List values = new(); + string rewrittenFormat = r.Replace(format, delegate (Match m) { Group startGroup = m.Groups["start"]; Group propertyGroup = m.Groups["property"]; @@ -112,10 +112,10 @@ namespace Greenshot.Base.Core byte[] clearTextBytes = Encoding.ASCII.GetBytes(clearText); SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); - using MemoryStream ms = new MemoryStream(); + using MemoryStream ms = new(); byte[] rgbIV = Encoding.ASCII.GetBytes(RGBIV); byte[] key = Encoding.ASCII.GetBytes(KEY); - using CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write); + using CryptoStream cs = new(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(clearTextBytes, 0, clearTextBytes.Length); cs.FlushFinalBlock(); @@ -140,14 +140,13 @@ namespace Greenshot.Base.Core try { byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText); - using MemoryStream ms = new MemoryStream(); + using MemoryStream ms = new(); SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); - byte[] rgbIV = Encoding.ASCII.GetBytes(RGBIV); byte[] key = Encoding.ASCII.GetBytes(KEY); - using CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write); + using CryptoStream cs = new(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); cs.FlushFinalBlock(); returnValue = Encoding.ASCII.GetString(ms.ToArray()); diff --git a/src/Greenshot.Base/Core/WindowCapture.cs b/src/Greenshot.Base/Core/WindowCapture.cs index 01e1bce56..564ce9a65 100644 --- a/src/Greenshot.Base/Core/WindowCapture.cs +++ b/src/Greenshot.Base/Core/WindowCapture.cs @@ -153,7 +153,7 @@ namespace Greenshot.Base.Core { if (process == null) return true; if (Configuration.NoDWMCaptureForProduct == null || - Configuration.NoDWMCaptureForProduct.Count <= 0) return true; + Configuration.NoDWMCaptureForProduct.Count == 0) return true; try { @@ -180,7 +180,7 @@ namespace Greenshot.Base.Core { if (process == null) return true; if (Configuration.NoGDICaptureForProduct == null || - Configuration.NoGDICaptureForProduct.Count <= 0) return true; + Configuration.NoGDICaptureForProduct.Count == 0) return true; try { @@ -337,7 +337,7 @@ namespace Greenshot.Base.Core try { // Collect all screens inside this capture - List screensInsideCapture = new List(); + List screensInsideCapture = new(); foreach (Screen screen in Screen.AllScreens) { if (screen.Bounds.IntersectsWith(captureBounds)) @@ -348,7 +348,7 @@ namespace Greenshot.Base.Core // Check all all screens are of an equal size bool offscreenContent; - using (Region captureRegion = new Region(captureBounds)) + using (Region captureRegion = new(captureBounds)) { // Exclude every visible part foreach (Screen screen in screensInsideCapture) diff --git a/src/Greenshot.Base/Core/WindowDetails.cs b/src/Greenshot.Base/Core/WindowDetails.cs index 9cdf5f370..e614841d3 100644 --- a/src/Greenshot.Base/Core/WindowDetails.cs +++ b/src/Greenshot.Base/Core/WindowDetails.cs @@ -87,7 +87,7 @@ namespace Greenshot.Base.Core private IntPtr _parentHandle = IntPtr.Zero; private WindowDetails _parent; private bool _frozen; - + /// /// This checks if the window is a Windows 10 App /// For Windows 10 apps are hosted inside "ApplicationFrameWindow" @@ -100,7 +100,6 @@ namespace Greenshot.Base.Core public bool IsBackgroundWin10App => WindowsVersion.IsWindows10OrLater && AppFrameWindowClass.Equals(ClassName) && !Children.Any(window => string.Equals(window.ClassName, AppWindowClass)); - /// /// To allow items to be compared, the hash code /// is set to the Window handle, so two EnumWindowsItem @@ -134,18 +133,13 @@ namespace Greenshot.Base.Core return true; } - if (GetType() != other.GetType()) - { - return false; - } - - return other.Handle == Handle; + return GetType() == other.GetType() && other.Handle == Handle; } /// /// Check if the window has children /// - public bool HasChildren => (_childWindows != null) && (_childWindows.Count > 0); + public bool HasChildren => _childWindows?.Count > 0; /// /// Freeze information updates @@ -182,7 +176,6 @@ namespace Greenshot.Base.Core } } - /// /// Get the icon belonging to the process /// @@ -226,8 +219,8 @@ namespace Greenshot.Base.Core private static Icon GetAppIcon(IntPtr hWnd) { IntPtr iconSmall = IntPtr.Zero; - IntPtr iconBig = new IntPtr(1); - IntPtr iconSmall2 = new IntPtr(2); + IntPtr iconBig = new(1); + IntPtr iconSmall2 = new(2); IntPtr iconHandle; if (Conf.UseLargeIcons) @@ -370,12 +363,7 @@ namespace Greenshot.Base.Core /// public IList GetChildren() { - if (_childWindows == null) - { - return GetChildren(0); - } - - return _childWindows; + return _childWindows ?? GetChildren(0); } /// @@ -492,12 +480,7 @@ namespace Greenshot.Base.Core get { // Tip from Raymond Chen https://devblogs.microsoft.com/oldnewthing/20200302-00/?p=103507 - if (IsCloaked) - { - return false; - } - - return User32Api.IsWindowVisible(Handle); + return !IsCloaked && User32Api.IsWindowVisible(Handle); } } @@ -599,7 +582,6 @@ namespace Greenshot.Base.Core _previousWindowRectangle = windowRect; return windowRect; - } } @@ -675,7 +657,7 @@ namespace Greenshot.Base.Core get => unchecked( (WindowStyleFlags)User32Api.GetWindowLongWrapper(Handle, WindowLongIndex.GWL_STYLE).ToInt64() ); - set => User32Api.SetWindowLongWrapper(Handle, WindowLongIndex.GWL_STYLE, new IntPtr((long) value)); + set => User32Api.SetWindowLongWrapper(Handle, WindowLongIndex.GWL_STYLE, new IntPtr((long)value)); } /// @@ -697,8 +679,8 @@ namespace Greenshot.Base.Core /// public ExtendedWindowStyleFlags ExtendedWindowStyle { - get => (ExtendedWindowStyleFlags) User32Api.GetWindowLongWrapper(Handle, WindowLongIndex.GWL_EXSTYLE); - set => User32Api.SetWindowLongWrapper(Handle, WindowLongIndex.GWL_EXSTYLE, new IntPtr((uint) value)); + get => (ExtendedWindowStyleFlags)User32Api.GetWindowLongWrapper(Handle, WindowLongIndex.GWL_EXSTYLE); + set => User32Api.SetWindowLongWrapper(Handle, WindowLongIndex.GWL_EXSTYLE, new IntPtr((uint)value)); } /// @@ -713,7 +695,6 @@ namespace Greenshot.Base.Core capture.Image = capturedImage; capture.Location = Location; return capture; - } /// @@ -751,14 +732,14 @@ namespace Greenshot.Base.Core // Calculate the location of the temp form NativeRect windowRectangle = WindowRectangle; NativePoint formLocation = windowRectangle.Location; - NativeSize borderSize = new NativeSize(); + NativeSize borderSize = new(); bool doesCaptureFit = false; if (!Maximised) { // Assume using it's own location formLocation = windowRectangle.Location; // TODO: Use Rectangle.Union! - using Region workingArea = new Region(Screen.PrimaryScreen.Bounds); + using Region workingArea = new(Screen.PrimaryScreen.Bounds); // Find the screen where the window is and check if it fits foreach (Screen screen in Screen.AllScreens) { @@ -1025,12 +1006,12 @@ namespace Greenshot.Base.Core else { // Calculate original color - byte originalAlpha = (byte) Math.Min(255, alpha); + byte originalAlpha = (byte)Math.Min(255, alpha); var alphaFactor = alpha / 255d; //LOG.DebugFormat("Alpha {0} & c0 {1} & c1 {2}", alpha, c0, c1); - byte originalRed = (byte) Math.Min(255, c0.R / alphaFactor); - byte originalGreen = (byte) Math.Min(255, c0.G / alphaFactor); - byte originalBlue = (byte) Math.Min(255, c0.B / alphaFactor); + byte originalRed = (byte)Math.Min(255, c0.R / alphaFactor); + byte originalGreen = (byte)Math.Min(255, c0.G / alphaFactor); + byte originalBlue = (byte)Math.Min(255, c0.B / alphaFactor); Color originalColor = Color.FromArgb(originalAlpha, originalRed, originalGreen, originalBlue); //Color originalColor = Color.FromArgb(originalAlpha, originalRed, c0.G, c0.B); targetBuffer.SetColorAt(x, y, originalColor); @@ -1237,10 +1218,9 @@ namespace Greenshot.Base.Core Log.DebugFormat("Freezing process: {0}", processName); - foreach (ProcessThread pT in proc.Threads) { - IntPtr pOpenThread = Kernel32Api.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint) pT.Id); + IntPtr pOpenThread = Kernel32Api.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); if (pOpenThread == IntPtr.Zero) { @@ -1279,7 +1259,7 @@ namespace Greenshot.Base.Core foreach (ProcessThread pT in proc.Threads) { - IntPtr pOpenThread = Kernel32Api.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint) pT.Id); + IntPtr pOpenThread = Kernel32Api.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); if (pOpenThread == IntPtr.Zero) { @@ -1311,8 +1291,8 @@ namespace Greenshot.Base.Core pixelFormat = PixelFormat.Format32bppArgb; backgroundColor = Color.Transparent; } - - returnImage = ImageHelper.CreateEmpty(windowRect.Width, windowRect.Height, pixelFormat, backgroundColor, 96,96); + + returnImage = ImageHelper.CreateEmpty(windowRect.Width, windowRect.Height, pixelFormat, backgroundColor, 96, 96); using Graphics graphics = Graphics.FromImage(returnImage); using (SafeGraphicsDcHandle graphicsDc = graphics.GetSafeDeviceContext()) { @@ -1326,7 +1306,7 @@ namespace Greenshot.Base.Core } // Apply the region "transparency" - if (region != null && !region.IsEmpty(graphics)) + if (region?.IsEmpty(graphics) == false) { graphics.ExcludeClip(region); graphics.Clear(Color.Transparent); @@ -1347,7 +1327,7 @@ namespace Greenshot.Base.Core { Log.Debug("Correcting for maximized window"); GetBorderSize(out var borderSize); - NativeRect borderRectangle = new NativeRect(borderSize.Width, borderSize.Height, windowRect.Width - (2 * borderSize.Width), windowRect.Height - (2 * borderSize.Height)); + NativeRect borderRectangle = new(borderSize.Width, borderSize.Height, windowRect.Width - (2 * borderSize.Width), windowRect.Height - (2 * borderSize.Height)); ImageHelper.Crop(ref returnImage, ref borderRectangle); } @@ -1378,14 +1358,9 @@ namespace Greenshot.Base.Core return GetDesktopWindow(); } - WindowDetails activeWindow = new WindowDetails(hWnd); + WindowDetails activeWindow = new(hWnd); // Invisible Windows should not be active - if (!activeWindow.Visible) - { - return GetDesktopWindow(); - } - - return activeWindow; + return !activeWindow.Visible ? GetDesktopWindow() : activeWindow; } return null; @@ -1483,12 +1458,7 @@ namespace Greenshot.Base.Core // Skip everything which is not rendered "normally", trying to fix BUG-2017 var exWindowStyle = window.ExtendedWindowStyle; - if (!window.IsWin10App && (exWindowStyle & ExtendedWindowStyleFlags.WS_EX_NOREDIRECTIONBITMAP) != 0) - { - return false; - } - - return true; + return window.IsWin10App || (exWindowStyle & ExtendedWindowStyleFlags.WS_EX_NOREDIRECTIONBITMAP) == 0; } /// @@ -1560,12 +1530,7 @@ namespace Greenshot.Base.Core return false; } - if (!(window.Visible || window.Iconic)) - { - return false; - } - - return !window.IsBackgroundWin10App; + return (window.Visible || window.Iconic) && !window.IsBackgroundWin10App; } /// @@ -1657,12 +1622,7 @@ namespace Greenshot.Base.Core { get { - if (AppVisibility != null) - { - return AppVisibility.IsLauncherVisible; - } - - return false; + return AppVisibility != null && AppVisibility.IsLauncherVisible; } } @@ -1673,21 +1633,21 @@ namespace Greenshot.Base.Core public override string ToString() { var result = new StringBuilder(); - result.AppendLine($"Text: {Text}"); - result.AppendLine($"ClassName: {ClassName}"); - result.AppendLine($"ExtendedWindowStyle: {ExtendedWindowStyle}"); - result.AppendLine($"WindowStyle: {WindowStyle}"); - result.AppendLine($"Size: {WindowRectangle.Size}"); - result.AppendLine($"HasParent: {HasParent}"); - result.AppendLine($"IsWin10App: {IsWin10App}"); - result.AppendLine($"Visible: {Visible}"); - result.AppendLine($"IsWindowVisible: {User32Api.IsWindowVisible(Handle)}"); - result.AppendLine($"IsCloaked: {IsCloaked}"); - result.AppendLine($"Iconic: {Iconic}"); - result.AppendLine($"IsBackgroundWin10App: {IsBackgroundWin10App}"); + result.Append("Text: ").AppendLine(Text); + result.Append("ClassName: ").AppendLine(ClassName); + result.Append("ExtendedWindowStyle: ").Append(ExtendedWindowStyle).AppendLine(); + result.Append("WindowStyle: ").Append(WindowStyle).AppendLine(); + result.Append("Size: ").Append(WindowRectangle.Size).AppendLine(); + result.Append("HasParent: ").Append(HasParent).AppendLine(); + result.Append("IsWin10App: ").Append(IsWin10App).AppendLine(); + result.Append("Visible: ").Append(Visible).AppendLine(); + result.Append("IsWindowVisible: ").Append(User32Api.IsWindowVisible(Handle)).AppendLine(); + result.Append("IsCloaked: ").Append(IsCloaked).AppendLine(); + result.Append("Iconic: ").Append(Iconic).AppendLine(); + result.Append("IsBackgroundWin10App: ").Append(IsBackgroundWin10App).AppendLine(); if (HasChildren) { - result.AppendLine($"Children classes: {string.Join(",", Children.Select(c => c.ClassName))}"); + result.Append("Children classes: ").AppendLine(string.Join(",", Children.Select(c => c.ClassName))); } return result.ToString(); diff --git a/src/Greenshot.Base/Core/WindowsVersion.cs b/src/Greenshot.Base/Core/WindowsVersion.cs index ca9e96d47..b7e883f72 100644 --- a/src/Greenshot.Base/Core/WindowsVersion.cs +++ b/src/Greenshot.Base/Core/WindowsVersion.cs @@ -37,13 +37,13 @@ namespace Greenshot.Base.Core /// Test if the current OS is Windows 8.1 or later /// /// true if we are running on Windows 8.1 or later - public static bool IsWindows81OrLater { get; } = WinVersion.Major == 6 && WinVersion.Minor >= 3 || WinVersion.Major > 6; + public static bool IsWindows81OrLater { get; } = (WinVersion.Major == 6 && WinVersion.Minor >= 3) || WinVersion.Major > 6; /// /// Test if the current OS is Windows 8 or later /// /// true if we are running on Windows 8 or later - public static bool IsWindows8OrLater { get; } = WinVersion.Major == 6 && WinVersion.Minor >= 2 || WinVersion.Major > 6; + public static bool IsWindows8OrLater { get; } = (WinVersion.Major == 6 && WinVersion.Minor >= 2) || WinVersion.Major > 6; /// /// Test if the current OS is Windows Vista or later diff --git a/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs b/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs index fb95dccb3..26d36ff14 100644 --- a/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs +++ b/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs @@ -50,7 +50,7 @@ namespace Greenshot.Base.Core /// true if the message should be filtered public static bool PreFilterMessageExternal(ref Message m) { - WindowsMessages message = (WindowsMessages) m.Msg; + WindowsMessages message = (WindowsMessages)m.Msg; if (message != WindowsMessages.WM_INPUTLANGCHANGEREQUEST && message != WindowsMessages.WM_INPUTLANGCHANGE) return false; LOG.DebugFormat("Filtering: {0}, {1:X} - {2:X} - {3:X}", message, m.LParam.ToInt64(), m.WParam.ToInt64(), m.HWnd.ToInt64()); diff --git a/src/Greenshot.Base/Effects/ReduceColorsEffect.cs b/src/Greenshot.Base/Effects/ReduceColorsEffect.cs index 30c6c3956..bca3ae680 100644 --- a/src/Greenshot.Base/Effects/ReduceColorsEffect.cs +++ b/src/Greenshot.Base/Effects/ReduceColorsEffect.cs @@ -48,7 +48,7 @@ namespace Greenshot.Base.Effects public Image Apply(Image sourceImage, Matrix matrix) { - using (WuQuantizer quantizer = new WuQuantizer((Bitmap) sourceImage)) + using (WuQuantizer quantizer = new((Bitmap)sourceImage)) { int colorCount = quantizer.GetColorCount(); if (colorCount > Colors) diff --git a/src/Greenshot.Base/Help/HelpFileLoader.cs b/src/Greenshot.Base/Help/HelpFileLoader.cs index 2c9b04b4d..639a0fd9c 100644 --- a/src/Greenshot.Base/Help/HelpFileLoader.cs +++ b/src/Greenshot.Base/Help/HelpFileLoader.cs @@ -33,7 +33,7 @@ namespace Greenshot.Base.Help { private static readonly ILog Log = LogManager.GetLogger(typeof(HelpFileLoader)); - private const string ExtHelpUrl = @"https://getgreenshot.org/help/"; + private const string ExtHelpUrl = "https://getgreenshot.org/help/"; public static void LoadHelp() { @@ -89,12 +89,12 @@ namespace Greenshot.Base.Help try { HttpWebRequest req = NetworkHelper.CreateWebRequest(url); - using HttpWebResponse res = (HttpWebResponse) req.GetResponse(); + using HttpWebResponse res = (HttpWebResponse)req.GetResponse(); return res.StatusCode; } catch (WebException e) { - return ((HttpWebResponse) e.Response)?.StatusCode; + return ((HttpWebResponse)e.Response)?.StatusCode; } } } diff --git a/src/Greenshot.Base/IEInterop/IHTMLDocument2.cs b/src/Greenshot.Base/IEInterop/IHTMLDocument2.cs index fe0df4260..6a7797c3e 100644 --- a/src/Greenshot.Base/IEInterop/IHTMLDocument2.cs +++ b/src/Greenshot.Base/IEInterop/IHTMLDocument2.cs @@ -79,7 +79,8 @@ namespace Greenshot.Base.IEInterop [DispId(1014)] [return: MarshalAs(UnmanagedType.BStr)] get; - [DispId(1014)] set; + [DispId(1014)] + set; } } } \ No newline at end of file diff --git a/src/Greenshot.Base/IEInterop/IHTMLFrameBase.cs b/src/Greenshot.Base/IEInterop/IHTMLFrameBase.cs index 33cff2500..760b5c9bd 100644 --- a/src/Greenshot.Base/IEInterop/IHTMLFrameBase.cs +++ b/src/Greenshot.Base/IEInterop/IHTMLFrameBase.cs @@ -28,47 +28,47 @@ namespace Greenshot.Base.IEInterop InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IHTMLFrameBase { -//dispinterface IHTMLFrameBase { -// properties: -// methods: -// [id(0x80010bb8), propput] -// void src([in] BSTR rhs); -// [id(0x80010bb8), propget] -// BSTR src(); -// [id(0x80010000), propput] -// void name([in] BSTR rhs); -// [id(0x80010000), propget] -// BSTR name(); -// [id(0x80010bba), propput] -// void border([in] VARIANT rhs); -// [id(0x80010bba), propget] -// VARIANT border(); -// [id(0x80010bbb), propput] -// void frameBorder([in] BSTR rhs); -// [id(0x80010bbb), propget] -// BSTR frameBorder(); -// [id(0x80010bbc), propput] -// void frameSpacing([in] VARIANT rhs); -// [id(0x80010bbc), propget] -// VARIANT frameSpacing(); -// [id(0x80010bbd), propput] -// void marginWidth([in] VARIANT rhs); -// [id(0x80010bbd), propget] -// VARIANT marginWidth(); -// [id(0x80010bbe), propput] -// void marginHeight([in] VARIANT rhs); -// [id(0x80010bbe), propget] -// VARIANT marginHeight(); -// [id(0x80010bbf), propput] -// void noResize([in] VARIANT_BOOL rhs); -// [id(0x80010bbf), propget] -// VARIANT_BOOL noResize(); -// [id(0x80010bc0), propput] -// void scrolling([in] BSTR rhs); -// [id(0x80010bc0), propget] -// BSTR scrolling(); -//}; -// [DispId(HTMLDispIDs.DISPID_IHTMLFRAMEBASE_SRC)] + //dispinterface IHTMLFrameBase { + // properties: + // methods: + // [id(0x80010bb8), propput] + // void src([in] BSTR rhs); + // [id(0x80010bb8), propget] + // BSTR src(); + // [id(0x80010000), propput] + // void name([in] BSTR rhs); + // [id(0x80010000), propget] + // BSTR name(); + // [id(0x80010bba), propput] + // void border([in] VARIANT rhs); + // [id(0x80010bba), propget] + // VARIANT border(); + // [id(0x80010bbb), propput] + // void frameBorder([in] BSTR rhs); + // [id(0x80010bbb), propget] + // BSTR frameBorder(); + // [id(0x80010bbc), propput] + // void frameSpacing([in] VARIANT rhs); + // [id(0x80010bbc), propget] + // VARIANT frameSpacing(); + // [id(0x80010bbd), propput] + // void marginWidth([in] VARIANT rhs); + // [id(0x80010bbd), propget] + // VARIANT marginWidth(); + // [id(0x80010bbe), propput] + // void marginHeight([in] VARIANT rhs); + // [id(0x80010bbe), propget] + // VARIANT marginHeight(); + // [id(0x80010bbf), propput] + // void noResize([in] VARIANT_BOOL rhs); + // [id(0x80010bbf), propget] + // VARIANT_BOOL noResize(); + // [id(0x80010bc0), propput] + // void scrolling([in] BSTR rhs); + // [id(0x80010bc0), propget] + // BSTR scrolling(); + //}; + // [DispId(HTMLDispIDs.DISPID_IHTMLFRAMEBASE_SRC)] string src { [return: MarshalAs(UnmanagedType.BStr)] diff --git a/src/Greenshot.Base/IEInterop/IHTMLStyle.cs b/src/Greenshot.Base/IEInterop/IHTMLStyle.cs index 67269ed18..2ddef4063 100644 --- a/src/Greenshot.Base/IEInterop/IHTMLStyle.cs +++ b/src/Greenshot.Base/IEInterop/IHTMLStyle.cs @@ -71,7 +71,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT background (BSTR value); // VB6: Sub background (ByVal value As String) - [DispId(-2147413080)] set; + [DispId(-2147413080)] + set; } /// backgroundAttachment property of IHTMLStyle interface. @@ -87,7 +88,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT backgroundAttachment (BSTR value); // VB6: Sub backgroundAttachment (ByVal value As String) - [DispId(-2147413067)] set; + [DispId(-2147413067)] + set; } /// backgroundColor property of IHTMLStyle interface. @@ -98,10 +100,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT backgroundColor ([out, retval] VARIANT* ReturnValue); // VB6: Function backgroundColor As Any - [DispId(-501)] get; + [DispId(-501)] + get; // IDL: HRESULT backgroundColor (VARIANT value); // VB6: Sub backgroundColor (ByVal value As Any) - [DispId(-501)] set; + [DispId(-501)] + set; } /// backgroundImage property of IHTMLStyle interface. @@ -117,7 +121,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT backgroundImage (BSTR value); // VB6: Sub backgroundImage (ByVal value As String) - [DispId(-2147413111)] set; + [DispId(-2147413111)] + set; } /// backgroundPosition property of IHTMLStyle interface. @@ -133,7 +138,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT backgroundPosition (BSTR value); // VB6: Sub backgroundPosition (ByVal value As String) - [DispId(-2147413066)] set; + [DispId(-2147413066)] + set; } /// backgroundPositionX property of IHTMLStyle interface. @@ -144,10 +150,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT backgroundPositionX ([out, retval] VARIANT* ReturnValue); // VB6: Function backgroundPositionX As Any - [DispId(-2147413079)] get; + [DispId(-2147413079)] + get; // IDL: HRESULT backgroundPositionX (VARIANT value); // VB6: Sub backgroundPositionX (ByVal value As Any) - [DispId(-2147413079)] set; + [DispId(-2147413079)] + set; } /// backgroundPositionY property of IHTMLStyle interface. @@ -158,10 +166,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT backgroundPositionY ([out, retval] VARIANT* ReturnValue); // VB6: Function backgroundPositionY As Any - [DispId(-2147413078)] get; + [DispId(-2147413078)] + get; // IDL: HRESULT backgroundPositionY (VARIANT value); // VB6: Sub backgroundPositionY (ByVal value As Any) - [DispId(-2147413078)] set; + [DispId(-2147413078)] + set; } /// backgroundRepeat property of IHTMLStyle interface. @@ -177,7 +187,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT backgroundRepeat (BSTR value); // VB6: Sub backgroundRepeat (ByVal value As String) - [DispId(-2147413068)] set; + [DispId(-2147413068)] + set; } /// border property of IHTMLStyle interface. @@ -193,7 +204,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT border (BSTR value); // VB6: Sub border (ByVal value As String) - [DispId(-2147413063)] set; + [DispId(-2147413063)] + set; } /// borderBottom property of IHTMLStyle interface. @@ -209,7 +221,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderBottom (BSTR value); // VB6: Sub borderBottom (ByVal value As String) - [DispId(-2147413060)] set; + [DispId(-2147413060)] + set; } /// borderBottomColor property of IHTMLStyle interface. @@ -220,10 +233,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT borderBottomColor ([out, retval] VARIANT* ReturnValue); // VB6: Function borderBottomColor As Any - [DispId(-2147413055)] get; + [DispId(-2147413055)] + get; // IDL: HRESULT borderBottomColor (VARIANT value); // VB6: Sub borderBottomColor (ByVal value As Any) - [DispId(-2147413055)] set; + [DispId(-2147413055)] + set; } /// borderBottomStyle property of IHTMLStyle interface. @@ -239,7 +254,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderBottomStyle (BSTR value); // VB6: Sub borderBottomStyle (ByVal value As String) - [DispId(-2147413045)] set; + [DispId(-2147413045)] + set; } /// borderBottomWidth property of IHTMLStyle interface. @@ -250,10 +266,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT borderBottomWidth ([out, retval] VARIANT* ReturnValue); // VB6: Function borderBottomWidth As Any - [DispId(-2147413050)] get; + [DispId(-2147413050)] + get; // IDL: HRESULT borderBottomWidth (VARIANT value); // VB6: Sub borderBottomWidth (ByVal value As Any) - [DispId(-2147413050)] set; + [DispId(-2147413050)] + set; } /// borderColor property of IHTMLStyle interface. @@ -269,7 +287,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderColor (BSTR value); // VB6: Sub borderColor (ByVal value As String) - [DispId(-2147413058)] set; + [DispId(-2147413058)] + set; } /// borderLeft property of IHTMLStyle interface. @@ -285,7 +304,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderLeft (BSTR value); // VB6: Sub borderLeft (ByVal value As String) - [DispId(-2147413059)] set; + [DispId(-2147413059)] + set; } /// borderLeftColor property of IHTMLStyle interface. @@ -296,10 +316,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT borderLeftColor ([out, retval] VARIANT* ReturnValue); // VB6: Function borderLeftColor As Any - [DispId(-2147413054)] get; + [DispId(-2147413054)] + get; // IDL: HRESULT borderLeftColor (VARIANT value); // VB6: Sub borderLeftColor (ByVal value As Any) - [DispId(-2147413054)] set; + [DispId(-2147413054)] + set; } /// borderLeftStyle property of IHTMLStyle interface. @@ -315,7 +337,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderLeftStyle (BSTR value); // VB6: Sub borderLeftStyle (ByVal value As String) - [DispId(-2147413044)] set; + [DispId(-2147413044)] + set; } /// borderLeftWidth property of IHTMLStyle interface. @@ -326,10 +349,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT borderLeftWidth ([out, retval] VARIANT* ReturnValue); // VB6: Function borderLeftWidth As Any - [DispId(-2147413049)] get; + [DispId(-2147413049)] + get; // IDL: HRESULT borderLeftWidth (VARIANT value); // VB6: Sub borderLeftWidth (ByVal value As Any) - [DispId(-2147413049)] set; + [DispId(-2147413049)] + set; } /// borderRight property of IHTMLStyle interface. @@ -345,7 +370,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderRight (BSTR value); // VB6: Sub borderRight (ByVal value As String) - [DispId(-2147413061)] set; + [DispId(-2147413061)] + set; } /// borderRightColor property of IHTMLStyle interface. @@ -356,10 +382,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT borderRightColor ([out, retval] VARIANT* ReturnValue); // VB6: Function borderRightColor As Any - [DispId(-2147413056)] get; + [DispId(-2147413056)] + get; // IDL: HRESULT borderRightColor (VARIANT value); // VB6: Sub borderRightColor (ByVal value As Any) - [DispId(-2147413056)] set; + [DispId(-2147413056)] + set; } /// borderRightStyle property of IHTMLStyle interface. @@ -375,7 +403,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderRightStyle (BSTR value); // VB6: Sub borderRightStyle (ByVal value As String) - [DispId(-2147413046)] set; + [DispId(-2147413046)] + set; } /// borderRightWidth property of IHTMLStyle interface. @@ -386,10 +415,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT borderRightWidth ([out, retval] VARIANT* ReturnValue); // VB6: Function borderRightWidth As Any - [DispId(-2147413051)] get; + [DispId(-2147413051)] + get; // IDL: HRESULT borderRightWidth (VARIANT value); // VB6: Sub borderRightWidth (ByVal value As Any) - [DispId(-2147413051)] set; + [DispId(-2147413051)] + set; } /// borderStyle property of IHTMLStyle interface. @@ -405,7 +436,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderStyle (BSTR value); // VB6: Sub borderStyle (ByVal value As String) - [DispId(-2147413048)] set; + [DispId(-2147413048)] + set; } /// borderTop property of IHTMLStyle interface. @@ -421,7 +453,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderTop (BSTR value); // VB6: Sub borderTop (ByVal value As String) - [DispId(-2147413062)] set; + [DispId(-2147413062)] + set; } /// borderTopColor property of IHTMLStyle interface. @@ -432,10 +465,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT borderTopColor ([out, retval] VARIANT* ReturnValue); // VB6: Function borderTopColor As Any - [DispId(-2147413057)] get; + [DispId(-2147413057)] + get; // IDL: HRESULT borderTopColor (VARIANT value); // VB6: Sub borderTopColor (ByVal value As Any) - [DispId(-2147413057)] set; + [DispId(-2147413057)] + set; } /// borderTopStyle property of IHTMLStyle interface. @@ -451,7 +486,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderTopStyle (BSTR value); // VB6: Sub borderTopStyle (ByVal value As String) - [DispId(-2147413047)] set; + [DispId(-2147413047)] + set; } /// borderTopWidth property of IHTMLStyle interface. @@ -462,10 +498,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT borderTopWidth ([out, retval] VARIANT* ReturnValue); // VB6: Function borderTopWidth As Any - [DispId(-2147413052)] get; + [DispId(-2147413052)] + get; // IDL: HRESULT borderTopWidth (VARIANT value); // VB6: Sub borderTopWidth (ByVal value As Any) - [DispId(-2147413052)] set; + [DispId(-2147413052)] + set; } /// borderWidth property of IHTMLStyle interface. @@ -481,7 +519,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT borderWidth (BSTR value); // VB6: Sub borderWidth (ByVal value As String) - [DispId(-2147413053)] set; + [DispId(-2147413053)] + set; } /// clear property of IHTMLStyle interface. @@ -497,7 +536,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT clear (BSTR value); // VB6: Sub clear (ByVal value As String) - [DispId(-2147413096)] set; + [DispId(-2147413096)] + set; } /// clip property of IHTMLStyle interface. @@ -513,7 +553,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT clip (BSTR value); // VB6: Sub clip (ByVal value As String) - [DispId(-2147413020)] set; + [DispId(-2147413020)] + set; } /// color property of IHTMLStyle interface. @@ -524,10 +565,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT color ([out, retval] VARIANT* ReturnValue); // VB6: Function color As Any - [DispId(-2147413110)] get; + [DispId(-2147413110)] + get; // IDL: HRESULT color (VARIANT value); // VB6: Sub color (ByVal value As Any) - [DispId(-2147413110)] set; + [DispId(-2147413110)] + set; } /// cssText property of IHTMLStyle interface. @@ -543,7 +586,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT cssText (BSTR value); // VB6: Sub cssText (ByVal value As String) - [DispId(-2147413013)] set; + [DispId(-2147413013)] + set; } /// cursor property of IHTMLStyle interface. @@ -559,7 +603,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT cursor (BSTR value); // VB6: Sub cursor (ByVal value As String) - [DispId(-2147413010)] set; + [DispId(-2147413010)] + set; } /// display property of IHTMLStyle interface. @@ -575,7 +620,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT display (BSTR value); // VB6: Sub display (ByVal value As String) - [DispId(-2147413041)] set; + [DispId(-2147413041)] + set; } /// filter property of IHTMLStyle interface. @@ -591,7 +637,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT filter (BSTR value); // VB6: Sub filter (ByVal value As String) - [DispId(-2147413030)] set; + [DispId(-2147413030)] + set; } /// font property of IHTMLStyle interface. @@ -607,7 +654,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT font (BSTR value); // VB6: Sub font (ByVal value As String) - [DispId(-2147413071)] set; + [DispId(-2147413071)] + set; } /// fontFamily property of IHTMLStyle interface. @@ -623,7 +671,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT fontFamily (BSTR value); // VB6: Sub fontFamily (ByVal value As String) - [DispId(-2147413094)] set; + [DispId(-2147413094)] + set; } /// fontSize property of IHTMLStyle interface. @@ -634,10 +683,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT fontSize ([out, retval] VARIANT* ReturnValue); // VB6: Function fontSize As Any - [DispId(-2147413093)] get; + [DispId(-2147413093)] + get; // IDL: HRESULT fontSize (VARIANT value); // VB6: Sub fontSize (ByVal value As Any) - [DispId(-2147413093)] set; + [DispId(-2147413093)] + set; } /// fontStyle property of IHTMLStyle interface. @@ -653,7 +704,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT fontStyle (BSTR value); // VB6: Sub fontStyle (ByVal value As String) - [DispId(-2147413088)] set; + [DispId(-2147413088)] + set; } /// fontVariant property of IHTMLStyle interface. @@ -669,7 +721,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT fontVariant (BSTR value); // VB6: Sub fontVariant (ByVal value As String) - [DispId(-2147413087)] set; + [DispId(-2147413087)] + set; } /// fontWeight property of IHTMLStyle interface. @@ -685,7 +738,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT fontWeight (BSTR value); // VB6: Sub fontWeight (ByVal value As String) - [DispId(-2147413085)] set; + [DispId(-2147413085)] + set; } /// height property of IHTMLStyle interface. @@ -696,10 +750,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT height ([out, retval] VARIANT* ReturnValue); // VB6: Function height As Any - [DispId(-2147418106)] get; + [DispId(-2147418106)] + get; // IDL: HRESULT height (VARIANT value); // VB6: Sub height (ByVal value As Any) - [DispId(-2147418106)] set; + [DispId(-2147418106)] + set; } /// left property of IHTMLStyle interface. @@ -710,10 +766,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT left ([out, retval] VARIANT* ReturnValue); // VB6: Function left As Any - [DispId(-2147418109)] get; + [DispId(-2147418109)] + get; // IDL: HRESULT left (VARIANT value); // VB6: Sub left (ByVal value As Any) - [DispId(-2147418109)] set; + [DispId(-2147418109)] + set; } /// letterSpacing property of IHTMLStyle interface. @@ -724,10 +782,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT letterSpacing ([out, retval] VARIANT* ReturnValue); // VB6: Function letterSpacing As Any - [DispId(-2147413104)] get; + [DispId(-2147413104)] + get; // IDL: HRESULT letterSpacing (VARIANT value); // VB6: Sub letterSpacing (ByVal value As Any) - [DispId(-2147413104)] set; + [DispId(-2147413104)] + set; } /// lineHeight property of IHTMLStyle interface. @@ -738,10 +798,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT lineHeight ([out, retval] VARIANT* ReturnValue); // VB6: Function lineHeight As Any - [DispId(-2147413106)] get; + [DispId(-2147413106)] + get; // IDL: HRESULT lineHeight (VARIANT value); // VB6: Sub lineHeight (ByVal value As Any) - [DispId(-2147413106)] set; + [DispId(-2147413106)] + set; } /// listStyle property of IHTMLStyle interface. @@ -757,7 +819,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT listStyle (BSTR value); // VB6: Sub listStyle (ByVal value As String) - [DispId(-2147413037)] set; + [DispId(-2147413037)] + set; } /// listStyleImage property of IHTMLStyle interface. @@ -773,7 +836,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT listStyleImage (BSTR value); // VB6: Sub listStyleImage (ByVal value As String) - [DispId(-2147413038)] set; + [DispId(-2147413038)] + set; } /// listStylePosition property of IHTMLStyle interface. @@ -789,7 +853,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT listStylePosition (BSTR value); // VB6: Sub listStylePosition (ByVal value As String) - [DispId(-2147413039)] set; + [DispId(-2147413039)] + set; } /// listStyleType property of IHTMLStyle interface. @@ -805,7 +870,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT listStyleType (BSTR value); // VB6: Sub listStyleType (ByVal value As String) - [DispId(-2147413040)] set; + [DispId(-2147413040)] + set; } /// margin property of IHTMLStyle interface. @@ -821,7 +887,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT margin (BSTR value); // VB6: Sub margin (ByVal value As String) - [DispId(-2147413076)] set; + [DispId(-2147413076)] + set; } /// marginBottom property of IHTMLStyle interface. @@ -832,10 +899,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT marginBottom ([out, retval] VARIANT* ReturnValue); // VB6: Function marginBottom As Any - [DispId(-2147413073)] get; + [DispId(-2147413073)] + get; // IDL: HRESULT marginBottom (VARIANT value); // VB6: Sub marginBottom (ByVal value As Any) - [DispId(-2147413073)] set; + [DispId(-2147413073)] + set; } /// marginLeft property of IHTMLStyle interface. @@ -846,10 +915,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT marginLeft ([out, retval] VARIANT* ReturnValue); // VB6: Function marginLeft As Any - [DispId(-2147413072)] get; + [DispId(-2147413072)] + get; // IDL: HRESULT marginLeft (VARIANT value); // VB6: Sub marginLeft (ByVal value As Any) - [DispId(-2147413072)] set; + [DispId(-2147413072)] + set; } /// marginRight property of IHTMLStyle interface. @@ -860,10 +931,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT marginRight ([out, retval] VARIANT* ReturnValue); // VB6: Function marginRight As Any - [DispId(-2147413074)] get; + [DispId(-2147413074)] + get; // IDL: HRESULT marginRight (VARIANT value); // VB6: Sub marginRight (ByVal value As Any) - [DispId(-2147413074)] set; + [DispId(-2147413074)] + set; } /// marginTop property of IHTMLStyle interface. @@ -874,10 +947,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT marginTop ([out, retval] VARIANT* ReturnValue); // VB6: Function marginTop As Any - [DispId(-2147413075)] get; + [DispId(-2147413075)] + get; // IDL: HRESULT marginTop (VARIANT value); // VB6: Sub marginTop (ByVal value As Any) - [DispId(-2147413075)] set; + [DispId(-2147413075)] + set; } /// overflow property of IHTMLStyle interface. @@ -893,7 +968,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT overflow (BSTR value); // VB6: Sub overflow (ByVal value As String) - [DispId(-2147413102)] set; + [DispId(-2147413102)] + set; } /// padding property of IHTMLStyle interface. @@ -909,7 +985,8 @@ namespace Greenshot.Base.IEInterop get; // IDL: HRESULT padding (BSTR value); // VB6: Sub padding (ByVal value As String) - [DispId(-2147413101)] set; + [DispId(-2147413101)] + set; } /// paddingBottom property of IHTMLStyle interface. @@ -920,10 +997,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT paddingBottom ([out, retval] VARIANT* ReturnValue); // VB6: Function paddingBottom As Any - [DispId(-2147413098)] get; + [DispId(-2147413098)] + get; // IDL: HRESULT paddingBottom (VARIANT value); // VB6: Sub paddingBottom (ByVal value As Any) - [DispId(-2147413098)] set; + [DispId(-2147413098)] + set; } /// paddingLeft property of IHTMLStyle interface. @@ -934,10 +1013,12 @@ namespace Greenshot.Base.IEInterop { // IDL: HRESULT paddingLeft ([out, retval] VARIANT* ReturnValue); // VB6: Function paddingLeft As Any - [DispId(-2147413097)] get; + [DispId(-2147413097)] + get; // IDL: HRESULT paddingLeft (VARIANT value); // VB6: Sub paddingLeft (ByVal value As Any) - [DispId(-2147413097)] set; + [DispId(-2147413097)] + set; } /// paddingRight property of IHTMLStyle interface. diff --git a/src/Greenshot.Base/IEInterop/IHTMLTxtRange.cs b/src/Greenshot.Base/IEInterop/IHTMLTxtRange.cs index 77d258cb4..4317dfacf 100644 --- a/src/Greenshot.Base/IEInterop/IHTMLTxtRange.cs +++ b/src/Greenshot.Base/IEInterop/IHTMLTxtRange.cs @@ -137,7 +137,8 @@ namespace Greenshot.Base.IEInterop [DispId(1004)] [return: MarshalAs(UnmanagedType.BStr)] get; - [DispId(1004)] set; + [DispId(1004)] + set; } } } \ No newline at end of file diff --git a/src/Greenshot.Base/IEInterop/IWebBrowser2.cs b/src/Greenshot.Base/IEInterop/IWebBrowser2.cs index 074917726..a14c88e16 100644 --- a/src/Greenshot.Base/IEInterop/IWebBrowser2.cs +++ b/src/Greenshot.Base/IEInterop/IWebBrowser2.cs @@ -24,16 +24,16 @@ using System.Runtime.InteropServices; namespace Greenshot.Base.IEInterop { // IWebBrowser: EAB22AC1-30C1-11CF-A7EB-0000C05BAE0B -// [ComVisible(true), ComImport(), Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"), -// TypeLibType(TypeLibTypeFlags.FDual), -// InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] -// public interface IWebBrowser2 { -// [DispId(203)] -// object Document { -// [return: MarshalAs(UnmanagedType.IDispatch)] -// get; -// } -// } + // [ComVisible(true), ComImport(), Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"), + // TypeLibType(TypeLibTypeFlags.FDual), + // InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] + // public interface IWebBrowser2 { + // [DispId(203)] + // object Document { + // [return: MarshalAs(UnmanagedType.IDispatch)] + // get; + // } + // } [ComImport, /*SuppressUnmanagedCodeSecurity,*/ TypeLibType(TypeLibTypeFlags.FOleAutomation | TypeLibTypeFlags.FDual | diff --git a/src/Greenshot.Base/IniFile/IniConfig.cs b/src/Greenshot.Base/IniFile/IniConfig.cs index cbe04e11b..c6e638b3e 100644 --- a/src/Greenshot.Base/IniFile/IniConfig.cs +++ b/src/Greenshot.Base/IniFile/IniConfig.cs @@ -39,7 +39,7 @@ namespace Greenshot.Base.IniFile /// /// A lock object for the ini file saving /// - private static readonly object IniLock = new object(); + private static readonly object IniLock = new(); /// /// As the ini implementation is kept someone generic, for reusing, this holds the name of the application @@ -156,12 +156,9 @@ namespace Greenshot.Base.IniFile { get { - if (IsInitialized) - { - return CreateIniLocation(_configName + IniExtension, false); - } - - throw new InvalidOperationException("Ini configuration was not initialized!"); + return IsInitialized + ? CreateIniLocation(_configName + IniExtension, false) + : throw new InvalidOperationException("Ini configuration was not initialized!"); } } @@ -210,7 +207,7 @@ namespace Greenshot.Base.IniFile catch (Exception exception) { Log.WarnFormat("Problem retrieving the AssemblyLocation: {0} (Designer mode?)", exception.Message); - applicationStartupPath = @"."; + applicationStartupPath = "."; } if (applicationStartupPath != null) @@ -418,7 +415,7 @@ namespace Greenshot.Base.IniFile } /// - /// + /// /// /// IniSection Type to get the configuration for /// false to skip saving @@ -432,12 +429,12 @@ namespace Greenshot.Base.IniFile if (SectionMap.ContainsKey(sectionName)) { //LOG.Debug("Returning pre-mapped section " + sectionName); - section = (T) SectionMap[sectionName]; + section = (T)SectionMap[sectionName]; } else { // Create instance of this type - section = (T) Activator.CreateInstance(iniSectionType); + section = (T)Activator.CreateInstance(iniSectionType); // Store for later save & retrieval SectionMap.Add(sectionName, section); @@ -463,18 +460,15 @@ namespace Greenshot.Base.IniFile { string sectionName = section.IniSectionAttribute.Name; // Get the properties for the section - IDictionary properties; if (_sections.ContainsKey(sectionName)) { - properties = _sections[sectionName]; + return _sections[sectionName]; } else { _sections.Add(sectionName, new Dictionary()); - properties = _sections[sectionName]; + return _sections[sectionName]; } - - return properties; } /// @@ -567,7 +561,7 @@ namespace Greenshot.Base.IniFile // Don't forget to flush the buffer writer.Flush(); // Now write the created .ini string to the real file - using FileStream fileStream = new FileStream(iniLocation, FileMode.Create, FileAccess.Write); + using FileStream fileStream = new(iniLocation, FileMode.Create, FileAccess.Write); memoryStream.WriteTo(fileStream); } } diff --git a/src/Greenshot.Base/IniFile/IniSection.cs b/src/Greenshot.Base/IniFile/IniSection.cs index 73a02ee1e..e88fa75a5 100644 --- a/src/Greenshot.Base/IniFile/IniSection.cs +++ b/src/Greenshot.Base/IniFile/IniSection.cs @@ -43,12 +43,7 @@ namespace Greenshot.Base.IniFile { get { - if (iniSectionAttribute == null) - { - iniSectionAttribute = GetIniSectionAttribute(GetType()); - } - - return iniSectionAttribute; + return iniSectionAttribute ??= GetIniSectionAttribute(GetType()); } } @@ -118,9 +113,9 @@ namespace Greenshot.Base.IniFile Attribute[] classAttributes = Attribute.GetCustomAttributes(iniSectionType); foreach (Attribute attribute in classAttributes) { - if (attribute is IniSectionAttribute) + if (attribute is IniSectionAttribute iniSectionAttribute2) { - return (IniSectionAttribute) attribute; + return iniSectionAttribute2; } } @@ -140,7 +135,7 @@ namespace Greenshot.Base.IniFile { if (Attribute.IsDefined(fieldInfo, typeof(IniPropertyAttribute))) { - IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute) fieldInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0]; + IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute)fieldInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0]; if (!Values.ContainsKey(iniPropertyAttribute.Name)) { Values[iniPropertyAttribute.Name] = new IniValue(this, fieldInfo, iniPropertyAttribute); @@ -154,7 +149,7 @@ namespace Greenshot.Base.IniFile { if (!Values.ContainsKey(propertyInfo.Name)) { - IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute) propertyInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0]; + IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute)propertyInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0]; Values[iniPropertyAttribute.Name] = new IniValue(this, propertyInfo, iniPropertyAttribute); } } diff --git a/src/Greenshot.Base/IniFile/IniValue.cs b/src/Greenshot.Base/IniFile/IniValue.cs index 5a80cefae..2299e494a 100644 --- a/src/Greenshot.Base/IniFile/IniValue.cs +++ b/src/Greenshot.Base/IniFile/IniValue.cs @@ -37,21 +37,19 @@ namespace Greenshot.Base.IniFile private static readonly ILog Log = LogManager.GetLogger(typeof(IniValue)); private readonly PropertyInfo _propertyInfo; private readonly FieldInfo _fieldInfo; - private readonly IniSection _containingIniSection; - private readonly IniPropertyAttribute _attributes; public IniValue(IniSection containingIniSection, PropertyInfo propertyInfo, IniPropertyAttribute iniPropertyAttribute) { - _containingIniSection = containingIniSection; + ContainingIniSection = containingIniSection; _propertyInfo = propertyInfo; - _attributes = iniPropertyAttribute; + Attributes = iniPropertyAttribute; } public IniValue(IniSection containingIniSection, FieldInfo fieldInfo, IniPropertyAttribute iniPropertyAttribute) { - _containingIniSection = containingIniSection; + ContainingIniSection = containingIniSection; _fieldInfo = fieldInfo; - _attributes = iniPropertyAttribute; + Attributes = iniPropertyAttribute; } /// @@ -61,18 +59,13 @@ namespace Greenshot.Base.IniFile { get { - if (_attributes != null) - { - return _attributes.FixedValue; - } - - return false; + return Attributes != null && Attributes.FixedValue; } set { - if (_attributes != null) + if (Attributes != null) { - _attributes.FixedValue = value; + Attributes.FixedValue = value; } } } @@ -84,23 +77,17 @@ namespace Greenshot.Base.IniFile { get { - if (_attributes != null) - { - return _attributes.Expert; - } - - return false; + return Attributes != null && Attributes.Expert; } set { - if (_attributes != null) + if (Attributes != null) { - _attributes.Expert = value; + Attributes.Expert = value; } } } - /// /// Return true when the value is can be changed by the GUI /// @@ -115,24 +102,19 @@ namespace Greenshot.Base.IniFile { get { - if (_propertyInfo == null) - { - return _fieldInfo; - } - - return _propertyInfo; + return _propertyInfo == null ? _fieldInfo : _propertyInfo; } } /// /// Returns the IniSection this value is contained in /// - public IniSection ContainingIniSection => _containingIniSection; + public IniSection ContainingIniSection { get; } /// /// Get the in the ini file defined attributes /// - public IniPropertyAttribute Attributes => _attributes; + public IniPropertyAttribute Attributes { get; } /// /// Get the value for this IniValue @@ -141,22 +123,17 @@ namespace Greenshot.Base.IniFile { get { - if (_propertyInfo == null) - { - return _fieldInfo.GetValue(_containingIniSection); - } - - return _propertyInfo.GetValue(_containingIniSection, null); + return _propertyInfo == null ? _fieldInfo.GetValue(ContainingIniSection) : _propertyInfo.GetValue(ContainingIniSection, null); } set { if (_propertyInfo == null) { - _fieldInfo.SetValue(_containingIniSection, value); + _fieldInfo.SetValue(ContainingIniSection, value); } else { - _propertyInfo.SetValue(_containingIniSection, value, null); + _propertyInfo.SetValue(ContainingIniSection, value, null); } } } @@ -196,19 +173,19 @@ namespace Greenshot.Base.IniFile Type valueType = ValueType; if (myValue == null) { - if (_attributes.ExcludeIfNull) + if (Attributes.ExcludeIfNull) { return; } - if (_attributes.DefaultValue != null) + if (Attributes.DefaultValue != null) { - myValue = _attributes.DefaultValue; + myValue = Attributes.DefaultValue; valueType = typeof(string); } else { - myValue = _containingIniSection.GetDefault(_attributes.Name); + myValue = ContainingIniSection.GetDefault(Attributes.Name); if (myValue != null) { valueType = myValue.GetType(); @@ -218,7 +195,7 @@ namespace Greenshot.Base.IniFile if (myValue == null) { - if (_attributes.ExcludeIfNull) + if (Attributes.ExcludeIfNull) { return; } @@ -226,12 +203,12 @@ namespace Greenshot.Base.IniFile if (!onlyProperties) { - writer.WriteLine("; {0}", _attributes.Description); + writer.WriteLine("; {0}", Attributes.Description); } if (myValue == null) { - writer.WriteLine("{0}=", _attributes.Name); + writer.WriteLine("{0}=", Attributes.Name); return; } @@ -247,7 +224,7 @@ namespace Greenshot.Base.IniFile var moveNext = enumerator.GetType().GetMethod("MoveNext"); var current = enumerator.GetType().GetProperty("Current").GetGetMethod(); // Get all the values. - while ((bool) moveNext.Invoke(enumerator, null)) + while ((bool)moveNext.Invoke(enumerator, null)) { var key = current.Invoke(enumerator, null); var valueObject = item.GetValue(myValue, new[] @@ -255,13 +232,13 @@ namespace Greenshot.Base.IniFile key }); // Write to ini file! - writer.WriteLine("{0}.{1}={2}", _attributes.Name, ConvertValueToString(valueType1, key, _attributes.Separator), - ConvertValueToString(valueType2, valueObject, _attributes.Separator)); + writer.WriteLine("{0}.{1}={2}", Attributes.Name, ConvertValueToString(valueType1, key, Attributes.Separator), + ConvertValueToString(valueType2, valueObject, Attributes.Separator)); } } else { - writer.WriteLine("{0}={1}", _attributes.Name, ConvertValueToString(valueType, myValue, _attributes.Separator)); + writer.WriteLine("{0}={1}", Attributes.Name, ConvertValueToString(valueType, myValue, Attributes.Separator)); } } @@ -271,11 +248,11 @@ namespace Greenshot.Base.IniFile /// public void SetValueFromProperties(IDictionary properties) { - string propertyName = _attributes.Name; + string propertyName = Attributes.Name; string propertyValue = null; if (properties.ContainsKey(propertyName) && properties[propertyName] != null) { - propertyValue = _containingIniSection.PreCheckValue(propertyName, properties[propertyName]); + propertyValue = ContainingIniSection.PreCheckValue(propertyName, properties[propertyName]); } UseValueOrDefault(propertyValue); @@ -288,10 +265,10 @@ namespace Greenshot.Base.IniFile public void UseValueOrDefault(string propertyValue) { Type valueType = ValueType; - string propertyName = _attributes.Name; - string defaultValue = _attributes.DefaultValue; + string propertyName = Attributes.Name; + string defaultValue = Attributes.DefaultValue; bool defaultUsed = false; - object defaultValueFromConfig = _containingIniSection.GetDefault(propertyName); + object defaultValueFromConfig = ContainingIniSection.GetDefault(propertyName); if (string.IsNullOrEmpty(propertyValue)) { @@ -306,7 +283,7 @@ namespace Greenshot.Base.IniFile } else { - if (_attributes.ExcludeIfNull) + if (Attributes.ExcludeIfNull) { Value = null; return; @@ -326,10 +303,10 @@ namespace Greenshot.Base.IniFile object dictionary = Activator.CreateInstance(valueType); MethodInfo addMethodInfo = valueType.GetMethod("Add"); bool addedElements = false; - IDictionary properties = IniConfig.PropertiesForSection(_containingIniSection); + IDictionary properties = IniConfig.PropertiesForSection(ContainingIniSection); foreach (string key in properties.Keys) { - if (key != null && key.StartsWith(propertyName + ".")) + if (key?.StartsWith(propertyName + ".") == true) { // What "key" do we need to store it under? string subPropertyName = key.Substring(propertyName.Length + 1); @@ -338,7 +315,7 @@ namespace Greenshot.Base.IniFile object newValue2 = null; try { - newValue1 = ConvertStringToValueType(type1, subPropertyName, _attributes.Separator); + newValue1 = ConvertStringToValueType(type1, subPropertyName, Attributes.Separator); } catch (Exception ex) { @@ -348,7 +325,7 @@ namespace Greenshot.Base.IniFile try { - newValue2 = ConvertStringToValueType(type2, stringValue, _attributes.Separator); + newValue2 = ConvertStringToValueType(type2, stringValue, Attributes.Separator); } catch (Exception ex) { @@ -388,7 +365,7 @@ namespace Greenshot.Base.IniFile object newValue; try { - newValue = ConvertStringToValueType(valueType, propertyValue, _attributes.Separator); + newValue = ConvertStringToValueType(valueType, propertyValue, Attributes.Separator); } catch (Exception ex1) { @@ -398,7 +375,7 @@ namespace Greenshot.Base.IniFile try { Log.WarnFormat("Problem '{0}' while converting {1} to type {2} trying fallback...", ex1.Message, propertyValue, valueType.FullName); - newValue = ConvertStringToValueType(valueType, defaultValue, _attributes.Separator); + newValue = ConvertStringToValueType(valueType, defaultValue, Attributes.Separator); ContainingIniSection.IsDirty = true; Log.InfoFormat("Used default value {0} for property {1}", defaultValue, propertyName); } @@ -432,7 +409,7 @@ namespace Greenshot.Base.IniFile } catch (Exception) { - Log.WarnFormat("Couldn't create instance of {0} for {1}, using default value.", ValueType.FullName, _attributes.Name); + Log.WarnFormat("Couldn't create instance of {0} for {1}, using default value.", ValueType.FullName, Attributes.Name); Value = default(ValueType); } } @@ -545,7 +522,7 @@ namespace Greenshot.Base.IniFile /// string representation of this public override string ToString() { - return ConvertValueToString(ValueType, Value, _attributes.Separator); + return ConvertValueToString(ValueType, Value, Attributes.Separator); } /// @@ -565,9 +542,9 @@ namespace Greenshot.Base.IniFile if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(List<>)) { - StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder = new(); Type specificValueType = valueType.GetGenericArguments()[0]; - int listCount = (int) valueType.GetProperty("Count").GetValue(valueObject, null); + int listCount = (int)valueType.GetProperty("Count").GetValue(valueObject, null); // Loop though generic list for (int index = 0; index < listCount; index++) { diff --git a/src/Greenshot.Base/Interfaces/ICaptureHelper.cs b/src/Greenshot.Base/Interfaces/ICaptureHelper.cs index 9b15032ad..3cc596a97 100644 --- a/src/Greenshot.Base/Interfaces/ICaptureHelper.cs +++ b/src/Greenshot.Base/Interfaces/ICaptureHelper.cs @@ -30,7 +30,7 @@ namespace Greenshot.Base.Interfaces public interface ICaptureHelper { /// - /// + /// /// /// /// diff --git a/src/Greenshot.Base/Interfaces/IFileFormatHandler.cs b/src/Greenshot.Base/Interfaces/IFileFormatHandler.cs index bd5558857..7e8ef1a40 100644 --- a/src/Greenshot.Base/Interfaces/IFileFormatHandler.cs +++ b/src/Greenshot.Base/Interfaces/IFileFormatHandler.cs @@ -68,7 +68,7 @@ namespace Greenshot.Base.Interfaces public bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null); /// - /// + /// /// /// /// diff --git a/src/Greenshot.Base/Interfaces/Ocr/OcrInformation.cs b/src/Greenshot.Base/Interfaces/Ocr/OcrInformation.cs index 216265099..5c6b4c8d4 100644 --- a/src/Greenshot.Base/Interfaces/Ocr/OcrInformation.cs +++ b/src/Greenshot.Base/Interfaces/Ocr/OcrInformation.cs @@ -33,7 +33,7 @@ namespace Greenshot.Base.Interfaces.Ocr /// /// Check if there is any content /// - public bool HasContent => Lines.Any(); + public bool HasContent => Lines.Count > 0; /// /// The complete text diff --git a/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs b/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs index efce47bbb..68be7ebb6 100644 --- a/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs +++ b/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs @@ -84,12 +84,7 @@ namespace Greenshot.Base.Interfaces.Plugin get { // Fix for Bug #3468436, force quantizing when output format is gif as this has only 256 colors! - if (OutputFormat.gif.Equals(Format)) - { - return true; - } - - return _reduceColors; + return OutputFormat.gif.Equals(Format) || _reduceColors; } set { _reduceColors = value; } } diff --git a/src/Greenshot.Base/Interfaces/SurfaceBackgroundColorEventHandler.cs b/src/Greenshot.Base/Interfaces/SurfaceBackgroundColorEventHandler.cs index a2a93703b..d632c61af 100644 --- a/src/Greenshot.Base/Interfaces/SurfaceBackgroundColorEventHandler.cs +++ b/src/Greenshot.Base/Interfaces/SurfaceBackgroundColorEventHandler.cs @@ -21,5 +21,5 @@ namespace Greenshot.Base.Interfaces { - public delegate void SurfaceBackgroundColorEventHandler (object sender, SurfaceBackgroundColorEventArgs e); + public delegate void SurfaceBackgroundColorEventHandler(object sender, SurfaceBackgroundColorEventArgs e); } \ No newline at end of file diff --git a/src/Greenshot.Base/Interfaces/SurfaceForegroundColorEventHandler.cs b/src/Greenshot.Base/Interfaces/SurfaceForegroundColorEventHandler.cs index 9c62cee2d..b117bee80 100644 --- a/src/Greenshot.Base/Interfaces/SurfaceForegroundColorEventHandler.cs +++ b/src/Greenshot.Base/Interfaces/SurfaceForegroundColorEventHandler.cs @@ -21,5 +21,5 @@ namespace Greenshot.Base.Interfaces { - public delegate void SurfaceForegroundColorEventHandler (object sender, SurfaceForegroundColorEventArgs e); + public delegate void SurfaceForegroundColorEventHandler(object sender, SurfaceForegroundColorEventArgs e); } \ No newline at end of file diff --git a/src/Greenshot.Base/Interfaces/SurfaceLineThicknessEventHandler.cs b/src/Greenshot.Base/Interfaces/SurfaceLineThicknessEventHandler.cs index 9f8ac3ebe..99feb69ac 100644 --- a/src/Greenshot.Base/Interfaces/SurfaceLineThicknessEventHandler.cs +++ b/src/Greenshot.Base/Interfaces/SurfaceLineThicknessEventHandler.cs @@ -21,5 +21,5 @@ namespace Greenshot.Base.Interfaces { - public delegate void SurfaceLineThicknessEventHandler (object sender, SurfaceLineThicknessEventArgs e); + public delegate void SurfaceLineThicknessEventHandler(object sender, SurfaceLineThicknessEventArgs e); } \ No newline at end of file diff --git a/src/Greenshot.Base/Interfaces/SurfaceShadowEventHandler.cs b/src/Greenshot.Base/Interfaces/SurfaceShadowEventHandler.cs index a303aea62..f3e34cfff 100644 --- a/src/Greenshot.Base/Interfaces/SurfaceShadowEventHandler.cs +++ b/src/Greenshot.Base/Interfaces/SurfaceShadowEventHandler.cs @@ -21,5 +21,5 @@ namespace Greenshot.Base.Interfaces { - public delegate void SurfaceShadowEventHandler (object sender, SurfaceShadowEventArgs e); + public delegate void SurfaceShadowEventHandler(object sender, SurfaceShadowEventArgs e); } \ No newline at end of file diff --git a/src/Greenshot.Base/Interop/COMWrapper.cs b/src/Greenshot.Base/Interop/COMWrapper.cs index 5dd528214..3f75165a4 100644 --- a/src/Greenshot.Base/Interop/COMWrapper.cs +++ b/src/Greenshot.Base/Interop/COMWrapper.cs @@ -37,8 +37,8 @@ namespace Greenshot.Base.Interop public sealed class COMWrapper : RealProxy, IDisposable, IRemotingTypeInfo { private static readonly ILog Log = LogManager.GetLogger(typeof(COMWrapper)); - public const int RPC_E_CALL_REJECTED = unchecked((int) 0x80010001); - public const int RPC_E_FAIL = unchecked((int) 0x80004005); + public const int RPC_E_CALL_REJECTED = unchecked((int)0x80010001); + public const int RPC_E_FAIL = unchecked((int)0x80004005); /// /// Holds reference to the actual COM object which is wrapped by this proxy @@ -67,7 +67,7 @@ namespace Greenshot.Base.Interop public static T CreateInstance() { Type type = typeof(T); - if (null == type) + if (type == null) { throw new ArgumentNullException(nameof(T)); } @@ -87,7 +87,7 @@ namespace Greenshot.Base.Interop Type comType = null; if (progId.StartsWith("clsid:")) { - Guid guid = new Guid(progId.Substring(6)); + Guid guid = new(progId.Substring(6)); try { comType = Type.GetTypeFromCLSID(guid); @@ -127,12 +127,7 @@ namespace Greenshot.Base.Interop } } - if (comObject != null) - { - return (T) comObject; - } - - return default; + return comObject != null ? (T)comObject : default; } /// @@ -144,17 +139,17 @@ namespace Greenshot.Base.Interop /// Transparent proxy to the real proxy for the object private static object Wrap(object comObject, Type type, string targetName) { - if (null == comObject) + if (comObject == null) { throw new ArgumentNullException(nameof(comObject)); } - if (null == type) + if (type == null) { throw new ArgumentNullException(nameof(type)); } - COMWrapper wrapper = new COMWrapper(comObject, type, targetName); + COMWrapper wrapper = new(comObject, type, targetName); return wrapper.GetTransparentProxy(); } @@ -204,7 +199,7 @@ namespace Greenshot.Base.Interop /// private void Dispose(bool disposing) { - if (null != _comObject) + if (_comObject != null) { Log.DebugFormat("Disposing {0}", _interceptType); if (Marshal.IsComObject(_comObject)) @@ -264,10 +259,9 @@ namespace Greenshot.Base.Interop /// public override bool Equals(object value) { - if (null != value && RemotingServices.IsTransparentProxy(value)) + if (value != null && RemotingServices.IsTransparentProxy(value)) { - COMWrapper wrapper = RemotingServices.GetRealProxy(value) as COMWrapper; - if (null != wrapper) + if (RemotingServices.GetRealProxy(value) is COMWrapper wrapper) { return _comObject == wrapper._comObject; } @@ -290,7 +284,7 @@ namespace Greenshot.Base.Interop /// private static Type GetByValType(Type byRefType) { - if (null == byRefType) + if (byRefType == null) { throw new ArgumentNullException(nameof(byRefType)); } @@ -306,7 +300,7 @@ namespace Greenshot.Base.Interop } /// - /// Intercept method calls + /// Intercept method calls /// /// /// Contains information about the method being called @@ -316,14 +310,14 @@ namespace Greenshot.Base.Interop /// public override IMessage Invoke(IMessage myMessage) { - if (!(myMessage is IMethodCallMessage callMessage)) + if (myMessage is not IMethodCallMessage callMessage) { Log.DebugFormat("Message type not implemented: {0}", myMessage.GetType()); return null; } MethodInfo method = callMessage.MethodBase as MethodInfo; - if (null == method) + if (method == null) { Log.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase); return null; @@ -341,33 +335,34 @@ namespace Greenshot.Base.Interop ParameterModifier[] argModifiers = null; ParameterInfo[] parameters = null; - if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType) + if (methodName == "Dispose" && argCount == 0 && typeof(void) == returnType) { Dispose(); } - else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType) + else if (methodName == "ToString" && argCount == 0 && typeof(string) == returnType) { returnValue = ToString(); } - else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType) + else if (methodName == "GetType" && argCount == 0 && typeof(Type) == returnType) { returnValue = _interceptType; } - else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType) + else if (methodName == "GetHashCode" && argCount == 0 && typeof(int) == returnType) { returnValue = GetHashCode(); } - else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType) + else if (methodName == "Equals" && argCount == 1 && typeof(bool) == returnType) { returnValue = Equals(callMessage.Args[0]); } - else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_"))) + else if (argCount == 1 && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_"))) { bool removeHandler = methodName.StartsWith("remove_"); - methodName = methodName.Substring(removeHandler ? 7 : 4); + _ = methodName.Substring(removeHandler ? 7 : 4); // TODO: Something is missing here - if (!(callMessage.InArgs[0] is Delegate handler)) + if (callMessage.InArgs[0] is not Delegate) { + Delegate handler; return new ReturnMessage(new ArgumentNullException(nameof(handler)), callMessage); } } @@ -395,7 +390,7 @@ namespace Greenshot.Base.Interop else { args = callMessage.Args; - if (null != args && 0 != args.Length) + if (args != null && args.Length != 0) { // Modifiers for ref / out parameters argModifiers = new ParameterModifier[1]; @@ -412,7 +407,7 @@ namespace Greenshot.Base.Interop } } - if (0 == outArgsCount) + if (outArgsCount == 0) { argModifiers = null; } @@ -423,7 +418,7 @@ namespace Greenshot.Base.Interop Type byValType; COMWrapper wrapper; COMWrapper[] originalArgs; - if (null == args || 0 == args.Length) + if (args == null || args.Length == 0) { originalArgs = null; } @@ -432,16 +427,16 @@ namespace Greenshot.Base.Interop originalArgs = new COMWrapper[args.Length]; for (int i = 0; i < args.Length; i++) { - if (null != args[i] && RemotingServices.IsTransparentProxy(args[i])) + if (args[i] != null && RemotingServices.IsTransparentProxy(args[i])) { wrapper = RemotingServices.GetRealProxy(args[i]) as COMWrapper; - if (null != wrapper) + if (wrapper != null) { originalArgs[i] = wrapper; args[i] = wrapper._comObject; } } - else if (0 != outArgsCount && argModifiers[0][i]) + else if (outArgsCount != 0 && argModifiers[0][i]) { byValType = GetByValType(parameters[i].ParameterType); if (byValType.IsInterface) @@ -449,7 +444,7 @@ namespace Greenshot.Base.Interop // If we're passing a COM object by reference, and // the parameter is null, we need to pass a // DispatchWrapper to avoid a type mismatch exception. - if (null == args[i]) + if (args[i] == null) { args[i] = new DispatchWrapper(null); } @@ -466,7 +461,7 @@ namespace Greenshot.Base.Interop } } - do + while (true) { try { @@ -482,7 +477,7 @@ namespace Greenshot.Base.Interop catch (Exception ex) { // Test for rejected - if (!(ex is COMException comEx)) + if (ex is not COMException comEx) { comEx = ex.InnerException as COMException; } @@ -491,7 +486,7 @@ namespace Greenshot.Base.Interop { string destinationName = _targetName; // Try to find a "catchy" name for the rejecting application - if (destinationName != null && destinationName.Contains(".")) + if (destinationName?.Contains(".") == true) { destinationName = destinationName.Substring(0, destinationName.IndexOf(".", StringComparison.Ordinal)); } @@ -514,10 +509,10 @@ namespace Greenshot.Base.Interop // Not rejected OR pressed cancel return new ReturnMessage(ex, callMessage); } - } while (true); + } // Handle enum and interface return types - if (null != returnValue) + if (returnValue != null) { if (returnType.IsInterface) { @@ -535,7 +530,7 @@ namespace Greenshot.Base.Interop } // Handle out args - if (0 != outArgsCount) + if (outArgsCount != 0) { outArgs = new object[args.Length]; for (int i = 0; i < parameters.Length; i++) @@ -546,20 +541,18 @@ namespace Greenshot.Base.Interop } var arg = args[i]; - if (null == arg) + if (arg == null) { continue; } parameter = parameters[i]; - wrapper = null; - byValType = GetByValType(parameter.ParameterType); if (typeof(decimal) == byValType) { - if (arg is CurrencyWrapper) + if (arg is CurrencyWrapper wrapper1) { - arg = ((CurrencyWrapper) arg).WrappedObject; + arg = wrapper1.WrappedObject; } } else if (byValType.IsEnum) @@ -571,13 +564,13 @@ namespace Greenshot.Base.Interop if (Marshal.IsComObject(arg)) { wrapper = originalArgs[i]; - if (null != wrapper && wrapper._comObject != arg) + if (wrapper != null && wrapper._comObject != arg) { wrapper.Dispose(); wrapper = null; } - if (null == wrapper) + if (wrapper == null) { wrapper = new COMWrapper(arg, byValType, _targetName); } diff --git a/src/Greenshot.Base/Interop/ComProgIdAttribute.cs b/src/Greenshot.Base/Interop/ComProgIdAttribute.cs index 48c5168d5..f4e6fcebc 100644 --- a/src/Greenshot.Base/Interop/ComProgIdAttribute.cs +++ b/src/Greenshot.Base/Interop/ComProgIdAttribute.cs @@ -43,7 +43,7 @@ namespace Greenshot.Base.Interop /// public static ComProgIdAttribute GetAttribute(Type interfaceType) { - if (null == interfaceType) + if (interfaceType == null) { throw new ArgumentNullException(nameof(interfaceType)); } @@ -51,26 +51,21 @@ namespace Greenshot.Base.Interop Type attributeType = typeof(ComProgIdAttribute); object[] attributes = interfaceType.GetCustomAttributes(attributeType, false); - if (0 == attributes.Length) + if (attributes.Length == 0) { Type[] interfaces = interfaceType.GetInterfaces(); foreach (Type t in interfaces) { interfaceType = t; attributes = interfaceType.GetCustomAttributes(attributeType, false); - if (0 != attributes.Length) + if (attributes.Length != 0) { break; } } } - if (0 == attributes.Length) - { - return null; - } - - return (ComProgIdAttribute) attributes[0]; + return attributes.Length == 0 ? null : (ComProgIdAttribute)attributes[0]; } /// Constructor diff --git a/src/Greenshot.Editor/Configuration/EditorConfiguration.cs b/src/Greenshot.Editor/Configuration/EditorConfiguration.cs index 3a516797c..3e022a174 100644 --- a/src/Greenshot.Editor/Configuration/EditorConfiguration.cs +++ b/src/Greenshot.Editor/Configuration/EditorConfiguration.cs @@ -80,7 +80,6 @@ namespace Greenshot.Editor.Configuration [IniProperty("DefaultEditorSize", Description = "The size for the editor when it's opened without a capture", DefaultValue = "500,500")] public NativeSize DefaultEditorSize { get; set; } - public override void AfterLoad() { base.AfterLoad(); @@ -140,14 +139,7 @@ namespace Greenshot.Editor.Configuration LastUsedFieldValues ??= new Dictionary(); // check if settings for the requesting type exist, if not create! - if (LastUsedFieldValues.ContainsKey(requestedField)) - { - LastUsedFieldValues[requestedField] = field.Value; - } - else - { - LastUsedFieldValues.Add(requestedField, field.Value); - } + LastUsedFieldValues[requestedField] = field.Value; } public void ResetEditorPlacement() diff --git a/src/Greenshot.Editor/Controls/BindableToolStripDropDownButton.cs b/src/Greenshot.Editor/Controls/BindableToolStripDropDownButton.cs index 7d0a45676..60723c091 100644 --- a/src/Greenshot.Editor/Controls/BindableToolStripDropDownButton.cs +++ b/src/Greenshot.Editor/Controls/BindableToolStripDropDownButton.cs @@ -50,7 +50,7 @@ namespace Greenshot.Editor.Controls protected override void OnDropDownItemClicked(ToolStripItemClickedEventArgs e) { ToolStripItem clickedItem = e.ClickedItem; - if (Tag == null || !Tag.Equals(clickedItem.Tag)) + if (Tag?.Equals(clickedItem.Tag) != true) { Tag = clickedItem.Tag; Image = clickedItem.Image; @@ -62,12 +62,12 @@ namespace Greenshot.Editor.Controls private void AdoptFromTag(object tag) { - if (Tag == null || !Tag.Equals(tag)) + if (Tag?.Equals(tag) != true) { Tag = tag; foreach (ToolStripItem item in DropDownItems) { - if (item.Tag != null && item.Tag.Equals(tag)) + if (item.Tag?.Equals(tag) == true) { Image = item.Image; break; diff --git a/src/Greenshot.Editor/Controls/FontFamilyComboBox.cs b/src/Greenshot.Editor/Controls/FontFamilyComboBox.cs index cabb40e49..c9e8470f0 100644 --- a/src/Greenshot.Editor/Controls/FontFamilyComboBox.cs +++ b/src/Greenshot.Editor/Controls/FontFamilyComboBox.cs @@ -28,7 +28,7 @@ using Dapplo.Windows.Common.Structs; namespace Greenshot.Editor.Controls { /// - /// ToolStripComboBox containing installed font families, + /// ToolStripComboBox containing installed font families, /// implementing INotifyPropertyChanged for data binding /// public class FontFamilyComboBox : ToolStripComboBox, INotifyPropertyChanged @@ -37,7 +37,7 @@ namespace Greenshot.Editor.Controls public FontFamily FontFamily { - get { return (FontFamily) SelectedItem; } + get { return (FontFamily)SelectedItem; } set { if (!SelectedItem.Equals(value)) @@ -70,7 +70,7 @@ namespace Greenshot.Editor.Controls { FontFamily fontFamily = Items[e.Index] as FontFamily; FontStyle fontStyle = FontStyle.Regular; - if (fontFamily != null && !fontFamily.IsStyleAvailable(FontStyle.Regular)) + if (fontFamily?.IsStyleAvailable(FontStyle.Regular) == false) { if (fontFamily.IsStyleAvailable(FontStyle.Bold)) { @@ -121,9 +121,9 @@ namespace Greenshot.Editor.Controls /// string private void DrawText(Graphics graphics, FontFamily fontFamily, FontStyle fontStyle, NativeRect bounds, string text) { - using Font font = new Font(fontFamily, Font.Size + 5, fontStyle, GraphicsUnit.Pixel); + using Font font = new(fontFamily, Font.Size + 5, fontStyle, GraphicsUnit.Pixel); // Make sure the text is visible by centering it in the line - using StringFormat stringFormat = new StringFormat + using StringFormat stringFormat = new() { LineAlignment = StringAlignment.Center }; diff --git a/src/Greenshot.Editor/Controls/MenuStripEx.cs b/src/Greenshot.Editor/Controls/MenuStripEx.cs index c140416f6..43ee46685 100644 --- a/src/Greenshot.Editor/Controls/MenuStripEx.cs +++ b/src/Greenshot.Editor/Controls/MenuStripEx.cs @@ -37,28 +37,21 @@ namespace Greenshot.Editor.Controls MA_ACTIVATEANDEAT = 2, } - private bool _clickThrough; - /// /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// /// /// Default value is false, which is the same behavior provided by the base ToolStrip class. /// - public bool ClickThrough - { - get { return _clickThrough; } - - set { _clickThrough = value; } - } + public bool ClickThrough { get; set; } protected override void WndProc(ref Message m) { base.WndProc(ref m); - var windowsMessage = (WindowsMessages) m.Msg; - if (_clickThrough && windowsMessage == WindowsMessages.WM_MOUSEACTIVATE && m.Result == (IntPtr) NativeConstants.MA_ACTIVATEANDEAT) + var windowsMessage = (WindowsMessages)m.Msg; + if (ClickThrough && windowsMessage == WindowsMessages.WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) { - m.Result = (IntPtr) NativeConstants.MA_ACTIVATE; + m.Result = (IntPtr)NativeConstants.MA_ACTIVATE; } } } diff --git a/src/Greenshot.Editor/Controls/Pipette.cs b/src/Greenshot.Editor/Controls/Pipette.cs index dc1ae1046..9a07f235a 100644 --- a/src/Greenshot.Editor/Controls/Pipette.cs +++ b/src/Greenshot.Editor/Controls/Pipette.cs @@ -51,7 +51,7 @@ namespace Greenshot.Editor.Controls { BorderStyle = BorderStyle.FixedSingle; _dragging = false; - _image = (Bitmap) new ComponentResourceManager(typeof(ColorDialog)).GetObject("pipette.Image"); + _image = (Bitmap)new ComponentResourceManager(typeof(ColorDialog)).GetObject("pipette.Image"); Image = _image; _cursor = CreateCursor(_image, 1, 14); _movableShowColorForm = new MovableShowColorForm(); @@ -67,7 +67,7 @@ namespace Greenshot.Editor.Controls /// Cursor private static Cursor CreateCursor(Bitmap bitmap, int hotspotX, int hotspotY) { - using SafeIconHandle iconHandle = new SafeIconHandle(bitmap.GetHicon()); + using SafeIconHandle iconHandle = new(bitmap.GetHicon()); NativeIconMethods.GetIconInfo(iconHandle, out var iconInfo); iconInfo.Hotspot = new NativePoint(hotspotX, hotspotY); iconInfo.IsIcon = false; @@ -91,10 +91,7 @@ namespace Greenshot.Editor.Controls { if (disposing) { - if (_cursor != null) - { - _cursor.Dispose(); - } + _cursor?.Dispose(); _movableShowColorForm?.Dispose(); } @@ -181,9 +178,9 @@ namespace Greenshot.Editor.Controls { if (_dragging) { - if (m.Msg == (int) WindowsMessages.WM_CHAR) + if (m.Msg == (int)WindowsMessages.WM_CHAR) { - if ((int) m.WParam == VkEsc) + if ((int)m.WParam == VkEsc) { User32Api.ReleaseCapture(); } diff --git a/src/Greenshot.Editor/Controls/ToolStripEx.cs b/src/Greenshot.Editor/Controls/ToolStripEx.cs index 39e1859cc..f6a3dac46 100644 --- a/src/Greenshot.Editor/Controls/ToolStripEx.cs +++ b/src/Greenshot.Editor/Controls/ToolStripEx.cs @@ -38,28 +38,20 @@ namespace Greenshot.Editor.Controls MA_ACTIVATEANDEAT = 2, } - private bool _clickThrough; - /// /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// /// /// Default value is false, which is the same behavior provided by the base ToolStrip class. /// - - public bool ClickThrough - { - get { return _clickThrough; } - - set { _clickThrough = value; } - } + public bool ClickThrough { get; set; } protected override void WndProc(ref Message m) { base.WndProc(ref m); - if (_clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr) NativeConstants.MA_ACTIVATEANDEAT) + if (ClickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) { - m.Result = (IntPtr) NativeConstants.MA_ACTIVATE; + m.Result = (IntPtr)NativeConstants.MA_ACTIVATE; } } } diff --git a/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs b/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs index 89caa257c..c8b41a4a5 100644 --- a/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs +++ b/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs @@ -67,7 +67,6 @@ namespace Greenshot.Editor.Controls set { NumericUpDown.DecimalPlaces = value; } } - protected override void OnSubscribeControlEvents(Control control) { base.OnSubscribeControlEvents(control); diff --git a/src/Greenshot.Editor/Destinations/EditorDestination.cs b/src/Greenshot.Editor/Destinations/EditorDestination.cs index bfc143d88..95d6d42ba 100644 --- a/src/Greenshot.Editor/Destinations/EditorDestination.cs +++ b/src/Greenshot.Editor/Destinations/EditorDestination.cs @@ -59,12 +59,9 @@ namespace Greenshot.Editor.Destinations { get { - if (editor == null) - { - return Language.GetString(LangKey.settings_destination_editor); - } - - return Language.GetString(LangKey.settings_destination_editor) + " - " + editor.CaptureDetails.Title?.Substring(0, Math.Min(20, editor.CaptureDetails.Title.Length)); + return 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)); } } @@ -84,7 +81,7 @@ namespace Greenshot.Editor.Destinations public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); // Make sure we collect the garbage before opening the screenshot GC.Collect(); GC.WaitForPendingFinalizers(); @@ -108,7 +105,7 @@ namespace Greenshot.Editor.Destinations { try { - ImageEditorForm editorForm = new ImageEditorForm(surface, !surface.Modified); // Output made?? + ImageEditorForm editorForm = new(surface, !surface.Modified); // Output made?? if (!string.IsNullOrEmpty(captureDetails.Filename)) { diff --git a/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs index a2dd980a6..c53f098c8 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs @@ -122,7 +122,7 @@ namespace Greenshot.Editor.Drawing.Adorners get { NativePoint displayLocation = Owner.Parent.ToSurfaceCoordinates(Location); - return new NativeRect(displayLocation.X - Size.Width / 2, displayLocation.Y - Size.Height / 2, Size.Width, Size.Height); + return new NativeRect(displayLocation.X - (Size.Width / 2), displayLocation.Y - (Size.Height / 2), Size.Width, Size.Height); } } diff --git a/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs index 864ff28c5..11028df1d 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs @@ -63,8 +63,8 @@ namespace Greenshot.Editor.Drawing.Adorners } Owner.Invalidate(); - NativePoint newGripperLocation = new NativePoint(mouseEventArgs.X, mouseEventArgs.Y); - NativeRect imageBounds = new NativeRect(0, 0, Owner.Parent.Image.Width, Owner.Parent.Image.Height); + NativePoint newGripperLocation = new(mouseEventArgs.X, mouseEventArgs.Y); + NativeRect imageBounds = new(0, 0, Owner.Parent.Image.Width, Owner.Parent.Image.Height); // Check if gripper inside the parent (surface), if not we need to move it inside // This was made for BUG-1682 if (!imageBounds.Contains(newGripperLocation)) diff --git a/src/Greenshot.Editor/Drawing/ArrowContainer.cs b/src/Greenshot.Editor/Drawing/ArrowContainer.cs index 91c76366b..27875d28e 100644 --- a/src/Greenshot.Editor/Drawing/ArrowContainer.cs +++ b/src/Greenshot.Editor/Drawing/ArrowContainer.cs @@ -44,7 +44,7 @@ namespace Greenshot.Editor.Drawing BOTH }; - private static readonly AdjustableArrowCap ARROW_CAP = new AdjustableArrowCap(4, 6); + private static readonly AdjustableArrowCap ARROW_CAP = new(4, 6); public ArrowContainer(ISurface parent) : base(parent) { @@ -69,23 +69,23 @@ namespace Greenshot.Editor.Drawing bool shadow = GetFieldValueAsBool(FieldType.SHADOW); if (lineThickness <= 0) return; - + graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.None; Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); - ArrowHeadCombination heads = (ArrowHeadCombination) GetFieldValue(FieldType.ARROWHEADS); + ArrowHeadCombination heads = (ArrowHeadCombination)GetFieldValue(FieldType.ARROWHEADS); if (shadow) { //draw shadow first - int basealpha = 100; + const int basealpha = 100; int alpha = basealpha; - int steps = 5; + const int steps = 5; int currentStep = 1; while (currentStep <= steps) { - using Pen shadowCapPen = new Pen(Color.FromArgb(alpha, 100, 100, 100), lineThickness); + using Pen shadowCapPen = new(Color.FromArgb(alpha, 100, 100, 100), lineThickness); SetArrowHeads(heads, shadowCapPen); graphics.DrawLine(shadowCapPen, @@ -99,7 +99,7 @@ namespace Greenshot.Editor.Drawing } } - using Pen pen = new Pen(lineColor, lineThickness); + using Pen pen = new(lineColor, lineThickness); SetArrowHeads(heads, pen); graphics.DrawLine(pen, Left, Top, Left + Width, Top + Height); } @@ -124,14 +124,14 @@ namespace Greenshot.Editor.Drawing int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); if (lineThickness > 0) { - using Pen pen = new Pen(Color.White) + using Pen pen = new(Color.White) { Width = lineThickness }; - SetArrowHeads((ArrowHeadCombination) GetFieldValue(FieldType.ARROWHEADS), pen); - using GraphicsPath path = new GraphicsPath(); + SetArrowHeads((ArrowHeadCombination)GetFieldValue(FieldType.ARROWHEADS), pen); + using GraphicsPath path = new(); path.AddLine(Left, Top, Left + Width, Top + Height); - using Matrix matrix = new Matrix(); + using Matrix matrix = new(); NativeRect drawingBounds = Rectangle.Round(path.GetBounds(matrix, pen)); return drawingBounds.Inflate(2, 2); } @@ -145,12 +145,12 @@ namespace Greenshot.Editor.Drawing int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS) + 10; if (lineThickness > 0) { - using Pen pen = new Pen(Color.White) + using Pen pen = new(Color.White) { Width = lineThickness }; - SetArrowHeads((ArrowHeadCombination) GetFieldValue(FieldType.ARROWHEADS), pen); - using GraphicsPath path = new GraphicsPath(); + SetArrowHeads((ArrowHeadCombination)GetFieldValue(FieldType.ARROWHEADS), pen); + using GraphicsPath path = new(); path.AddLine(Left, Top, Left + Width, Top + Height); return path.IsOutlineVisible(x, y, pen); } diff --git a/src/Greenshot.Editor/Drawing/CropContainer.cs b/src/Greenshot.Editor/Drawing/CropContainer.cs index eb2f7179e..5960c63c3 100644 --- a/src/Greenshot.Editor/Drawing/CropContainer.cs +++ b/src/Greenshot.Editor/Drawing/CropContainer.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ - using System.Drawing; using System.Runtime.Serialization; using Dapplo.Windows.Common.Extensions; @@ -147,12 +146,7 @@ namespace Greenshot.Editor.Drawing { get { - if (_parent?.Image is { } image) - { - return new NativeRect(0, 0, image.Width, image.Height); - } - - return NativeRect.Empty; + return _parent?.Image is { } image ? new NativeRect(0, 0, image.Width, image.Height) : NativeRect.Empty; } } @@ -163,7 +157,6 @@ namespace Greenshot.Editor.Drawing return; } - using Brush cropBrush = new SolidBrush(Color.FromArgb(100, 150, 150, 100)); var cropRectangle = new NativeRect(Left, Top, Width, Height).Normalize(); var selectionRect = new NativeRect(cropRectangle.Left - 1, cropRectangle.Top - 1, cropRectangle.Width + 1, cropRectangle.Height + 1); @@ -195,7 +188,6 @@ namespace Greenshot.Editor.Drawing } } - } /// @@ -214,7 +206,7 @@ namespace Greenshot.Editor.Drawing _ => base.HandleMouseDown(x, y), }; } - + public override bool HandleMouseMove(int x, int y) { Invalidate(); diff --git a/src/Greenshot.Editor/Drawing/CursorContainer.cs b/src/Greenshot.Editor/Drawing/CursorContainer.cs index e8914eb75..a3bc851d7 100644 --- a/src/Greenshot.Editor/Drawing/CursorContainer.cs +++ b/src/Greenshot.Editor/Drawing/CursorContainer.cs @@ -67,10 +67,7 @@ namespace Greenshot.Editor.Drawing { set { - if (cursor != null) - { - cursor.Dispose(); - } + cursor?.Dispose(); // Clone cursor (is this correct??) cursor = new Cursor(value.CopyHandle()); @@ -89,10 +86,7 @@ namespace Greenshot.Editor.Drawing { if (disposing) { - if (cursor != null) - { - cursor.Dispose(); - } + cursor?.Dispose(); } cursor = null; @@ -106,7 +100,7 @@ namespace Greenshot.Editor.Drawing return; } - using Cursor fileCursor = new Cursor(filename); + using Cursor fileCursor = new(filename); Cursor = fileCursor; LOG.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width); } diff --git a/src/Greenshot.Editor/Drawing/DrawableContainer.cs b/src/Greenshot.Editor/Drawing/DrawableContainer.cs index cac23dc3a..f3236f25c 100644 --- a/src/Greenshot.Editor/Drawing/DrawableContainer.cs +++ b/src/Greenshot.Editor/Drawing/DrawableContainer.cs @@ -116,7 +116,7 @@ namespace Greenshot.Editor.Drawing { get { - List ret = new List(); + List ret = new(); foreach (IFieldHolder c in Children) { if (c is IFilter) @@ -165,7 +165,6 @@ namespace Greenshot.Editor.Drawing set => _status = value; } - private int left; public int Left @@ -232,7 +231,7 @@ namespace Greenshot.Editor.Drawing public NativePoint Location { - get => new NativePoint(left, top); + get => new(left, top); set { left = value.X; @@ -242,7 +241,7 @@ namespace Greenshot.Editor.Drawing public NativeSize Size { - get => new NativeSize(width, height); + get => new(width, height); set { width = value.Width; @@ -285,7 +284,7 @@ namespace Greenshot.Editor.Drawing Height = Round(newBounds.Height); } - public DrawableContainer(ISurface parent) + protected DrawableContainer(ISurface parent) { InitializeFields(); _parent = parent; @@ -304,8 +303,7 @@ namespace Greenshot.Editor.Drawing private static int Round(float f) { if (float.IsPositiveInfinity(f) || f > int.MaxValue / 2) return int.MaxValue / 2; - if (float.IsNegativeInfinity(f) || f < int.MinValue / 2) return int.MinValue / 2; - return (int) Math.Round(f); + return float.IsNegativeInfinity(f) || f < int.MinValue / 2 ? int.MinValue / 2 : (int)Math.Round(f); } private bool accountForShadowChange; @@ -470,7 +468,7 @@ namespace Greenshot.Editor.Drawing protected void DrawSelectionBorder(Graphics g, NativeRect rect) { - using Pen pen = new Pen(Color.MediumSeaGreen) + using Pen pen = new(Color.MediumSeaGreen) { DashPattern = new float[] { @@ -515,7 +513,7 @@ namespace Greenshot.Editor.Drawing public virtual bool HandleMouseDown(int x, int y) { _boundsBeforeResize = Bounds.MoveTo(x, y); - Left = x; + Left = x; Top = y; return true; } @@ -635,7 +633,7 @@ namespace Greenshot.Editor.Drawing const int M11 = 0; const int M21 = 2; var radians = Math.Atan2(matrix.Elements[M21], matrix.Elements[M11]); - return (int) -Math.Round(radians * 180 / Math.PI); + return (int)-Math.Round(radians * 180 / Math.PI); } /// @@ -653,8 +651,8 @@ namespace Greenshot.Editor.Drawing return; } - Point topLeft = new Point(Left, Top); - Point bottomRight = new Point(Left + Width, Top + Height); + Point topLeft = new(Left, Top); + Point bottomRight = new(Left + Width, Top + Height); Point[] points = new[] { topLeft, bottomRight diff --git a/src/Greenshot.Editor/Drawing/DrawableContainerList.cs b/src/Greenshot.Editor/Drawing/DrawableContainerList.cs index ef30c037f..c1a06a50a 100644 --- a/src/Greenshot.Editor/Drawing/DrawableContainerList.cs +++ b/src/Greenshot.Editor/Drawing/DrawableContainerList.cs @@ -77,7 +77,7 @@ namespace Greenshot.Editor.Drawing public List AsIDrawableContainerList() { - List interfaceList = new List(); + List interfaceList = new(); foreach (IDrawableContainer container in this) { interfaceList.Add(container); @@ -119,19 +119,14 @@ namespace Greenshot.Editor.Drawing { get { - if (Count > 0) - { - return this[Count - 1].Parent; - } - - return null; + return Count > 0 ? this[Count - 1].Parent : null; } set { ParentID = value?.ID ?? Guid.NewGuid(); foreach (var drawableContainer in this) { - var dc = (DrawableContainer) drawableContainer; + var dc = (DrawableContainer)drawableContainer; dc.Parent = value; } } @@ -146,7 +141,7 @@ namespace Greenshot.Editor.Drawing if (Count <= 0 || Parent == null) return; // Take all containers to make undoable var containersToClone = this.Where(c => c.IsUndoable).ToList(); - if (!containersToClone.Any()) + if (containersToClone.Count == 0) { return; } @@ -250,7 +245,7 @@ namespace Greenshot.Editor.Drawing { foreach (var drawableContainer in this) { - var dc = (DrawableContainer) drawableContainer; + var dc = (DrawableContainer)drawableContainer; dc.OnDoubleClick(); } } @@ -330,7 +325,7 @@ namespace Greenshot.Editor.Drawing foreach (var drawableContainer in this) { - var dc = (DrawableContainer) drawableContainer; + var dc = (DrawableContainer)drawableContainer; if (dc.Parent == null) { continue; @@ -352,7 +347,7 @@ namespace Greenshot.Editor.Drawing { foreach (var drawableContainer in this) { - var dc = (DrawableContainer) drawableContainer; + var dc = (DrawableContainer)drawableContainer; dc.HandleFieldChanged(sender, e); } } @@ -377,7 +372,7 @@ namespace Greenshot.Editor.Drawing } /// - /// Indicates whether the given list of elements can be pulled up, + /// Indicates whether the given list of elements can be pulled up, /// i.e. whether there is at least one unselected element higher in hierarchy /// /// list of elements to pull up @@ -443,70 +438,70 @@ namespace Greenshot.Editor.Drawing public void SetForegroundColor(Color color) { - var dcs = ToArray(); - var field = FieldType.LINE_COLOR; - foreach (var dc in dcs) - { - if (dc is not AbstractFieldHolderWithChildren fh) continue; - if (!fh.HasField(field)) continue; - - fh.SetFieldValue(field, color); - } + var dcs = ToArray(); + var field = FieldType.LINE_COLOR; + foreach (var dc in dcs) + { + if (dc is not AbstractFieldHolderWithChildren fh) continue; + if (!fh.HasField(field)) continue; + + fh.SetFieldValue(field, color); + } } public void SetBackgroundColor(Color color) { - var dcs = ToArray(); - var field = FieldType.FILL_COLOR; - foreach (var dc in dcs) - { - if (dc is not AbstractFieldHolderWithChildren fh) continue; - if (!fh.HasField(field)) continue; + var dcs = ToArray(); + var field = FieldType.FILL_COLOR; + foreach (var dc in dcs) + { + if (dc is not AbstractFieldHolderWithChildren fh) continue; + if (!fh.HasField(field)) continue; - fh.SetFieldValue(field, color); - } + fh.SetFieldValue(field, color); + } } public int IncreaseLineThickness(int increaseBy) { - var dcs = ToArray(); - var field = FieldType.LINE_THICKNESS; - var lastThickness = 0; - foreach (var dc in dcs) - { - if (dc is not AbstractFieldHolderWithChildren fh) continue; - if (!fh.HasField(field)) continue; + var dcs = ToArray(); + var field = FieldType.LINE_THICKNESS; + var lastThickness = 0; + foreach (var dc in dcs) + { + if (dc is not AbstractFieldHolderWithChildren fh) continue; + if (!fh.HasField(field)) continue; - var currentThickness = (int)fh.GetFieldValue(field); - var thickness = Math.Max(0, currentThickness + increaseBy); - fh.SetFieldValue(field, thickness); - lastThickness = thickness; - } + var currentThickness = (int)fh.GetFieldValue(field); + var thickness = Math.Max(0, currentThickness + increaseBy); + fh.SetFieldValue(field, thickness); + lastThickness = thickness; + } - return lastThickness; + return lastThickness; } public bool FlipShadow() { - var dcs = ToArray(); - var field = FieldType.SHADOW; - var lastShadow = false; - foreach (var dc in dcs) - { - if (dc is not AbstractFieldHolderWithChildren fh) continue; - if (!fh.HasField(field)) continue; + var dcs = ToArray(); + var field = FieldType.SHADOW; + var lastShadow = false; + foreach (var dc in dcs) + { + if (dc is not AbstractFieldHolderWithChildren fh) continue; + if (!fh.HasField(field)) continue; - var currentShadow = (bool)fh.GetFieldValue(field); - var shadow = !currentShadow; - fh.SetFieldValue(field, shadow); - lastShadow = shadow; - } + var currentShadow = (bool)fh.GetFieldValue(field); + var shadow = !currentShadow; + fh.SetFieldValue(field, shadow); + lastShadow = shadow; + } - return lastShadow; + return lastShadow; } /// - /// Indicates whether the given list of elements can be pushed down, + /// Indicates whether the given list of elements can be pushed down, /// i.e. whether there is at least one unselected element lower in hierarchy /// /// list of elements to push down @@ -572,7 +567,7 @@ namespace Greenshot.Editor.Drawing } /// - /// swaps two elements in hierarchy (z-index), + /// swaps two elements in hierarchy (z-index), /// checks both indices to be in range /// /// index of the 1st element @@ -655,7 +650,7 @@ namespace Greenshot.Editor.Drawing // Copy item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)) { - Image = (Image) EditorFormResources.GetObject("copyToolStripMenuItem.Image") + Image = (Image)EditorFormResources.GetObject("copyToolStripMenuItem.Image") }; item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this); }; menu.Items.Add(item); @@ -663,7 +658,7 @@ namespace Greenshot.Editor.Drawing // Cut item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)) { - Image = (Image) EditorFormResources.GetObject("btnCut.Image") + Image = (Image)EditorFormResources.GetObject("btnCut.Image") }; item.Click += delegate { @@ -675,7 +670,7 @@ namespace Greenshot.Editor.Drawing // Delete item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement)) { - Image = (Image) EditorFormResources.GetObject("removeObjectToolStripMenuItem.Image") + Image = (Image)EditorFormResources.GetObject("removeObjectToolStripMenuItem.Image") }; item.Click += delegate { surface.RemoveElements(this); }; menu.Items.Add(item); @@ -692,7 +687,7 @@ namespace Greenshot.Editor.Drawing MakeBoundsChangeUndoable(false); foreach (var drawableContainer in this) { - var container = (DrawableContainer) drawableContainer; + var container = (DrawableContainer)drawableContainer; if (!container.HasDefaultSize) { continue; @@ -726,8 +721,8 @@ namespace Greenshot.Editor.Drawing bool hasMenu = this.Cast().Any(container => container.HasContextMenu); if (!hasMenu) return; - - ContextMenuStrip menu = new ContextMenuStrip(); + + ContextMenuStrip menu = new(); AddContextMenuItems(menu, surface, mouseEventArgs); if (menu.Items.Count <= 0) return; menu.Show(surface, surface.ToSurfaceCoordinates(mouseEventArgs.Location)); diff --git a/src/Greenshot.Editor/Drawing/EllipseContainer.cs b/src/Greenshot.Editor/Drawing/EllipseContainer.cs index c421515d9..5b4816678 100644 --- a/src/Greenshot.Editor/Drawing/EllipseContainer.cs +++ b/src/Greenshot.Editor/Drawing/EllipseContainer.cs @@ -93,13 +93,13 @@ namespace Greenshot.Editor.Drawing // draw shadow before anything else if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { - int basealpha = 100; + const int basealpha = 100; int alpha = basealpha; - int steps = 5; + const int steps = 5; int currentStep = lineVisible ? 1 : 0; while (currentStep <= steps) { - using Pen shadowPen = new Pen(Color.FromArgb(alpha, 100, 100, 100)) + using Pen shadowPen = new(Color.FromArgb(alpha, 100, 100, 100)) { Width = lineVisible ? lineThickness : 1 }; @@ -119,7 +119,7 @@ namespace Greenshot.Editor.Drawing if (lineVisible) { - using Pen pen = new Pen(lineColor, lineThickness); + using Pen pen = new(lineColor, lineThickness); graphics.DrawEllipse(pen, rect); } } @@ -138,10 +138,10 @@ namespace Greenshot.Editor.Drawing /// public static bool EllipseContains(DrawableContainer caller, int x, int y) { - double xDistanceFromCenter = x - (caller.Left + caller.Width / 2); - double yDistanceFromCenter = y - (caller.Top + caller.Height / 2); + 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 / 2, 2)) + (Math.Pow(yDistanceFromCenter, 2) / Math.Pow(caller.Height / 2, 2)) < 1; } public override bool ClickableAt(int x, int y) @@ -166,8 +166,8 @@ namespace Greenshot.Editor.Drawing // check the rest of the lines if (lineThickness > 0) { - using Pen pen = new Pen(Color.White, lineThickness); - using GraphicsPath path = new GraphicsPath(); + using Pen pen = new(Color.White, lineThickness); + using GraphicsPath path = new(); path.AddEllipse(rect); return path.IsOutlineVisible(x, y, pen); } diff --git a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs index a3f3c92da..1bcc6c68b 100644 --- a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs +++ b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs @@ -109,7 +109,6 @@ namespace Greenshot.Editor.Drawing.Fields return fields; } - public IField GetField(IFieldType fieldType) { try @@ -159,7 +158,7 @@ namespace Greenshot.Editor.Drawing.Fields public Color GetFieldValueAsColor(IFieldType fieldType, Color defaultColor = default) { - return (Color) (GetFieldValue(fieldType) ?? defaultColor); + return (Color)(GetFieldValue(fieldType) ?? defaultColor); } public bool HasField(IFieldType fieldType) diff --git a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs index 968edef46..6116ad3cb 100644 --- a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -46,7 +46,7 @@ namespace Greenshot.Editor.Drawing.Fields public IList Children = new List(); - public AbstractFieldHolderWithChildren() + protected AbstractFieldHolderWithChildren() { _fieldChangedEventHandler = OnFieldChanged; } @@ -108,12 +108,7 @@ namespace Greenshot.Editor.Drawing.Fields } } - if (ret == null) - { - throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType()); - } - - return ret; + return ret ?? throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType()); } public new bool HasField(IFieldType fieldType) @@ -137,7 +132,7 @@ namespace Greenshot.Editor.Drawing.Fields public new bool HasFieldValue(IFieldType fieldType) { IField f = GetField(fieldType); - return f != null && f.HasValue; + return f?.HasValue == true; } public new void SetFieldValue(IFieldType fieldType, object value) diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs index 0a993f766..3cd8b0f3b 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs @@ -30,22 +30,12 @@ namespace Greenshot.Editor.Drawing.Fields.Binding { public object convert(object o) { - if (o == null) + return o switch { - return null; - } - - if (o is T1) - { - return convert((T1) o); - } - - if (o is T2) - { - return convert((T2) o); - } - - 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); diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs index 8dc390080..ac14baede 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs @@ -38,7 +38,6 @@ namespace Greenshot.Editor.Drawing.Fields.Binding private readonly string _fieldPropertyName; private bool _updatingControl; private bool _updatingField; - private IBindingConverter _converter; private readonly IBindingValidator _validator; /// @@ -75,7 +74,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) { - _converter = converter; + Converter = converter; } /// @@ -134,17 +133,17 @@ namespace Greenshot.Editor.Drawing.Fields.Binding PropertyInfo targetPropertyInfo = ResolvePropertyInfo(targetObject, targetProperty); PropertyInfo sourcePropertyInfo = ResolvePropertyInfo(sourceObject, sourceProperty); - if (sourcePropertyInfo != null && targetPropertyInfo != null && targetPropertyInfo.CanWrite) + if (sourcePropertyInfo != null && targetPropertyInfo?.CanWrite == true) { object bValue = sourcePropertyInfo.GetValue(sourceObject, null); - if (_converter != null && bValue != null) + if (Converter != null && bValue != null) { - bValue = _converter.convert(bValue); + bValue = Converter.convert(bValue); } try { - if (_validator == null || _validator.validate(bValue)) + if (_validator?.validate(bValue) != false) { targetPropertyInfo.SetValue(targetObject, bValue, null); } @@ -166,7 +165,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding { string prop = properties[i]; ret = obj.GetType().GetProperty(prop); - if (ret != null && ret.CanRead && i < prop.Length - 1) + if (ret?.CanRead == true && i < prop.Length - 1) { obj = ret.GetValue(obj, null); } @@ -175,10 +174,6 @@ namespace Greenshot.Editor.Drawing.Fields.Binding return ret; } - public IBindingConverter Converter - { - get { return _converter; } - set { _converter = value; } - } + public IBindingConverter Converter { get; set; } } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/Field.cs b/src/Greenshot.Editor/Drawing/Fields/Field.cs index c3870c54c..2d31f47e8 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Field.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Field.cs @@ -112,12 +112,7 @@ namespace Greenshot.Editor.Drawing.Fields public override bool Equals(object obj) { - if (!(obj is Field other)) - { - return false; - } - - return FieldType == other.FieldType && Equals(Scope, other.Scope); + return obj is Field other && FieldType == other.FieldType && Equals(Scope, other.Scope); } public override string ToString() diff --git a/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs b/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs index 96a19b7b9..045312a42 100644 --- a/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs +++ b/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs @@ -79,7 +79,7 @@ namespace Greenshot.Editor.Drawing.Fields public void BindElement(IDrawableContainer dc) { - if (!(dc is DrawableContainer container) || _boundContainers.Contains(container)) + if (dc is not DrawableContainer container || _boundContainers.Contains(container)) { return; } @@ -97,7 +97,7 @@ namespace Greenshot.Editor.Drawing.Fields public void UpdateElement(IDrawableContainer dc) { - if (!(dc is DrawableContainer container)) + if (dc is not DrawableContainer container) { return; } @@ -172,7 +172,7 @@ namespace Greenshot.Editor.Drawing.Fields returnFields = leastSelectedContainer.GetFields(); for (int i = 0; i < _boundContainers.Count - 1; i++) { - if (!(_boundContainers[i] is DrawableContainer dc)) continue; + if (_boundContainers[i] is not DrawableContainer dc) continue; IList fieldsToRemove = new List(); foreach (IField field in returnFields) { @@ -196,7 +196,7 @@ namespace Greenshot.Editor.Drawing.Fields public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea) { - IField field = (IField) sender; + IField field = (IField)sender; if (_internalUpdateRunning || field.Value == null) { return; @@ -204,7 +204,7 @@ namespace Greenshot.Editor.Drawing.Fields foreach (var drawableContainer1 in _boundContainers.ToList()) { - var drawableContainer = (DrawableContainer) drawableContainer1; + var drawableContainer = (DrawableContainer)drawableContainer1; if (!drawableContainer.HasField(field.FieldType)) { continue; diff --git a/src/Greenshot.Editor/Drawing/Fields/FieldType.cs b/src/Greenshot.Editor/Drawing/Fields/FieldType.cs index eead7452a..9983e2e4a 100644 --- a/src/Greenshot.Editor/Drawing/Fields/FieldType.cs +++ b/src/Greenshot.Editor/Drawing/Fields/FieldType.cs @@ -53,7 +53,6 @@ namespace Greenshot.Editor.Drawing.Fields public static readonly IFieldType FLAGS = new FieldType(nameof(FLAGS)); public static readonly IFieldType CROPMODE = new FieldType(nameof(CROPMODE)); - public static IFieldType[] Values = { ARROWHEADS, BLUR_RADIUS, BRIGHTNESS, FILL_COLOR, FONT_BOLD, FONT_FAMILY, FONT_ITALIC, FONT_SIZE, TEXT_HORIZONTAL_ALIGNMENT, TEXT_VERTICAL_ALIGNMENT, HIGHLIGHT_COLOR, @@ -87,12 +86,7 @@ namespace Greenshot.Editor.Drawing.Fields public override bool Equals(object obj) { FieldType other = obj as FieldType; - if (other == null) - { - return false; - } - - return Equals(Name, other.Name); + return other != null && Equals(Name, other.Name); } public static bool operator ==(FieldType a, FieldType b) diff --git a/src/Greenshot.Editor/Drawing/FilterContainer.cs b/src/Greenshot.Editor/Drawing/FilterContainer.cs index 4b846fe66..3a4a7395a 100644 --- a/src/Greenshot.Editor/Drawing/FilterContainer.cs +++ b/src/Greenshot.Editor/Drawing/FilterContainer.cs @@ -54,7 +54,7 @@ namespace Greenshot.Editor.Drawing MAGNIFICATION }; - public FilterContainer(ISurface parent) : base(parent) + protected FilterContainer(ISurface parent) : base(parent) { Init(); } @@ -92,13 +92,13 @@ namespace Greenshot.Editor.Drawing //draw shadow first if (shadow) { - int basealpha = 100; + const int basealpha = 100; int alpha = basealpha; - int steps = 5; + const int steps = 5; int currentStep = lineVisible ? 1 : 0; while (currentStep <= steps) { - using Pen shadowPen = new Pen(Color.FromArgb(alpha, 100, 100, 100), lineThickness); + using Pen shadowPen = new(Color.FromArgb(alpha, 100, 100, 100), lineThickness); var shadowRect = new NativeRect(Left + currentStep, Top + currentStep, Width, Height).Normalize(); graphics.DrawRectangle(shadowPen, shadowRect); currentStep++; @@ -109,7 +109,7 @@ namespace Greenshot.Editor.Drawing if (lineThickness > 0) { var rect = new NativeRect(Left, Top, Width, Height).Normalize(); - using Pen pen = new Pen(lineColor, lineThickness); + using Pen pen = new(lineColor, lineThickness); graphics.DrawRectangle(pen, rect); } } diff --git a/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs b/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs index c972ed77d..334a7c1af 100644 --- a/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs @@ -64,7 +64,7 @@ namespace Greenshot.Editor.Drawing.Filters set { parent = value; } } - public AbstractFilter(DrawableContainer parent) + protected AbstractFilter(DrawableContainer parent) { this.parent = parent; } diff --git a/src/Greenshot.Editor/Drawing/Filters/GrayscaleFilter.cs b/src/Greenshot.Editor/Drawing/Filters/GrayscaleFilter.cs index 441102980..09463eb6a 100644 --- a/src/Greenshot.Editor/Drawing/Filters/GrayscaleFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/GrayscaleFilter.cs @@ -56,7 +56,7 @@ namespace Greenshot.Editor.Drawing.Filters graphics.ExcludeClip(rect); } - ColorMatrix grayscaleMatrix = new ColorMatrix(new[] + ColorMatrix grayscaleMatrix = new(new[] { new[] { @@ -79,7 +79,7 @@ namespace Greenshot.Editor.Drawing.Filters 0, 0, 0, 0, 1 } }); - using (ImageAttributes ia = new ImageAttributes()) + using (ImageAttributes ia = new()) { ia.SetColorMatrix(grayscaleMatrix); graphics.DrawImage(applyBitmap, applyRect, applyRect.X, applyRect.Y, applyRect.Width, applyRect.Height, GraphicsUnit.Pixel, ia); diff --git a/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs b/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs index 70d829a2e..47a8e3a58 100644 --- a/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs @@ -66,7 +66,7 @@ namespace Greenshot.Editor.Drawing.Filters int halfHeight = rect.Height / 2; int newWidth = rect.Width / magnificationFactor; int newHeight = rect.Height / magnificationFactor; - var source = new NativeRect(rect.X + halfWidth - newWidth / 2, rect.Y + halfHeight - newHeight / 2, newWidth, newHeight); + var source = new NativeRect(rect.X + halfWidth - (newWidth / 2), rect.Y + halfHeight - (newHeight / 2), newWidth, newHeight); graphics.DrawImage(applyBitmap, rect, source, GraphicsUnit.Pixel); graphics.Restore(state); } diff --git a/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs b/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs index fa677b128..97604e995 100644 --- a/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs @@ -64,7 +64,7 @@ namespace Greenshot.Editor.Drawing.Filters using IFastBitmap dest = FastBitmap.CreateCloneOf(applyBitmap, rect); using (IFastBitmap src = FastBitmap.Create(applyBitmap, rect)) { - List colors = new List(); + List colors = new(); int halbPixelSize = pixelSize / 2; for (int y = src.Top - halbPixelSize; y < src.Bottom + halbPixelSize; y += pixelSize) { diff --git a/src/Greenshot.Editor/Drawing/FreehandContainer.cs b/src/Greenshot.Editor/Drawing/FreehandContainer.cs index b8a66be4e..bae2025d5 100644 --- a/src/Greenshot.Editor/Drawing/FreehandContainer.cs +++ b/src/Greenshot.Editor/Drawing/FreehandContainer.cs @@ -43,10 +43,10 @@ namespace Greenshot.Editor.Drawing 0.5f, 0.25f, 0.75f }; - [NonSerialized] private GraphicsPath freehandPath = new GraphicsPath(); + [NonSerialized] private GraphicsPath freehandPath = new(); private NativeRect myBounds = NativeRect.Empty; private NativePoint lastMouse = NativePoint.Empty; - private readonly List capturePoints = new List(); + private readonly List capturePoints = new(); private bool isRecalculated; /// @@ -165,7 +165,7 @@ namespace Greenshot.Editor.Drawing while ((capturePoints.Count - 1) % 3 != 0) { // duplicate points, first at 50% than 25% than 75% - capturePoints.Insert((int) (capturePoints.Count * PointOffset[index]), capturePoints[(int) (capturePoints.Count * PointOffset[index++])]); + capturePoints.Insert((int)(capturePoints.Count * PointOffset[index]), capturePoints[(int)(capturePoints.Count * PointOffset[index++])]); } newFreehandPath.AddBeziers(capturePoints.ToArray()); @@ -239,8 +239,8 @@ namespace Greenshot.Editor.Drawing /// GraphicsPath protected static void DrawSelectionBorder(Graphics graphics, Pen linePen, GraphicsPath path) { - using var selectionPen = (Pen) linePen.Clone(); - using var selectionPath = (GraphicsPath) path.Clone(); + using var selectionPen = (Pen)linePen.Clone(); + using var selectionPath = (GraphicsPath)path.Clone(); selectionPen.Width += 5; selectionPen.Color = Color.FromArgb(120, Color.LightSeaGreen); graphics.DrawPath(selectionPen, selectionPath); @@ -264,17 +264,12 @@ namespace Greenshot.Editor.Drawing if (!myBounds.IsEmpty) { int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS)); - int safetyMargin = 10; + const int safetyMargin = 10; return new NativeRect(myBounds.Left + Left - (safetyMargin + lineThickness), myBounds.Top + Top - (safetyMargin + lineThickness), - myBounds.Width + 2 * (lineThickness + safetyMargin), myBounds.Height + 2 * (lineThickness + safetyMargin)); + myBounds.Width + (2 * (lineThickness + safetyMargin)), myBounds.Height + (2 * (lineThickness + safetyMargin))); } - if (_parent?.Image is Image image) - { - return new NativeRect(0, 0, image.Width, image.Height); - } - - return NativeRect.Empty; + return _parent?.Image is Image image ? new NativeRect(0, 0, image.Width, image.Height) : NativeRect.Empty; } } diff --git a/src/Greenshot.Editor/Drawing/HighlightContainer.cs b/src/Greenshot.Editor/Drawing/HighlightContainer.cs index 58cf792ba..62994bd87 100644 --- a/src/Greenshot.Editor/Drawing/HighlightContainer.cs +++ b/src/Greenshot.Editor/Drawing/HighlightContainer.cs @@ -75,7 +75,7 @@ namespace Greenshot.Editor.Drawing private void ConfigurePreparedFilters() { - PreparedFilter preset = (PreparedFilter) GetFieldValue(FieldType.PREPARED_FILTER_HIGHLIGHT); + PreparedFilter preset = (PreparedFilter)GetFieldValue(FieldType.PREPARED_FILTER_HIGHLIGHT); while (Filters.Count > 0) { Remove(Filters[0]); diff --git a/src/Greenshot.Editor/Drawing/IconContainer.cs b/src/Greenshot.Editor/Drawing/IconContainer.cs index 185c17cd2..6ef6d49df 100644 --- a/src/Greenshot.Editor/Drawing/IconContainer.cs +++ b/src/Greenshot.Editor/Drawing/IconContainer.cs @@ -72,7 +72,7 @@ namespace Greenshot.Editor.Drawing set { icon?.Dispose(); - icon = (Icon) value.Clone(); + icon = (Icon)value.Clone(); Width = value.Width; Height = value.Height; } @@ -101,7 +101,7 @@ namespace Greenshot.Editor.Drawing return; } - using Icon fileIcon = new Icon(filename); + using Icon fileIcon = new(filename); Icon = fileIcon; Log.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width); } @@ -113,7 +113,7 @@ namespace Greenshot.Editor.Drawing return; } - using Icon fileIcon = new Icon(iconStream); + using Icon fileIcon = new(iconStream); Icon = fileIcon; Log.Debug("Loaded stream: with resolution: " + Height + "," + Width); } diff --git a/src/Greenshot.Editor/Drawing/ImageContainer.cs b/src/Greenshot.Editor/Drawing/ImageContainer.cs index 21f8d2fa6..089c9a54e 100644 --- a/src/Greenshot.Editor/Drawing/ImageContainer.cs +++ b/src/Greenshot.Editor/Drawing/ImageContainer.cs @@ -54,7 +54,7 @@ namespace Greenshot.Editor.Drawing /// This is the offset for the shadow version of the bitmap /// Do not serialize, as the offset is recreated /// - [NonSerialized] private NativePoint _shadowOffset = new NativePoint(-1, -1); + [NonSerialized] private readonly NativePoint _shadowOffset = new(-1, -1); public ImageContainer(ISurface parent, string filename) : this(parent) { @@ -174,7 +174,6 @@ namespace Greenshot.Editor.Drawing _shadowBitmap = null; } - /// /// Make sure the content is also transformed. /// diff --git a/src/Greenshot.Editor/Drawing/LineContainer.cs b/src/Greenshot.Editor/Drawing/LineContainer.cs index f48dddec7..d9f03abbf 100644 --- a/src/Greenshot.Editor/Drawing/LineContainer.cs +++ b/src/Greenshot.Editor/Drawing/LineContainer.cs @@ -62,7 +62,6 @@ namespace Greenshot.Editor.Drawing public override void Draw(Graphics graphics, RenderMode rm) { - int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); if (lineThickness <= 0) return; @@ -75,13 +74,13 @@ namespace Greenshot.Editor.Drawing if (shadow) { //draw shadow first - int basealpha = 100; + const int basealpha = 100; int alpha = basealpha; - int steps = 5; + const int steps = 5; int currentStep = 1; while (currentStep <= steps) { - using Pen shadowCapPen = new Pen(Color.FromArgb(alpha, 100, 100, 100), lineThickness); + using Pen shadowCapPen = new(Color.FromArgb(alpha, 100, 100, 100), lineThickness); graphics.DrawLine(shadowCapPen, Left + currentStep, Top + currentStep, @@ -94,7 +93,7 @@ namespace Greenshot.Editor.Drawing } Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); - using Pen pen = new Pen(lineColor, lineThickness); + using Pen pen = new(lineColor, lineThickness); graphics.DrawLine(pen, Left, Top, Left + Width, Top + Height); } @@ -103,11 +102,11 @@ namespace Greenshot.Editor.Drawing int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS) + 5; if (lineThickness > 0) { - using Pen pen = new Pen(Color.White) + using Pen pen = new(Color.White) { Width = lineThickness }; - using GraphicsPath path = new GraphicsPath(); + using GraphicsPath path = new(); path.AddLine(Left, Top, Left + Width, Top + Height); return path.IsOutlineVisible(x, y, pen); } diff --git a/src/Greenshot.Editor/Drawing/MetafileContainer.cs b/src/Greenshot.Editor/Drawing/MetafileContainer.cs index 3225c4700..817437ad1 100644 --- a/src/Greenshot.Editor/Drawing/MetafileContainer.cs +++ b/src/Greenshot.Editor/Drawing/MetafileContainer.cs @@ -40,13 +40,13 @@ namespace Greenshot.Editor.Drawing public MetafileContainer(Metafile metafile, ISurface parent) : base(parent) { _metafile = metafile; - Size = new NativeSize(metafile.Width/4, metafile.Height/4); + Size = new NativeSize(metafile.Width / 4, metafile.Height / 4); } - + protected override Image ComputeBitmap() { var image = ImageHelper.CreateEmpty(Width, Height, PixelFormat.Format32bppArgb, Color.Transparent); - + var dstRect = new NativeRect(0, 0, Width, Height); using (Graphics graphics = Graphics.FromImage(image)) { @@ -56,7 +56,7 @@ namespace Greenshot.Editor.Drawing graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.DrawImage(_metafile, dstRect); } - + if (RotationAngle == 0) return image; var newImage = image.Rotate(RotationAngle); @@ -70,12 +70,12 @@ namespace Greenshot.Editor.Drawing { _metafile?.Dispose(); } - + base.Dispose(disposing); } public override bool HasDefaultSize => true; - public override NativeSize DefaultSize => new NativeSize(_metafile.Width, _metafile.Height); + public override NativeSize DefaultSize => new(_metafile.Width, _metafile.Height); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs b/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs index b0c890ffc..453735457 100644 --- a/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs +++ b/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs @@ -70,7 +70,7 @@ namespace Greenshot.Editor.Drawing private void ConfigurePreparedFilters() { - PreparedFilter preset = (PreparedFilter) GetFieldValue(FieldType.PREPARED_FILTER_OBFUSCATE); + PreparedFilter preset = (PreparedFilter)GetFieldValue(FieldType.PREPARED_FILTER_OBFUSCATE); while (Filters.Count > 0) { Remove(Filters[0]); diff --git a/src/Greenshot.Editor/Drawing/Positions.cs b/src/Greenshot.Editor/Drawing/Positions.cs index 863690887..815876255 100644 --- a/src/Greenshot.Editor/Drawing/Positions.cs +++ b/src/Greenshot.Editor/Drawing/Positions.cs @@ -22,7 +22,7 @@ namespace Greenshot.Editor.Drawing { /// - /// Position + /// Position /// public enum Positions : int { diff --git a/src/Greenshot.Editor/Drawing/RectangleContainer.cs b/src/Greenshot.Editor/Drawing/RectangleContainer.cs index 717e1a593..14faa69c2 100644 --- a/src/Greenshot.Editor/Drawing/RectangleContainer.cs +++ b/src/Greenshot.Editor/Drawing/RectangleContainer.cs @@ -98,13 +98,13 @@ namespace Greenshot.Editor.Drawing if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { //draw shadow first - int basealpha = 100; + const int basealpha = 100; int alpha = basealpha; - int steps = 5; + const int steps = 5; int currentStep = lineVisible ? 1 : 0; while (currentStep <= steps) { - using Pen shadowPen = new Pen(Color.FromArgb(alpha, 100, 100, 100)) + using Pen shadowPen = new(Color.FromArgb(alpha, 100, 100, 100)) { Width = lineVisible ? lineThickness : 1 }; @@ -119,7 +119,6 @@ namespace Greenshot.Editor.Drawing } } - if (Colors.IsVisible(fillColor)) { using Brush brush = new SolidBrush(fillColor); @@ -129,7 +128,7 @@ namespace Greenshot.Editor.Drawing graphics.SmoothingMode = SmoothingMode.HighSpeed; if (lineVisible) { - using Pen pen = new Pen(lineColor, lineThickness); + using Pen pen = new(lineColor, lineThickness); graphics.DrawRectangle(pen, rect); } } @@ -157,8 +156,8 @@ namespace Greenshot.Editor.Drawing // check the rest of the lines if (lineThickness > 0) { - using Pen pen = new Pen(Color.White, lineThickness); - using GraphicsPath path = new GraphicsPath(); + using Pen pen = new(Color.White, lineThickness); + using GraphicsPath path = new(); path.AddRectangle(rect); return path.IsOutlineVisible(x, y, pen); } diff --git a/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs b/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs index 22dd13379..477985a0a 100644 --- a/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs +++ b/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs @@ -144,10 +144,10 @@ namespace Greenshot.Editor.Drawing int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); bool shadow = GetFieldValueAsBool(FieldType.SHADOW); - using Pen pen = new Pen(lineColor, lineThickness); + using Pen pen = new(lineColor, lineThickness); int inflateValue = lineThickness + 2 + (shadow ? 6 : 0); using GraphicsPath tailPath = CreateTail(); - + var bubbleBounds = new NativeRect(Left, Top, Width, Height).Normalize(); using var matrix = new Matrix(); @@ -155,7 +155,6 @@ namespace Greenshot.Editor.Drawing var drawingBoundsWithoutSafety = bubbleBounds.Union(tailBounds); return drawingBoundsWithoutSafety.Inflate(inflateValue, inflateValue); - } } @@ -166,13 +165,13 @@ namespace Greenshot.Editor.Drawing /// private GraphicsPath CreateBubble(int lineThickness) { - GraphicsPath bubble = new GraphicsPath(); + GraphicsPath bubble = new(); var rect = new NativeRect(Left, Top, Width, Height).Normalize(); var bubbleRect = new NativeRect(0, 0, rect.Width, rect.Height).Normalize(); // adapt corner radius to small rectangle dimensions int smallerSideLength = Math.Min(bubbleRect.Width, bubbleRect.Height); - int cornerRadius = Math.Min(30, smallerSideLength / 2 - lineThickness); + int cornerRadius = Math.Min(30, (smallerSideLength / 2) - lineThickness); if (cornerRadius > 0) { bubble.AddArc(bubbleRect.X, bubbleRect.Y, cornerRadius, cornerRadius, 180, 90); @@ -186,7 +185,7 @@ namespace Greenshot.Editor.Drawing } bubble.CloseAllFigures(); - using (Matrix bubbleMatrix = new Matrix()) + using (Matrix bubbleMatrix = new()) { bubbleMatrix.Translate(rect.Left, rect.Top); bubble.Transform(bubbleMatrix); @@ -210,16 +209,16 @@ namespace Greenshot.Editor.Drawing tailWidth = Math.Min(Math.Abs(rect.Width) / 2, tailWidth); tailWidth = Math.Min(Math.Abs(rect.Height) / 2, tailWidth); - GraphicsPath tail = new GraphicsPath(); + GraphicsPath tail = new(); tail.AddLine(-tailWidth, 0, tailWidth, 0); tail.AddLine(tailWidth, 0, 0, -tailLength); tail.CloseFigure(); - int tailAngle = 90 + (int) GeometryHelper.Angle2D(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2, TargetAdorner.Location.X, TargetAdorner.Location.Y); + int tailAngle = 90 + (int)GeometryHelper.Angle2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetAdorner.Location.X, TargetAdorner.Location.Y); - using (Matrix tailMatrix = new Matrix()) + using (Matrix tailMatrix = new()) { - tailMatrix.Translate(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2); + tailMatrix.Translate(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2)); tailMatrix.Rotate(tailAngle); tail.Transform(tailMatrix); } @@ -269,13 +268,13 @@ namespace Greenshot.Editor.Drawing int alpha = basealpha; const int steps = 5; int currentStep = lineVisible ? 1 : 0; - using Matrix shadowMatrix = new Matrix(); - using GraphicsPath bubbleClone = (GraphicsPath) bubble.Clone(); - using GraphicsPath tailClone = (GraphicsPath) tail.Clone(); + using Matrix shadowMatrix = new(); + using GraphicsPath bubbleClone = (GraphicsPath)bubble.Clone(); + using GraphicsPath tailClone = (GraphicsPath)tail.Clone(); shadowMatrix.Translate(1, 1); while (currentStep <= steps) { - using (Pen shadowPen = new Pen(Color.FromArgb(alpha, 100, 100, 100))) + using (Pen shadowPen = new(Color.FromArgb(alpha, 100, 100, 100))) { shadowPen.Width = lineVisible ? lineThickness : 1; tailClone.Transform(shadowMatrix); @@ -291,10 +290,10 @@ namespace Greenshot.Editor.Drawing GraphicsState state = graphics.Save(); // draw the tail border where the bubble is not visible - using (Region clipRegion = new Region(bubble)) + using (Region clipRegion = new(bubble)) { graphics.SetClip(clipRegion, CombineMode.Exclude); - using Pen pen = new Pen(lineColor, lineThickness); + using Pen pen = new(lineColor, lineThickness); graphics.DrawPath(pen, tail); } @@ -317,10 +316,10 @@ namespace Greenshot.Editor.Drawing //draw the bubble border state = graphics.Save(); // Draw bubble where the Tail is not visible. - using (Region clipRegion = new Region(tail)) + using (Region clipRegion = new(tail)) { graphics.SetClip(clipRegion, CombineMode.Exclude); - using Pen pen = new Pen(lineColor, lineThickness); + using Pen pen = new(lineColor, lineThickness); //pen.EndCap = pen.StartCap = LineCap.Round; graphics.DrawPath(pen, bubble); } @@ -355,12 +354,12 @@ namespace Greenshot.Editor.Drawing return true; } - Point clickedPoint = new Point(x, y); + Point clickedPoint = new(x, y); if (Status != EditStatus.UNDRAWN) { int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); - using Pen pen = new Pen(lineColor, lineThickness); + using Pen pen = new(lineColor, lineThickness); using (GraphicsPath bubblePath = CreateBubble(lineThickness)) { bubblePath.Widen(pen); diff --git a/src/Greenshot.Editor/Drawing/StepLabelContainer.cs b/src/Greenshot.Editor/Drawing/StepLabelContainer.cs index e5d93e514..198a209db 100644 --- a/src/Greenshot.Editor/Drawing/StepLabelContainer.cs +++ b/src/Greenshot.Editor/Drawing/StepLabelContainer.cs @@ -39,7 +39,7 @@ namespace Greenshot.Editor.Drawing [Serializable] public sealed class StepLabelContainer : DrawableContainer { - [NonSerialized] private StringFormat _stringFormat = new StringFormat(); + [NonSerialized] private StringFormat _stringFormat = new(); private readonly bool _drawAsRectangle = false; @@ -55,17 +55,10 @@ namespace Greenshot.Editor.Drawing CreateDefaultAdorners(); } - // Used to store the number of this label, so when deserializing it can be placed back to the StepLabels list in the right location - private int _number; - // Used to store the counter start of the Surface, as the surface is NOT stored. private int _counterStart = 1; - public int Number - { - get { return _number; } - set { _number = value; } - } + public int Number { get; set; } /// /// Retrieve the counter before serializing @@ -117,7 +110,7 @@ namespace Greenshot.Editor.Drawing newParentSurface.AddStepLabel(this); } - public override NativeSize DefaultSize => new NativeSize(30, 30); + public override NativeSize DefaultSize => new(30, 30); public override bool InitContent() { @@ -137,7 +130,7 @@ namespace Greenshot.Editor.Drawing /// public override bool HandleMouseDown(int mouseX, int mouseY) { - return base.HandleMouseDown(mouseX - Width / 2, mouseY - Height / 2); + return base.HandleMouseDown(mouseX - (Width / 2), mouseY - (Height / 2)); } /// @@ -161,7 +154,7 @@ namespace Greenshot.Editor.Drawing return; } - ((Surface) Parent)?.RemoveStepLabel(this); + ((Surface)Parent)?.RemoveStepLabel(this); if (_stringFormat == null) { return; @@ -174,8 +167,8 @@ namespace Greenshot.Editor.Drawing public override bool HandleMouseMove(int x, int y) { Invalidate(); - Left = x - Width / 2; - Top = y - Height / 2; + Left = x - (Width / 2); + Top = y - (Height / 2); Invalidate(); return true; } @@ -192,7 +185,7 @@ namespace Greenshot.Editor.Drawing graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.None; graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; - string text = ((Surface) Parent).CountStepLabels(this).ToString(); + string text = ((Surface)Parent).CountStepLabels(this).ToString(); var rect = new NativeRect(Left, Top, Width, Height).Normalize(); Color fillColor = GetFieldValueAsColor(FieldType.FILL_COLOR); Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); @@ -206,8 +199,8 @@ namespace Greenshot.Editor.Drawing } float fontSize = Math.Min(Math.Abs(Width), Math.Abs(Height)) / 1.4f; - using FontFamily fam = new FontFamily(FontFamily.GenericSansSerif.Name); - using Font font = new Font(fam, fontSize, FontStyle.Bold, GraphicsUnit.Pixel); + using FontFamily fam = new(FontFamily.GenericSansSerif.Name); + using Font font = new(fam, fontSize, FontStyle.Bold, GraphicsUnit.Pixel); TextContainer.DrawText(graphics, rect, 0, lineColor, false, _stringFormat, text, font); } @@ -215,12 +208,9 @@ namespace Greenshot.Editor.Drawing { var rect = new NativeRect(Left, Top, Width, Height).Normalize(); Color fillColor = GetFieldValueAsColor(FieldType.FILL_COLOR); - if (_drawAsRectangle) - { - return RectangleContainer.RectangleClickableAt(rect, 0, fillColor, x, y); - } - - return EllipseContainer.EllipseClickableAt(rect, 0, fillColor, x, y); + return _drawAsRectangle + ? RectangleContainer.RectangleClickableAt(rect, 0, fillColor, x, y) + : EllipseContainer.EllipseClickableAt(rect, 0, fillColor, x, y); } } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Surface.cs b/src/Greenshot.Editor/Drawing/Surface.cs index f050374a6..715f81742 100644 --- a/src/Greenshot.Editor/Drawing/Surface.cs +++ b/src/Greenshot.Editor/Drawing/Surface.cs @@ -53,9 +53,6 @@ namespace Greenshot.Editor.Drawing private static readonly ILog LOG = LogManager.GetLogger(typeof(Surface)); private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - // Property to identify the Surface ID - private Guid _uniqueId = Guid.NewGuid(); - /// /// This value is used to start counting the step labels /// @@ -64,11 +61,7 @@ namespace Greenshot.Editor.Drawing /// /// The GUID of the surface /// - public Guid ID - { - get => _uniqueId; - set => _uniqueId = value; - } + public Guid ID { get; set; } = Guid.NewGuid(); /// /// Event handlers (do not serialize!) @@ -145,7 +138,6 @@ namespace Greenshot.Editor.Drawing remove => _shadowChanged -= value; } - [NonSerialized] private int _currentDpi = 96; /// /// The most recent DPI value that was used @@ -169,9 +161,9 @@ namespace Greenshot.Editor.Drawing /// /// Undo/Redo stacks, should not be serialized as the file would be way to big /// - [NonSerialized] private readonly Stack _undoStack = new Stack(); + [NonSerialized] private readonly Stack _undoStack = new(); - [NonSerialized] private readonly Stack _redoStack = new Stack(); + [NonSerialized] private readonly Stack _redoStack = new(); /// /// Last save location, do not serialize! @@ -240,7 +232,7 @@ namespace Greenshot.Editor.Drawing /// /// all stepLabels for the surface, needed with serialization /// - private readonly List _stepLabels = new List(); + private readonly List _stepLabels = new(); public void AddStepLabel(StepLabelContainer stepLabel) { @@ -298,29 +290,11 @@ namespace Greenshot.Editor.Drawing return number; } - /// - /// all elements on the surface, needed with serialization - /// - private readonly IDrawableContainerList _elements; - - /// - /// all elements on the surface, needed with serialization - /// - private IFieldAggregator _fieldAggregator; - /// /// the cursor container, needed with serialization as we need a direct acces to it. /// private IDrawableContainer _cursorContainer; - /// - /// the modified flag specifies if the surface has had modifications after the last export. - /// Initial state is modified, as "it's not saved" - /// After serialization this should actually be "false" (the surface came from a stream) - /// For now we just serialize it... - /// - private bool _modified = true; - /// /// The image is the actual captured image, needed with serialization /// @@ -336,8 +310,8 @@ namespace Greenshot.Editor.Drawing } } - [NonSerialized] private Matrix _zoomMatrix = new Matrix(1, 0, 0, 1, 0, 0); - [NonSerialized] private Matrix _inverseZoomMatrix = new Matrix(1, 0, 0, 1, 0, 0); + [NonSerialized] private Matrix _zoomMatrix = new(1, 0, 0, 1, 0, 0); + [NonSerialized] private Matrix _inverseZoomMatrix = new(1, 0, 0, 1, 0, 0); [NonSerialized] private Fraction _zoomFactor = Fraction.Identity; public Fraction ZoomFactor @@ -353,25 +327,20 @@ namespace Greenshot.Editor.Drawing } } - /// /// Sets the surface size as zoomed image size. /// private void UpdateSize() { var size = _image.Size; - Size = new Size((int) (size.Width * _zoomFactor), (int) (size.Height * _zoomFactor)); + Size = new Size((int)(size.Width * _zoomFactor), (int)(size.Height * _zoomFactor)); } /// /// The field aggregator is that which is used to have access to all the fields inside the currently selected elements. /// e.g. used to decided if and which line thickness is shown when multiple elements are selected. /// - public IFieldAggregator FieldAggregator - { - get => _fieldAggregator; - set => _fieldAggregator = value; - } + public IFieldAggregator FieldAggregator { get; set; } /// /// The cursor container has it's own accessor so we can find and remove this (when needed) @@ -413,11 +382,7 @@ namespace Greenshot.Editor.Drawing /// /// Is this surface modified? This is only true if the surface has not been exported. /// - public bool Modified - { - get => _modified; - set => _modified = value; - } + public bool Modified { get; set; } = true; /// /// The DrawingMode property specifies the mode for drawing, more or less the element type. @@ -430,7 +395,7 @@ namespace Greenshot.Editor.Drawing _drawingMode = value; if (_drawingModeChanged != null) { - SurfaceDrawingModeEventArgs eventArgs = new SurfaceDrawingModeEventArgs + SurfaceDrawingModeEventArgs eventArgs = new() { DrawingMode = _drawingMode }; @@ -468,7 +433,7 @@ namespace Greenshot.Editor.Drawing public void AdjustToDpi(int dpi) { CurrentDpi = dpi; - foreach (var element in this._elements) + foreach (var element in Elements) { element.AdjustToDpi(dpi); } @@ -479,9 +444,9 @@ namespace Greenshot.Editor.Drawing /// public Surface() { - _fieldAggregator = new FieldAggregator(this); - _elements = new DrawableContainerList(_uniqueId); - selectedElements = new DrawableContainerList(_uniqueId); + FieldAggregator = new FieldAggregator(this); + Elements = new DrawableContainerList(ID); + selectedElements = new DrawableContainerList(ID); LOG.Debug("Creating surface!"); MouseDown += SurfaceMouseDown; MouseUp += SurfaceMouseUp; @@ -493,7 +458,7 @@ namespace Greenshot.Editor.Drawing DragEnter += OnDragEnter; // bind selected & elements to this, otherwise they can't inform of modifications selectedElements.Parent = this; - _elements.Parent = this; + Elements.Parent = this; // Make sure we are visible Visible = true; TabStop = false; @@ -520,7 +485,7 @@ namespace Greenshot.Editor.Drawing // Set new values Image = newImage; - _modified = true; + Modified = true; } /// @@ -553,7 +518,7 @@ namespace Greenshot.Editor.Drawing } // Make sure the image is NOT disposed, we took the reference directly into ourselves - ((Capture) capture).NullImage(); + ((Capture)capture).NullImage(); CaptureDetails = capture.CaptureDetails; } @@ -576,17 +541,17 @@ namespace Greenshot.Editor.Drawing } // Cleanup undo/redo stacks - while (_undoStack != null && _undoStack.Count > 0) + while (_undoStack?.Count > 0) { _undoStack.Pop().Dispose(); } - while (_redoStack != null && _redoStack.Count > 0) + while (_redoStack?.Count > 0) { _redoStack.Pop().Dispose(); } - foreach (IDrawableContainer container in _elements) + foreach (IDrawableContainer container in Elements) { container.Dispose(); } @@ -701,8 +666,8 @@ namespace Greenshot.Editor.Drawing try { long lengtBefore = streamWrite.Length; - BinaryFormatter binaryWrite = new BinaryFormatter(); - binaryWrite.Serialize(streamWrite, _elements); + BinaryFormatter binaryWrite = new(); + binaryWrite.Serialize(streamWrite, Elements); bytesWritten = streamWrite.Length - lengtBefore; } catch (Exception e) @@ -721,8 +686,8 @@ namespace Greenshot.Editor.Drawing { try { - BinaryFormatter binaryRead = new BinaryFormatter(); - IDrawableContainerList loadedElements = (IDrawableContainerList) binaryRead.Deserialize(streamRead); + BinaryFormatter binaryRead = new(); + IDrawableContainerList loadedElements = (IDrawableContainerList)binaryRead.Deserialize(streamRead); loadedElements.Parent = this; // Make sure the steplabels are sorted according to their number _stepLabels.Sort((p1, p2) => p1.Number.CompareTo(p2.Number)); @@ -803,7 +768,7 @@ namespace Greenshot.Editor.Drawing public IImageContainer AddImageContainer(Image image, int x, int y) { - ImageContainer bitmapContainer = new ImageContainer(this) + ImageContainer bitmapContainer = new(this) { Image = image, Left = x, @@ -815,7 +780,7 @@ namespace Greenshot.Editor.Drawing public IImageContainer AddImageContainer(string filename, int x, int y) { - ImageContainer bitmapContainer = new ImageContainer(this); + ImageContainer bitmapContainer = new(this); bitmapContainer.Load(filename); bitmapContainer.Left = x; bitmapContainer.Top = y; @@ -825,7 +790,7 @@ namespace Greenshot.Editor.Drawing public IIconContainer AddIconContainer(Icon icon, int x, int y) { - IconContainer iconContainer = new IconContainer(this) + IconContainer iconContainer = new(this) { Icon = icon, Left = x, @@ -837,7 +802,7 @@ namespace Greenshot.Editor.Drawing public IIconContainer AddIconContainer(string filename, int x, int y) { - IconContainer iconContainer = new IconContainer(this); + IconContainer iconContainer = new(this); iconContainer.Load(filename); iconContainer.Left = x; iconContainer.Top = y; @@ -847,7 +812,7 @@ namespace Greenshot.Editor.Drawing public ICursorContainer AddCursorContainer(Cursor cursor, int x, int y) { - CursorContainer cursorContainer = new CursorContainer(this) + CursorContainer cursorContainer = new(this) { Cursor = cursor, Left = x, @@ -859,7 +824,7 @@ namespace Greenshot.Editor.Drawing public ICursorContainer AddCursorContainer(string filename, int x, int y) { - CursorContainer cursorContainer = new CursorContainer(this); + CursorContainer cursorContainer = new(this); cursorContainer.Load(filename); cursorContainer.Left = x; cursorContainer.Top = y; @@ -870,7 +835,7 @@ namespace Greenshot.Editor.Drawing public ITextContainer AddTextContainer(string text, int x, int y, FontFamily family, float size, bool italic, bool bold, bool shadow, int borderSize, Color color, Color fillColor) { - TextContainer textContainer = new TextContainer(this) + TextContainer textContainer = new(this) { Text = text, Left = x, @@ -931,11 +896,11 @@ namespace Greenshot.Editor.Drawing private void FitContainer(IDrawableContainer drawableContainer) { double factor = 1; - if (drawableContainer.Width > this.Width) + if (drawableContainer.Width > Width) { factor = drawableContainer.Width / (double)Width; } - if (drawableContainer.Height > this.Height) + if (drawableContainer.Height > Height) { var otherFactor = drawableContainer.Height / (double)Height; factor = Math.Max(factor, otherFactor); @@ -957,7 +922,7 @@ namespace Greenshot.Editor.Drawing { string possibleUrl = ClipboardHelper.GetText(e.Data); // Test if it's an url and try to download the image so we have it in the original form - if (possibleUrl != null && possibleUrl.StartsWith("http")) + if (possibleUrl?.StartsWith("http") == true) { var drawableContainer = NetworkHelper.DownloadImageAsDrawableContainer(possibleUrl); if (drawableContainer != null) @@ -1038,18 +1003,18 @@ namespace Greenshot.Editor.Drawing /// public void ApplyBitmapEffect(IEffect effect) { - BackgroundForm backgroundForm = new BackgroundForm("Effect", "Please wait"); + BackgroundForm backgroundForm = new("Effect", "Please wait"); backgroundForm.Show(); Application.DoEvents(); try { var imageRectangle = new NativeRect(NativePoint.Empty, Image.Size); - Matrix matrix = new Matrix(); + Matrix matrix = new(); Image newImage = ImageHelper.ApplyEffect(Image, effect, matrix); if (newImage != null) { // Make sure the elements move according to the offset the effect made the bitmap move - _elements.Transform(matrix); + Elements.Transform(matrix); // Make undoable MakeUndoable(new SurfaceBackgroundChangeMemento(this, matrix), false); SetImage(newImage, false); @@ -1103,7 +1068,7 @@ namespace Greenshot.Editor.Drawing } // special condition for vertical - if(cropMode == CropContainer.CropModes.Vertical && cropRectangle.Width == Image.Width) + if (cropMode == CropContainer.CropModes.Vertical && cropRectangle.Width == Image.Width) { //crop out the hole image is not allowed return false; @@ -1117,12 +1082,7 @@ namespace Greenshot.Editor.Drawing } //condition for all other crop modes - if (cropRectangle.Height > 0 && cropRectangle.Width > 0) - { - return true; - } - - return false; + return cropRectangle.Height > 0 && cropRectangle.Width > 0; } /// @@ -1240,7 +1200,7 @@ namespace Greenshot.Editor.Drawing // Do not dispose otherwise we can't undo the image! SetImage(tmpImage, false); - _elements.Transform(matrix); + Elements.Transform(matrix); if (_surfaceSizeChanged != null && !imageRectangle.Equals(new NativeRect(NativePoint.Empty, tmpImage.Size))) { _surfaceSizeChanged(this, null); @@ -1252,7 +1212,7 @@ namespace Greenshot.Editor.Drawing /// /// Crop out the surface - /// Splits the image in 3 parts(top, middle, bottom). Crop out the middle and joins top and bottom. + /// Splits the image in 3 parts(top, middle, bottom). Crop out the middle and joins top and bottom. /// /// NativeRect of the middle part /// bool @@ -1298,7 +1258,7 @@ namespace Greenshot.Editor.Drawing // Do not dispose otherwise we can't undo the image! SetImage(newImage, false); - _elements.Transform(matrix); + Elements.Transform(matrix); if (_surfaceSizeChanged != null && !imageRectangle.Equals(new NativeRect(NativePoint.Empty, newImage.Size))) { _surfaceSizeChanged(this, null); @@ -1331,13 +1291,13 @@ namespace Greenshot.Editor.Drawing var insertPositionLeft = 0; if (leftRectangle.Width > 0) { - graphics.DrawImage(Image, new NativeRect(insertPositionLeft, 0, leftRectangle.Width, leftRectangle.Height), leftRectangle , GraphicsUnit.Pixel); + graphics.DrawImage(Image, new NativeRect(insertPositionLeft, 0, leftRectangle.Width, leftRectangle.Height), leftRectangle, GraphicsUnit.Pixel); insertPositionLeft += leftRectangle.Width; } - + if (rightRectangle.Width > 0) { - graphics.DrawImage(Image, new NativeRect(insertPositionLeft, 0, rightRectangle.Width, rightRectangle.Height), rightRectangle, GraphicsUnit.Pixel); + graphics.DrawImage(Image, new NativeRect(insertPositionLeft, 0, rightRectangle.Width, rightRectangle.Height), rightRectangle, GraphicsUnit.Pixel); } } catch (Exception ex) @@ -1356,7 +1316,7 @@ namespace Greenshot.Editor.Drawing // Do not dispose otherwise we can't undo the image! SetImage(newImage, false); - _elements.Transform(matrix); + Elements.Transform(matrix); if (_surfaceSizeChanged != null && !imageRectangle.Equals(new NativeRect(NativePoint.Empty, newImage.Size))) { _surfaceSizeChanged(this, null); @@ -1377,7 +1337,7 @@ namespace Greenshot.Editor.Drawing SetImage(previous, false); if (matrix != null) { - _elements.Transform(matrix); + Elements.Transform(matrix); } _surfaceSizeChanged?.Invoke(this, null); @@ -1396,7 +1356,7 @@ namespace Greenshot.Editor.Drawing foreach (IAdorner adorner in drawableContainer.Adorners) { if (!adorner.IsActive && !adorner.HitTest(mouseEventArgs.Location)) continue; - + if (adorner.Cursor != null) { Cursor = adorner.Cursor; @@ -1413,7 +1373,7 @@ namespace Greenshot.Editor.Drawing /// Translate mouse coordinates as if they were applied directly to unscaled image. /// private MouseEventArgs InverseZoomMouseCoordinates(MouseEventArgs e) - => new MouseEventArgs(e.Button, e.Clicks, (int) (e.X / _zoomFactor), (int) (e.Y / _zoomFactor), e.Delta); + => new(e.Button, e.Clicks, (int)(e.X / _zoomFactor), (int)(e.Y / _zoomFactor), e.Delta); /// /// This event handler is called when someone presses the mouse on a surface. @@ -1438,14 +1398,14 @@ namespace Greenshot.Editor.Drawing if (e.Button == MouseButtons.Right) { IDrawableContainerList selectedList = null; - if (selectedElements != null && selectedElements.Count > 0) + if (selectedElements?.Count > 0) { selectedList = selectedElements; } else { // Single element - IDrawableContainer rightClickedContainer = _elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y); + IDrawableContainer rightClickedContainer = Elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y); if (rightClickedContainer != null) { selectedList = new DrawableContainerList(ID) @@ -1455,7 +1415,7 @@ namespace Greenshot.Editor.Drawing } } - if (selectedList != null && selectedList.Count > 0) + if (selectedList?.Count > 0) { selectedList.ShowContextMenu(e, this); } @@ -1510,7 +1470,7 @@ namespace Greenshot.Editor.Drawing // check whether an existing element was clicked // we save mouse down element separately from selectedElements (checked on mouse up), // since it could be moved around before it is actually selected - _mouseDownElement = _elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y); + _mouseDownElement = Elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y); if (_mouseDownElement != null) { @@ -1536,9 +1496,9 @@ namespace Greenshot.Editor.Drawing return; } - Point currentMouse = new Point(e.X, e.Y); + Point currentMouse = new(e.X, e.Y); - _elements.Status = EditStatus.IDLE; + Elements.Status = EditStatus.IDLE; if (_mouseDownElement != null) { _mouseDownElement.Status = EditStatus.IDLE; @@ -1549,7 +1509,7 @@ namespace Greenshot.Editor.Drawing if (DrawingMode == DrawingModes.None) { // check whether an existing element was clicked - IDrawableContainer element = _elements.ClickableElementAt(currentMouse.X, currentMouse.Y); + IDrawableContainer element = Elements.ClickableElementAt(currentMouse.X, currentMouse.Y); bool shiftModifier = (ModifierKeys & Keys.Shift) == Keys.Shift; if (element != null) { @@ -1591,7 +1551,7 @@ namespace Greenshot.Editor.Drawing { if (!_drawingElement.InitContent()) { - _elements.Remove(_drawingElement); + Elements.Remove(_drawingElement); _drawingElement.Invalidate(); } else @@ -1668,12 +1628,12 @@ namespace Greenshot.Editor.Drawing _mouseStart = currentMouse; _mouseDownElement.Invalidate(); - _modified = true; + Modified = true; } else if (_drawingElement != null) { _drawingElement.HandleMouseMove(currentMouse.X, currentMouse.Y); - _modified = true; + Modified = true; } } @@ -1705,7 +1665,7 @@ namespace Greenshot.Editor.Drawing //graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; //graphics.CompositingQuality = CompositingQuality.HighQuality; //graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - _elements.Draw(graphics, clone, renderMode, new Rectangle(Point.Empty, clone.Size)); + Elements.Draw(graphics, clone, renderMode, new Rectangle(Point.Empty, clone.Size)); } return clone; @@ -1723,14 +1683,14 @@ namespace Greenshot.Editor.Drawing private static NativeRect ZoomClipRectangle(NativeRect rc, double scale, int inflateAmount = 0) { rc = new NativeRect( - (int) (rc.X * scale), - (int) (rc.Y * scale), - (int) (rc.Width * scale) + 1, - (int) (rc.Height * scale) + 1 + (int)(rc.X * scale), + (int)(rc.Y * scale), + (int)(rc.Width * scale) + 1, + (int)(rc.Height * scale) + 1 ); if (scale > 1) { - inflateAmount = (int) (inflateAmount * scale); + inflateAmount = (int)(inflateAmount * scale); } return rc.Inflate(inflateAmount, inflateAmount); @@ -1758,8 +1718,8 @@ namespace Greenshot.Editor.Drawing // When zooming to N/M, clip rectangle top and left coordinates should be multiples of N. if (_zoomFactor.Numerator > 1 && _zoomFactor.Denominator > 1) { - int horizontalCorrection = targetClipRectangle.Left % (int) _zoomFactor.Numerator; - int verticalCorrection = targetClipRectangle.Top % (int) _zoomFactor.Numerator; + int horizontalCorrection = targetClipRectangle.Left % (int)_zoomFactor.Numerator; + int verticalCorrection = targetClipRectangle.Top % (int)_zoomFactor.Numerator; if (horizontalCorrection != 0) { targetClipRectangle = targetClipRectangle.ChangeX(-horizontalCorrection).ChangeWidth(horizontalCorrection); @@ -1773,7 +1733,7 @@ namespace Greenshot.Editor.Drawing NativeRect imageClipRectangle = ZoomClipRectangle(targetClipRectangle, _zoomFactor.Inverse(), 2); - if (_elements.HasIntersectingFilters(imageClipRectangle) || _zoomFactor > Fraction.Identity) + if (Elements.HasIntersectingFilters(imageClipRectangle) || _zoomFactor > Fraction.Identity) { if (_buffer != null) { @@ -1801,7 +1761,7 @@ namespace Greenshot.Editor.Drawing DrawBackground(graphics, imageClipRectangle); graphics.DrawImage(Image, imageClipRectangle, imageClipRectangle, GraphicsUnit.Pixel); graphics.SetClip(ZoomClipRectangle(Rectangle.Round(targetGraphics.ClipBounds), _zoomFactor.Inverse(), 2)); - _elements.Draw(graphics, _buffer, RenderMode.EDIT, imageClipRectangle); + Elements.Draw(graphics, _buffer, RenderMode.EDIT, imageClipRectangle); } if (_zoomFactor == Fraction.Identity) @@ -1829,13 +1789,13 @@ namespace Greenshot.Editor.Drawing if (_zoomFactor == Fraction.Identity) { targetGraphics.DrawImage(Image, imageClipRectangle, imageClipRectangle, GraphicsUnit.Pixel); - _elements.Draw(targetGraphics, null, RenderMode.EDIT, imageClipRectangle); + Elements.Draw(targetGraphics, null, RenderMode.EDIT, imageClipRectangle); } else { targetGraphics.ScaleTransform(_zoomFactor, _zoomFactor); DrawSmoothImage(targetGraphics, Image, imageClipRectangle); - _elements.Draw(targetGraphics, null, RenderMode.EDIT, imageClipRectangle); + Elements.Draw(targetGraphics, null, RenderMode.EDIT, imageClipRectangle); targetGraphics.ResetTransform(); } } @@ -1907,7 +1867,7 @@ namespace Greenshot.Editor.Drawing /// true if invalidate needs to be called public void AddElement(IDrawableContainer element, bool makeUndoable = true, bool invalidate = true) { - _elements.Add(element); + Elements.Add(element); if (element is DrawableContainer container) { container.FieldChanged += Element_FieldChanged; @@ -1935,7 +1895,7 @@ namespace Greenshot.Editor.Drawing MakeUndoable(new AddElementMemento(this, element), false); } - _modified = true; + Modified = true; } /// @@ -1946,13 +1906,13 @@ namespace Greenshot.Editor.Drawing public void RemoveElements(IDrawableContainerList elementsToRemove, bool makeUndoable = true) { // fix potential issues with iterating a changing list - DrawableContainerList cloned = new DrawableContainerList(elementsToRemove); + DrawableContainerList cloned = new(elementsToRemove); if (makeUndoable) { // Take all containers to make undoable var undoableContainers = elementsToRemove.Where(c => c.IsUndoable).ToList(); - if (undoableContainers.Any()) + if (undoableContainers.Count > 0) { var undoableContainerList = new DrawableContainerList(undoableContainers); MakeUndoable(new DeleteElementsMemento(this, undoableContainerList), false); @@ -1969,7 +1929,7 @@ namespace Greenshot.Editor.Drawing Invalidate(); if (_movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs + SurfaceElementEventArgs eventArgs = new() { Elements = cloned }; @@ -1987,7 +1947,7 @@ namespace Greenshot.Editor.Drawing public void RemoveElement(IDrawableContainer elementToRemove, bool makeUndoable = true, bool invalidate = true, bool generateEvents = true) { DeselectElement(elementToRemove, generateEvents); - _elements.Remove(elementToRemove); + Elements.Remove(elementToRemove); if (elementToRemove is DrawableContainer element) { element.FieldChanged -= Element_FieldChanged; @@ -2009,7 +1969,7 @@ namespace Greenshot.Editor.Drawing MakeUndoable(new DeleteElementMemento(this, elementToRemove), false); } - _modified = true; + Modified = true; } /// @@ -2020,12 +1980,12 @@ namespace Greenshot.Editor.Drawing public void AddElements(IDrawableContainerList elementsToAdd, bool makeUndoable = true) { // fix potential issues with iterating a changing list - DrawableContainerList cloned = new DrawableContainerList(elementsToAdd); + DrawableContainerList cloned = new(elementsToAdd); if (makeUndoable) { // Take all containers to make undoable var undoableContainers = elementsToAdd.Where(c => c.IsUndoable).ToList(); - if (undoableContainers.Any()) + if (undoableContainers.Count > 0) { var undoableContainerList = new DrawableContainerList(undoableContainers); MakeUndoable(new AddElementsMemento(this, undoableContainerList), false); @@ -2065,7 +2025,7 @@ namespace Greenshot.Editor.Drawing RemoveElements(selectedElements); if (_movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); + SurfaceElementEventArgs eventArgs = new(); _movingElementChanged(this, eventArgs); } } @@ -2117,10 +2077,10 @@ namespace Greenshot.Editor.Drawing public void ConfirmSelectedConfirmableElements(bool confirm) { // create new collection so that we can iterate safely (selectedElements might change due with confirm/cancel) - List selectedDCs = new List(selectedElements); + List selectedDCs = new(selectedElements); foreach (IDrawableContainer dc in selectedDCs.Where(c => c.IsConfirmable)) - { - throw new NotImplementedException($"No confirm/cancel defined for Container type {dc.GetType()}"); + { + throw new NotImplementedException($"No confirm/cancel defined for Container type {dc.GetType()}"); } // maybe the undo button has to be enabled @@ -2135,7 +2095,7 @@ namespace Greenshot.Editor.Drawing public void ConfirmCrop(bool confirm) { if (_cropContainer is not CropContainer e) return; - + if (confirm && selectedElements.Count > 0) { // No undo memento for the cropcontainer itself, only for the effect @@ -2195,11 +2155,11 @@ namespace Greenshot.Editor.Drawing if (formats.Contains(typeof(IDrawableContainerList).FullName)) { - IDrawableContainerList dcs = (IDrawableContainerList) ClipboardHelper.GetFromDataObject(clipboard, typeof(IDrawableContainerList)); + IDrawableContainerList dcs = (IDrawableContainerList)ClipboardHelper.GetFromDataObject(clipboard, typeof(IDrawableContainerList)); if (dcs != null) { // Make element(s) only move 10,10 if the surface is the same - bool isSameSurface = (dcs.ParentID == _uniqueId); + bool isSameSurface = dcs.ParentID == ID; dcs.Parent = this; var moveOffset = isSameSurface ? new NativePoint(10, 10) : NativePoint.Empty; // Here a fix for bug #1475, first calculate the bounds of the complete IDrawableContainerList @@ -2282,7 +2242,7 @@ namespace Greenshot.Editor.Drawing if (drawableContainer == null) continue; DeselectAllElements(); drawableContainer.Left = pasteLocation.X; - drawableContainer.Top = pasteLocation.Y; + drawableContainer.Top = pasteLocation.Y; AddElement(drawableContainer); SelectElement(drawableContainer); pasteLocation = pasteLocation.Offset(10, 10); @@ -2317,8 +2277,8 @@ namespace Greenshot.Editor.Drawing if (!rc.Contains(point)) { point = new NativePoint( - rc.Left + (int) (rc.Width * horizontalRatio), - rc.Top + (int) (rc.Height * verticalRatio) + rc.Left + (int)(rc.Width * horizontalRatio), + rc.Top + (int)(rc.Height * verticalRatio) ); } @@ -2400,7 +2360,7 @@ namespace Greenshot.Editor.Drawing if (_movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs + SurfaceElementEventArgs eventArgs = new() { Elements = selectedElements }; @@ -2433,7 +2393,7 @@ namespace Greenshot.Editor.Drawing FieldAggregator.BindElement(container); if (generateEvents && _movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs + SurfaceElementEventArgs eventArgs = new() { Elements = selectedElements }; @@ -2451,7 +2411,7 @@ namespace Greenshot.Editor.Drawing /// public void SelectAllElements() { - SelectElements(_elements); + SelectElements(Elements); } /// @@ -2463,13 +2423,13 @@ namespace Greenshot.Editor.Drawing SuspendLayout(); foreach (var drawableContainer in elements) { - var element = (DrawableContainer) drawableContainer; + var element = (DrawableContainer)drawableContainer; SelectElement(element, false, false); } if (_movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs + SurfaceElementEventArgs eventArgs = new() { Elements = selectedElements }; @@ -2487,7 +2447,7 @@ namespace Greenshot.Editor.Drawing /// false if no keys were processed public bool ProcessCmdKey(Keys k) { - if (selectedElements.Count <= 0 && k != Keys.Escape) return false; + if (selectedElements.Count == 0 && k != Keys.Escape) return false; bool shiftModifier = (ModifierKeys & Keys.Shift) == Keys.Shift; int px = shiftModifier ? 10 : 1; @@ -2593,51 +2553,50 @@ namespace Greenshot.Editor.Drawing } return true; - } // for laptops without numPads, also allow shift modifier private void SetSelectedElementColor(Color color, bool numPad, bool shift) { - if (numPad || shift) - { - selectedElements.SetForegroundColor(color); - UpdateForegroundColorEvent(this, color); - } - else - { - selectedElements.SetBackgroundColor(color); - UpdateBackgroundColorEvent(this, color); - } - selectedElements.Invalidate(); + if (numPad || shift) + { + selectedElements.SetForegroundColor(color); + UpdateForegroundColorEvent(this, color); + } + else + { + selectedElements.SetBackgroundColor(color); + UpdateBackgroundColorEvent(this, color); + } + selectedElements.Invalidate(); } private void ChangeLineThickness(int increaseBy) { - var newThickness = selectedElements.IncreaseLineThickness(increaseBy); - UpdateLineThicknessEvent(this, newThickness); - selectedElements.Invalidate(); + var newThickness = selectedElements.IncreaseLineThickness(increaseBy); + UpdateLineThicknessEvent(this, newThickness); + selectedElements.Invalidate(); } private void FlipShadow() { - var shadow = selectedElements.FlipShadow(); - UpdateShadowEvent(this, shadow); - selectedElements.Invalidate(); + var shadow = selectedElements.FlipShadow(); + UpdateShadowEvent(this, shadow); + selectedElements.Invalidate(); } /// /// Property for accessing the elements on the surface /// - public IDrawableContainerList Elements => _elements; + public IDrawableContainerList Elements { get; } /// /// pulls selected elements up one level in hierarchy /// public void PullElementsUp() { - _elements.PullElementsUp(selectedElements); - _elements.Invalidate(); + Elements.PullElementsUp(selectedElements); + Elements.Invalidate(); } /// @@ -2645,8 +2604,8 @@ namespace Greenshot.Editor.Drawing /// public void PullElementsToTop() { - _elements.PullElementsToTop(selectedElements); - _elements.Invalidate(); + Elements.PullElementsToTop(selectedElements); + Elements.Invalidate(); } /// @@ -2654,8 +2613,8 @@ namespace Greenshot.Editor.Drawing /// public void PushElementsDown() { - _elements.PushElementsDown(selectedElements); - _elements.Invalidate(); + Elements.PushElementsDown(selectedElements); + Elements.Invalidate(); } /// @@ -2663,8 +2622,8 @@ namespace Greenshot.Editor.Drawing /// public void PushElementsToBottom() { - _elements.PushElementsToBottom(selectedElements); - _elements.Invalidate(); + Elements.PushElementsToBottom(selectedElements); + Elements.Invalidate(); } /// @@ -2673,7 +2632,7 @@ namespace Greenshot.Editor.Drawing /// true if selected elements could be pulled up, false otherwise public bool CanPullSelectionUp() { - return _elements.CanPullUp(selectedElements); + return Elements.CanPullUp(selectedElements); } /// @@ -2682,7 +2641,7 @@ namespace Greenshot.Editor.Drawing /// true if selected elements could be pushed down, false otherwise public bool CanPushSelectionDown() { - return _elements.CanPushDown(selectedElements); + return Elements.CanPushDown(selectedElements); } private void Element_FieldChanged(object sender, FieldChangedEventArgs e) @@ -2692,7 +2651,7 @@ namespace Greenshot.Editor.Drawing public bool IsOnSurface(IDrawableContainer container) { - return _elements.Contains(container); + return Elements.Contains(container); } public NativePoint ToSurfaceCoordinates(NativePoint point) diff --git a/src/Greenshot.Editor/Drawing/SvgContainer.cs b/src/Greenshot.Editor/Drawing/SvgContainer.cs index 283f755e8..c1bcc2405 100644 --- a/src/Greenshot.Editor/Drawing/SvgContainer.cs +++ b/src/Greenshot.Editor/Drawing/SvgContainer.cs @@ -41,13 +41,13 @@ namespace Greenshot.Editor.Drawing _svgDocument = svgDocument; Size = new Size((int)svgDocument.Width, (int)svgDocument.Height); } - + protected override Image ComputeBitmap() { //var image = ImageHelper.CreateEmpty(Width, Height, PixelFormat.Format32bppArgb, Color.Transparent); var image = _svgDocument.Draw(Width, Height); - + if (RotationAngle == 0) return image; var newImage = image.Rotate(RotationAngle); @@ -57,6 +57,6 @@ namespace Greenshot.Editor.Drawing public override bool HasDefaultSize => true; - public override NativeSize DefaultSize => new NativeSize((int)_svgDocument.Width, (int)_svgDocument.Height); + public override NativeSize DefaultSize => new((int)_svgDocument.Width, (int)_svgDocument.Height); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/TextContainer.cs b/src/Greenshot.Editor/Drawing/TextContainer.cs index a49fd4bee..170d91607 100644 --- a/src/Greenshot.Editor/Drawing/TextContainer.cs +++ b/src/Greenshot.Editor/Drawing/TextContainer.cs @@ -56,7 +56,7 @@ namespace Greenshot.Editor.Drawing /// /// The StringFormat object is not serializable!! /// - [NonSerialized] private StringFormat _stringFormat = new StringFormat(); + [NonSerialized] private StringFormat _stringFormat = new(); public StringFormat StringFormat => _stringFormat; @@ -185,7 +185,7 @@ namespace Greenshot.Editor.Drawing public override void Invalidate() { base.Invalidate(); - if (_textBox != null && _textBox.Visible) + if (_textBox?.Visible == true) { _textBox.Invalidate(); } @@ -362,7 +362,7 @@ namespace Greenshot.Editor.Drawing rect = new NativeRect(Left, Top, Width, Height).Normalize(); int pixelsAfter = rect.Width * rect.Height; - float factor = pixelsAfter / (float) pixelsBefore; + float factor = pixelsAfter / (float)pixelsBefore; float fontSize = GetFieldValueAsFloat(FieldType.FONT_SIZE); fontSize *= factor; @@ -462,8 +462,8 @@ namespace Greenshot.Editor.Drawing private void UpdateAlignment() { - _stringFormat.Alignment = (StringAlignment) GetFieldValue(FieldType.TEXT_HORIZONTAL_ALIGNMENT); - _stringFormat.LineAlignment = (StringAlignment) GetFieldValue(FieldType.TEXT_VERTICAL_ALIGNMENT); + _stringFormat.Alignment = (StringAlignment)GetFieldValue(FieldType.TEXT_HORIZONTAL_ALIGNMENT); + _stringFormat.LineAlignment = (StringAlignment)GetFieldValue(FieldType.TEXT_VERTICAL_ALIGNMENT); } /// @@ -501,7 +501,7 @@ namespace Greenshot.Editor.Drawing int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); - int lineWidth = (int) Math.Floor(lineThickness / 2d); + int lineWidth = (int)Math.Floor(lineThickness / 2d); int correction = (lineThickness + 1) % 2; if (lineThickness <= 1) { @@ -518,8 +518,8 @@ namespace Greenshot.Editor.Drawing lineWidth = 0; } - _textBox.Width = displayRectangle.Width - 2 * lineWidth + correction; - _textBox.Height = displayRectangle.Height - 2 * lineWidth + correction; + _textBox.Width = displayRectangle.Width - (2 * lineWidth) + correction; + _textBox.Height = displayRectangle.Height - (2 * lineWidth) + correction; } /// @@ -532,7 +532,7 @@ namespace Greenshot.Editor.Drawing return; } - var alignment = (StringAlignment) GetFieldValue(FieldType.TEXT_HORIZONTAL_ALIGNMENT); + var alignment = (StringAlignment)GetFieldValue(FieldType.TEXT_HORIZONTAL_ALIGNMENT); switch (alignment) { case StringAlignment.Near: @@ -645,13 +645,13 @@ namespace Greenshot.Editor.Drawing return; } #endif - int textOffset = lineThickness > 0 ? (int) Math.Ceiling(lineThickness / 2d) : 0; + int textOffset = lineThickness > 0 ? (int)Math.Ceiling(lineThickness / 2d) : 0; // draw shadow before anything else if (drawShadow) { - int basealpha = 100; + const int basealpha = 100; int alpha = basealpha; - int steps = 5; + const int steps = 5; int currentStep = 1; while (currentStep <= steps) { diff --git a/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs b/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs index 45238caaf..8d710dd65 100644 --- a/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs +++ b/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs @@ -36,12 +36,7 @@ namespace Greenshot.Editor.Drawing [Serializable] public abstract class VectorGraphicsContainer : DrawableContainer { - private int _rotationAngle; - protected int RotationAngle - { - get => _rotationAngle; - set => _rotationAngle = value; - } + protected int RotationAngle { get; set; } /// /// This is the cached version of the bitmap, pre-rendered to save performance @@ -53,7 +48,7 @@ namespace Greenshot.Editor.Drawing /// Constructor takes care of calling Init /// /// ISurface - public VectorGraphicsContainer(ISurface parent) : base(parent) + protected VectorGraphicsContainer(ISurface parent) : base(parent) { Init(); } @@ -92,7 +87,6 @@ namespace Greenshot.Editor.Drawing /// When disposing==true all non-managed resources should be freed too! /// /// - protected override void Dispose(bool disposing) { if (disposing) @@ -132,7 +126,6 @@ namespace Greenshot.Editor.Drawing graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.DrawImage(_cachedImage, Bounds); } diff --git a/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs index fff576267..7c2621a0d 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs @@ -45,7 +45,7 @@ namespace Greenshot.Editor.FileFormatHandlers public abstract bool TryLoadFromStream(Stream stream, string extension, out Bitmap bitmap); /// - /// Default implementation taking the TryLoadFromStream image and placing it in an ImageContainer + /// Default implementation taking the TryLoadFromStream image and placing it in an ImageContainer /// /// Stream /// string diff --git a/src/Greenshot.Editor/FileFormatHandlers/DefaultFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/DefaultFileFormatHandler.cs index 115b5328f..71ea8edd7 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/DefaultFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/DefaultFileFormatHandler.cs @@ -71,7 +71,7 @@ namespace Greenshot.Editor.FileFormatHandlers { return false; } - EncoderParameters parameters = new EncoderParameters(1) + EncoderParameters parameters = new(1) { Param = { diff --git a/src/Greenshot.Editor/FileFormatHandlers/DibFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/DibFileFormatHandler.cs index b14a33bd0..252ded983 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/DibFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/DibFileFormatHandler.cs @@ -100,7 +100,7 @@ namespace Greenshot.Editor.FileFormatHandlers bitmap = new Bitmap(infoHeader.Width, infoHeader.Height, -(int)(infoHeader.SizeImage / infoHeader.Height), infoHeader.BitCount == 32 ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb, - IntPtr.Add(handle.AddrOfPinnedObject(), (int)infoHeader.OffsetToPixels + (infoHeader.Height - 1) * (int)(infoHeader.SizeImage / infoHeader.Height)) + IntPtr.Add(handle.AddrOfPinnedObject(), (int)infoHeader.OffsetToPixels + ((infoHeader.Height - 1) * (int)(infoHeader.SizeImage / infoHeader.Height))) ); } catch (Exception ex) @@ -148,7 +148,7 @@ namespace Greenshot.Editor.FileFormatHandlers // The bitmap info hear takes this many bytes: var bitmapInfoHeaderSize = Marshal.SizeOf(typeof(BitmapInfoHeader)); // The bitmap info size is the header + 3 RGBQUADs - var bitmapInfoSize = bitmapInfoHeaderSize + 3 * Marshal.SizeOf(typeof(RgbQuad)); + var bitmapInfoSize = bitmapInfoHeaderSize + (3 * Marshal.SizeOf(typeof(RgbQuad))); // Create a byte [] to contain the complete DIB (with .NET 5 and upwards, we could write the pixels directly to a stream) var fullBmpBytes = new byte[bitmapInfoSize + bitmapSize]; @@ -192,7 +192,7 @@ namespace Greenshot.Editor.FileFormatHandlers for (int destinationY = 0; destinationY < sourceBitmap.Height; destinationY++) { // Calculate the y coordinate for the bottom up. (flipping the image) - var sourceY = (sourceBitmap.Height - 1) - destinationY; + var sourceY = sourceBitmap.Height - 1 - destinationY; // Make a Span for the source bitmap pixels var sourceLine = bitmapSourceSpan.Slice(sourceBitmapData.Stride * sourceY, 4 * sourceBitmap.Width); // Make a Span for the destination dib pixels diff --git a/src/Greenshot.Editor/FileFormatHandlers/GreenshotFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/GreenshotFileFormatHandler.cs index 0b956c001..1f92a756b 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/GreenshotFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/GreenshotFileFormatHandler.cs @@ -36,7 +36,7 @@ namespace Greenshot.Editor.FileFormatHandlers public class GreenshotFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler { private static readonly ILog Log = LogManager.GetLogger(typeof(GreenshotFileFormatHandler)); - private readonly IReadOnlyCollection _ourExtensions = new [] { ".greenshot" }; + private readonly IReadOnlyCollection _ourExtensions = new[] { ".greenshot" }; public GreenshotFileFormatHandler() { SupportedExtensions[FileFormatHandlerActions.LoadDrawableFromStream] = _ourExtensions; @@ -54,9 +54,9 @@ namespace Greenshot.Editor.FileFormatHandlers try { bitmap.Save(stream, ImageFormat.Png); - using MemoryStream tmpStream = new MemoryStream(); + using MemoryStream tmpStream = new(); long bytesWritten = surface.SaveElementsToStream(tmpStream); - using BinaryWriter writer = new BinaryWriter(tmpStream); + using BinaryWriter writer = new(tmpStream); writer.Write(bytesWritten); Version v = Assembly.GetExecutingAssembly().GetName().Version; byte[] marker = Encoding.ASCII.GetBytes($"Greenshot{v.Major:00}.{v.Minor:00}"); @@ -115,7 +115,7 @@ namespace Greenshot.Editor.FileFormatHandlers Log.InfoFormat("Greenshot file format: {0}", greenshotMarker); const int fileSizeLocation = 8 + markerSize; surfaceFileStream.Seek(-fileSizeLocation, SeekOrigin.End); - using BinaryReader reader = new BinaryReader(surfaceFileStream); + using BinaryReader reader = new(surfaceFileStream); long bytesWritten = reader.ReadInt64(); surfaceFileStream.Seek(-(bytesWritten + fileSizeLocation), SeekOrigin.End); returnSurface.LoadElementsFromStream(surfaceFileStream); diff --git a/src/Greenshot.Editor/FileFormatHandlers/IconFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/IconFileFormatHandler.cs index d2769d5f0..514a7d643 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/IconFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/IconFileFormatHandler.cs @@ -161,7 +161,7 @@ namespace Greenshot.Editor.FileFormatHandlers // No vista icon, try normal icon stream.Position = stream.Seek(0, SeekOrigin.Begin); // We create a copy of the bitmap, so everything else can be disposed - using Icon tmpIcon = new Icon(stream, new Size(1024, 1024)); + using Icon tmpIcon = new(stream, new Size(1024, 1024)); using Image tmpImage = tmpIcon.ToBitmap(); bitmap = ImageHelper.Clone(tmpImage, PixelFormat.Format32bppArgb); return true; @@ -194,13 +194,13 @@ namespace Greenshot.Editor.FileFormatHandlers int iCount = BitConverter.ToInt16(srcBuf, 4); for (int iIndex = 0; iIndex < iCount; iIndex++) { - int iWidth = srcBuf[sizeIconDir + sizeIconDirEntry * iIndex]; - int iHeight = srcBuf[sizeIconDir + sizeIconDirEntry * iIndex + 1]; + int iWidth = srcBuf[sizeIconDir + (sizeIconDirEntry * iIndex)]; + int iHeight = srcBuf[sizeIconDir + (sizeIconDirEntry * iIndex) + 1]; if (iWidth != 0 || iHeight != 0) continue; - int iImageSize = BitConverter.ToInt32(srcBuf, sizeIconDir + sizeIconDirEntry * iIndex + 8); - int iImageOffset = BitConverter.ToInt32(srcBuf, sizeIconDir + sizeIconDirEntry * iIndex + 12); - using MemoryStream destStream = new MemoryStream(); + int iImageSize = BitConverter.ToInt32(srcBuf, sizeIconDir + (sizeIconDirEntry * iIndex) + 8); + int iImageOffset = BitConverter.ToInt32(srcBuf, sizeIconDir + (sizeIconDirEntry * iIndex) + 12); + using MemoryStream destStream = new(); destStream.Write(srcBuf, iImageOffset, iImageSize); destStream.Seek(0, SeekOrigin.Begin); bmpPngExtracted = new Bitmap(destStream); // This is PNG! :) diff --git a/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs index 04c3825b3..09b52b6b3 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs @@ -37,7 +37,7 @@ namespace Greenshot.Editor.FileFormatHandlers public class MetaFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler { private readonly IReadOnlyCollection _ourExtensions = new[] { ".wmf", ".emf" }; - + public MetaFileFormatHandler() { SupportedExtensions[FileFormatHandlerActions.LoadDrawableFromStream] = _ourExtensions; diff --git a/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs index 2d655bb1b..9d81d394b 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs @@ -42,9 +42,9 @@ namespace Greenshot.Editor.FileFormatHandlers private const string HeifDecoder = "{E9A4A80A-44FE-4DE4-8971-7150B10A5199}"; private const string WicDecoderCategory = "{7ED96837-96F0-4812-B211-F13C24117ED3}"; - private IReadOnlyCollection LoadFromStreamExtensions { get; } = new []{ ".jxr", ".dds", ".hdp", ".wdp", ".wmp"}; + private IReadOnlyCollection LoadFromStreamExtensions { get; } = new[] { ".jxr", ".dds", ".hdp", ".wdp", ".wmp" }; private IReadOnlyCollection SaveToStreamExtensions { get; } = new[] { ".jxr" }; - + public WpfFileFormatHandler() { LoadFromStreamExtensions = LoadFromStreamExtensions.ToList().Concat(RetrieveSupportedExtensions()).OrderBy(e => e).Distinct().ToArray(); diff --git a/src/Greenshot.Editor/Forms/ColorDialog.cs b/src/Greenshot.Editor/Forms/ColorDialog.cs index 2a146012a..5b30e64e2 100644 --- a/src/Greenshot.Editor/Forms/ColorDialog.cs +++ b/src/Greenshot.Editor/Forms/ColorDialog.cs @@ -54,9 +54,9 @@ namespace Greenshot.Editor.Forms public static ColorDialog GetInstance() => _instance; - private readonly List private void ShowSettings() { - trackBar1.Value = (int) (_effect.Darkness * 40); + trackBar1.Value = (int)(_effect.Darkness * 40); offsetX.Value = _effect.ShadowOffset.X; offsetY.Value = _effect.ShadowOffset.Y; thickness.Value = _effect.ShadowSize; @@ -51,9 +51,9 @@ namespace Greenshot.Editor.Forms private void ButtonOK_Click(object sender, EventArgs e) { - _effect.Darkness = trackBar1.Value / (float) 40; - _effect.ShadowOffset = new NativePoint((int) offsetX.Value, (int) offsetY.Value); - _effect.ShadowSize = (int) thickness.Value; + _effect.Darkness = trackBar1.Value / (float)40; + _effect.ShadowOffset = new NativePoint((int)offsetX.Value, (int)offsetY.Value); + _effect.ShadowSize = (int)thickness.Value; DialogResult = DialogResult.OK; } } diff --git a/src/Greenshot.Editor/Forms/ImageEditorForm.cs b/src/Greenshot.Editor/Forms/ImageEditorForm.cs index 87c3813c7..816f9234d 100644 --- a/src/Greenshot.Editor/Forms/ImageEditorForm.cs +++ b/src/Greenshot.Editor/Forms/ImageEditorForm.cs @@ -100,7 +100,7 @@ namespace Greenshot.Editor.Forms { try { - EditorList.Sort((e1, e2) => string.Compare(e1.Surface.CaptureDetails.Title, e2.Surface.CaptureDetails.Title, StringComparison.Ordinal)); + EditorList.Sort((e1, e2) => string.CompareOrdinal(e1.Surface.CaptureDetails.Title, e2.Surface.CaptureDetails.Title)); } catch (Exception ex) { @@ -223,7 +223,7 @@ namespace Greenshot.Editor.Forms /// private void SetSurface(ISurface newSurface) { - if (Surface != null && Surface.Modified) + if (Surface?.Modified == true) { throw new ApplicationException("Surface modified"); } @@ -308,7 +308,7 @@ namespace Greenshot.Editor.Forms /// private void PropertiesToolStrip_Paint(object sender, PaintEventArgs e) { - using Pen cbBorderPen = new Pen(SystemColors.ActiveBorder); + using Pen cbBorderPen = new(SystemColors.ActiveBorder); // Loop over all items in the propertiesToolStrip foreach (ToolStripItem item in propertiesToolStrip.Items) { @@ -333,7 +333,7 @@ namespace Greenshot.Editor.Forms /// private void AddDestinations() { - Invoke((MethodInvoker) delegate + Invoke((MethodInvoker)delegate { // Create export buttons foreach (IDestination destination in DestinationHelper.GetAllDestinations()) @@ -379,7 +379,7 @@ namespace Greenshot.Editor.Forms }; //ToolStripDropDownButton destinationButton = new ToolStripDropDownButton(); - ToolStripMenuItem defaultItem = new ToolStripMenuItem(toolstripDestination.Description) + ToolStripMenuItem defaultItem = new(toolstripDestination.Description) { Tag = toolstripDestination, Image = toolstripDestination.DisplayIcon @@ -395,7 +395,7 @@ namespace Greenshot.Editor.Forms ClearItems(destinationButton.DropDownItems); destinationButton.DropDownItems.Add(defaultItem); - List subDestinations = new List(); + List subDestinations = new(); subDestinations.AddRange(toolstripDestination.DynamicDestinations()); if (subDestinations.Count > 0) { @@ -403,7 +403,7 @@ namespace Greenshot.Editor.Forms foreach (IDestination subDestination in subDestinations) { IDestination closureFixedDestination = subDestination; - ToolStripMenuItem destinationMenuItem = new ToolStripMenuItem(closureFixedDestination.Description) + ToolStripMenuItem destinationMenuItem = new(closureFixedDestination.Description) { Tag = closureFixedDestination, Image = closureFixedDestination.DisplayIcon @@ -418,7 +418,7 @@ namespace Greenshot.Editor.Forms } else { - ToolStripButton destinationButton = new ToolStripButton(); + ToolStripButton destinationButton = new(); destinationsToolStrip.Items.Insert(destinationsToolStrip.Items.IndexOf(toolStripSeparator16), destinationButton); destinationButton.DisplayStyle = ToolStripItemDisplayStyle.Image; destinationButton.Size = new Size(23, 22); @@ -519,7 +519,7 @@ namespace Greenshot.Editor.Forms { _surface.FieldAggregator.GetField(FieldType.LINE_COLOR).Value = eventArgs.Color; } - + /// /// This is called when the background color of the select element chances, used for shortcuts /// @@ -529,7 +529,7 @@ namespace Greenshot.Editor.Forms { _surface.FieldAggregator.GetField(FieldType.FILL_COLOR).Value = eventArgs.Color; } - + /// /// This is called when the line thickness of the select element chances, used for shortcuts /// @@ -539,7 +539,7 @@ namespace Greenshot.Editor.Forms { _surface.FieldAggregator.GetField(FieldType.LINE_THICKNESS).Value = eventArgs.Thickness; } - + /// /// This is called when the shadow of the select element chances, used for shortcuts /// @@ -663,7 +663,7 @@ namespace Greenshot.Editor.Forms private void BtnPrintClick(object sender, EventArgs e) { // The BeginInvoke is a solution for the printdialog not having focus - BeginInvoke((MethodInvoker) delegate { DestinationHelper.ExportCapture(true, WellKnownDestinations.Printer, _surface, _surface.CaptureDetails); }); + BeginInvoke((MethodInvoker)delegate { DestinationHelper.ExportCapture(true, WellKnownDestinations.Printer, _surface, _surface.CaptureDetails); }); } private void CloseToolStripMenuItemClick(object sender, EventArgs e) @@ -894,7 +894,6 @@ namespace Greenshot.Editor.Forms _surface.PushElementsToBottom(); } - private void HelpToolStripMenuItem1Click(object sender, EventArgs e) { HelpFileLoader.LoadHelp(); @@ -1122,12 +1121,7 @@ namespace Greenshot.Editor.Forms protected override bool ProcessKeyPreview(ref Message msg) { // disable default key handling if surface has requested a lock - if (!_surface.KeysLocked) - { - return base.ProcessKeyPreview(ref msg); - } - - return false; + return !_surface.KeysLocked && base.ProcessKeyPreview(ref msg); } protected override bool ProcessCmdKey(ref Message msg, Keys keys) @@ -1242,7 +1236,7 @@ namespace Greenshot.Editor.Forms private void StatusLabelClicked(object sender, MouseEventArgs e) { - ToolStrip ss = (StatusStrip) ((ToolStripStatusLabel) sender).Owner; + ToolStrip ss = (StatusStrip)((ToolStripStatusLabel)sender).Owner; ss.ContextMenuStrip?.Show(ss, e.X, e.Y); } @@ -1316,7 +1310,7 @@ namespace Greenshot.Editor.Forms shadowButton.Visible = props.HasFieldValue(FieldType.SHADOW); counterLabel.Visible = counterUpDown.Visible = props.HasFieldValue(FieldType.FLAGS) && ((FieldFlag)props.GetFieldValue(FieldType.FLAGS)).HasFlag(FieldFlag.COUNTER); - btnConfirm.Visible = btnCancel.Visible = props.HasFieldValue(FieldType.FLAGS) && ((FieldFlag) props.GetFieldValue(FieldType.FLAGS)).HasFlag(FieldFlag.CONFIRMABLE); + btnConfirm.Visible = btnCancel.Visible = props.HasFieldValue(FieldType.FLAGS) && ((FieldFlag)props.GetFieldValue(FieldType.FLAGS)).HasFlag(FieldFlag.CONFIRMABLE); btnConfirm.Enabled = _surface.HasSelectedElements; obfuscateModeButton.Visible = props.HasFieldValue(FieldType.PREPARED_FILTER_OBFUSCATE); @@ -1348,11 +1342,11 @@ namespace Greenshot.Editor.Forms Image icon; if (stepLabels <= 20) { - icon = (Image) resources.GetObject($"btnStepLabel{stepLabels:00}.Image"); + icon = (Image)resources.GetObject($"btnStepLabel{stepLabels:00}.Image"); } else { - icon = (Image) resources.GetObject("btnStepLabel20+.Image"); + icon = (Image)resources.GetObject("btnStepLabel20+.Image"); } btnStepLabel.Image = icon; @@ -1361,7 +1355,7 @@ namespace Greenshot.Editor.Forms FieldAggregator props = (FieldAggregator)_surface.FieldAggregator; // if a confirmable element is selected, we must disable most of the controls // since we demand confirmation or cancel for confirmable element - if (props.HasFieldValue(FieldType.FLAGS) && ((FieldFlag) props.GetFieldValue(FieldType.FLAGS) & FieldFlag.CONFIRMABLE) == FieldFlag.CONFIRMABLE) + if (props.HasFieldValue(FieldType.FLAGS) && ((FieldFlag)props.GetFieldValue(FieldType.FLAGS) & FieldFlag.CONFIRMABLE) == FieldFlag.CONFIRMABLE) { // disable most controls if (!_controlsDisabledDueToConfirmable) @@ -1406,10 +1400,9 @@ namespace Greenshot.Editor.Forms RefreshFieldControls(); } - private void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) { - _surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination) ((ToolStripMenuItem) sender).Tag; + _surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; } private void EditToolStripMenuItemClick(object sender, EventArgs e) @@ -1510,7 +1503,7 @@ namespace Greenshot.Editor.Forms private void SaveElementsToolStripMenuItemClick(object sender, EventArgs e) { - SaveFileDialog saveFileDialog = new SaveFileDialog + SaveFileDialog saveFileDialog = new() { Filter = "Greenshot templates (*.gst)|*.gst", FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(coreConfiguration.OutputFileFilenamePattern, _surface.CaptureDetails) @@ -1525,7 +1518,7 @@ namespace Greenshot.Editor.Forms private void LoadElementsToolStripMenuItemClick(object sender, EventArgs e) { - OpenFileDialog openFileDialog = new OpenFileDialog + OpenFileDialog openFileDialog = new() { Filter = "Greenshot templates (*.gst)|*.gst" }; @@ -1552,19 +1545,19 @@ namespace Greenshot.Editor.Forms return; } - clickedDestination = (IDestination) clickedControl.Tag; + clickedDestination = (IDestination)clickedControl.Tag; } else { if (sender is ToolStripMenuItem item) { ToolStripMenuItem clickedMenuItem = item; - clickedDestination = (IDestination) clickedMenuItem.Tag; + clickedDestination = (IDestination)clickedMenuItem.Tag; } } ExportInformation exportInformation = clickedDestination?.ExportCapture(true, _surface, _surface.CaptureDetails); - if (exportInformation != null && exportInformation.ExportMade) + if (exportInformation?.ExportMade == true) { _surface.Modified = false; } @@ -1577,9 +1570,9 @@ namespace Greenshot.Editor.Forms } protected void CropStyleDropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) - { + { InitCropMode((CropContainer.CropModes)e.ClickedItem.Tag); - + RefreshFieldControls(); Invalidate(true); } @@ -1598,8 +1591,8 @@ namespace Greenshot.Editor.Forms //not AutoCrop possible automatic switch to default crop mode _surface.DrawingMode = DrawingModes.Crop; _surface.FieldAggregator.GetField(FieldType.CROPMODE).Value = CropContainer.CropModes.Default; - this.cropModeButton.SelectedTag = CropContainer.CropModes.Default; - this.statusLabel.Text = Language.GetString(LangKey.editor_autocrop_not_possible); + cropModeButton.SelectedTag = CropContainer.CropModes.Default; + statusLabel.Text = Language.GetString(LangKey.editor_autocrop_not_possible); } } else @@ -1614,7 +1607,6 @@ namespace Greenshot.Editor.Forms _surface.SelectAllElements(); } - private void BtnConfirmClick(object sender, EventArgs e) { _surface.Confirm(true); @@ -1629,17 +1621,17 @@ namespace Greenshot.Editor.Forms private void Insert_window_toolstripmenuitemMouseEnter(object sender, EventArgs e) { - ToolStripMenuItem captureWindowMenuItem = (ToolStripMenuItem) sender; + ToolStripMenuItem captureWindowMenuItem = (ToolStripMenuItem)sender; var mainForm = SimpleServiceProvider.Current.GetInstance(); mainForm.AddCaptureWindowMenuItems(captureWindowMenuItem, Contextmenu_window_Click); } private void Contextmenu_window_Click(object sender, EventArgs e) { - ToolStripMenuItem clickedItem = (ToolStripMenuItem) sender; + ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender; try { - WindowDetails windowToCapture = (WindowDetails) clickedItem.Tag; + WindowDetails windowToCapture = (WindowDetails)clickedItem.Tag; ICapture capture = new Capture(); using (Graphics graphics = Graphics.FromHwnd(Handle)) { @@ -1654,8 +1646,8 @@ namespace Greenshot.Editor.Forms capture = captureHelper.CaptureWindow(windowToCapture, capture, coreConfiguration.WindowCaptureMode); if (capture?.CaptureDetails != null && capture.Image != null) { - ((Bitmap) capture.Image).SetResolution(capture.CaptureDetails.DpiX, capture.CaptureDetails.DpiY); - _surface.AddImageContainer((Bitmap) capture.Image, 100, 100); + ((Bitmap)capture.Image).SetResolution(capture.CaptureDetails.DpiX, capture.CaptureDetails.DpiY); + _surface.AddImageContainer((Bitmap)capture.Image, 100, 100); } Activate(); @@ -1736,7 +1728,6 @@ namespace Greenshot.Editor.Forms } } - /// /// Open the resize settings from, and resize if ok was pressed /// @@ -1827,7 +1818,7 @@ namespace Greenshot.Editor.Forms var canvas = Surface as Control; Size canvasSize = canvas.Size; Size currentClientSize = panel1.ClientSize; - Panel panel = (Panel) canvas?.Parent; + Panel panel = (Panel)canvas?.Parent; if (panel == null) { return; @@ -1837,7 +1828,7 @@ namespace Greenshot.Editor.Forms int offsetY = -panel.VerticalScroll.Value; if (currentClientSize.Width > canvasSize.Width) { - canvas.Left = offsetX + (currentClientSize.Width - canvasSize.Width) / 2; + canvas.Left = offsetX + ((currentClientSize.Width - canvasSize.Width) / 2); } else { @@ -1846,7 +1837,7 @@ namespace Greenshot.Editor.Forms if (currentClientSize.Height > canvasSize.Height) { - canvas.Top = offsetY + (currentClientSize.Height - canvasSize.Height) / 2; + canvas.Top = offsetY + ((currentClientSize.Height - canvasSize.Height) / 2); } else { @@ -1871,8 +1862,8 @@ namespace Greenshot.Editor.Forms newHeight = Math.Min(newHeight, maxWindowSize.Height); // Lower bound. Don't make it smaller than a fixed value. - int minimumFormWidth = 650; - int minimumFormHeight = 530; + const int minimumFormWidth = 650; + const int minimumFormHeight = 530; newWidth = Math.Max(minimumFormWidth, newWidth); newHeight = Math.Max(minimumFormHeight, newHeight); @@ -1890,14 +1881,9 @@ namespace Greenshot.Editor.Forms var screen = Screen.FromControl(this); var screenBounds = screen.Bounds; var workingArea = screen.WorkingArea; - if (Left > screenBounds.Left && Top > screenBounds.Top) - { - return new Size(workingArea.Right - Left, workingArea.Bottom - Top); - } - else - { - return workingArea.Size; - } + return Left > screenBounds.Left && Top > screenBounds.Top + ? new Size(workingArea.Right - Left, workingArea.Bottom - Top) + : workingArea.Size; } private void ZoomInMenuItemClick(object sender, EventArgs e) @@ -1920,8 +1906,8 @@ namespace Greenshot.Editor.Forms private void ZoomSetValueMenuItemClick(object sender, EventArgs e) { - var senderMenuItem = (ToolStripMenuItem) sender; - var nextValue = Fraction.Parse((string) senderMenuItem.Tag); + var senderMenuItem = (ToolStripMenuItem)sender; + var nextValue = Fraction.Parse((string)senderMenuItem.Tag); ZoomSetValue(nextValue); } @@ -1934,7 +1920,7 @@ namespace Greenshot.Editor.Forms var imageSize = Surface.Image.Size; static bool isFit(Fraction scale, int source, int boundary) - => (int) (source * scale) <= boundary; + => (int)(source * scale) <= boundary; var nextIndex = Array.FindLastIndex( ZOOM_VALUES, @@ -1985,8 +1971,8 @@ namespace Greenshot.Editor.Forms } } - var horizontalCenter = 1.0 * (rc.Left + rc.Width / 2) / size.Width; - var verticalCenter = 1.0 * (rc.Top + rc.Height / 2) / size.Height; + var horizontalCenter = 1.0 * (rc.Left + (rc.Width / 2)) / size.Width; + var verticalCenter = 1.0 * (rc.Top + (rc.Height / 2)) / size.Height; // Set the new zoom value Surface.ZoomFactor = value; @@ -1994,7 +1980,7 @@ namespace Greenshot.Editor.Forms AlignCanvasPositionAfterResize(); // Update zoom controls - zoomStatusDropDownBtn.Text = ((int) (100 * (double) value)).ToString() + "%"; + zoomStatusDropDownBtn.Text = ((int)(100 * (double)value)).ToString() + "%"; var valueString = value.ToString(); foreach (var item in zoomMenuStrip.Items) { @@ -2008,8 +1994,8 @@ namespace Greenshot.Editor.Forms rc = surface.GetVisibleRectangle(); size = surface.Size; panel.AutoScrollPosition = new Point( - (int) (horizontalCenter * size.Width) - rc.Width / 2, - (int) (verticalCenter * size.Height) - rc.Height / 2 + (int)(horizontalCenter * size.Width) - (rc.Width / 2), + (int)(verticalCenter * size.Height) - (rc.Height / 2) ); } } diff --git a/src/Greenshot.Editor/Forms/MovableShowColorForm.cs b/src/Greenshot.Editor/Forms/MovableShowColorForm.cs index 416ec6407..a07d283e6 100644 --- a/src/Greenshot.Editor/Forms/MovableShowColorForm.cs +++ b/src/Greenshot.Editor/Forms/MovableShowColorForm.cs @@ -107,7 +107,7 @@ namespace Greenshot.Editor.Forms try { uint pixel = Gdi32Api.GetPixel(safeWindowDcHandle, screenCoordinates.X, screenCoordinates.Y); - Color color = Color.FromArgb(255, (int) (pixel & 0xFF), (int) (pixel & 0xFF00) >> 8, (int) (pixel & 0xFF0000) >> 16); + Color color = Color.FromArgb(255, (int)(pixel & 0xFF), (int)(pixel & 0xFF00) >> 8, (int)(pixel & 0xFF0000) >> 16); return color; } catch (Exception) diff --git a/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs b/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs index f15a56d5f..5af9f6679 100644 --- a/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs +++ b/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs @@ -64,8 +64,8 @@ namespace Greenshot.Editor.Forms const double tolerance = 3 * double.Epsilon; if (Math.Abs(_newWidth - _effect.Width) > tolerance || Math.Abs(_newHeight - _effect.Height) > tolerance) { - _effect.Width = (int) _newWidth; - _effect.Height = (int) _newHeight; + _effect.Width = (int)_newWidth; + _effect.Height = (int)_newHeight; _effect.MaintainAspectRatio = checkbox_aspectratio.Checked; DialogResult = DialogResult.OK; } @@ -100,7 +100,7 @@ namespace Greenshot.Editor.Forms displayValue = _newWidth; } - textbox_width.Text = ((int) displayValue).ToString(); + textbox_width.Text = ((int)displayValue).ToString(); } private void DisplayHeight() @@ -115,7 +115,7 @@ namespace Greenshot.Editor.Forms displayValue = _newHeight; } - textbox_height.Text = ((int) displayValue).ToString(); + textbox_height.Text = ((int)displayValue).ToString(); } private void Textbox_KeyUp(object sender, KeyEventArgs e) @@ -194,7 +194,7 @@ namespace Greenshot.Editor.Forms } /// - /// + /// /// /// /// diff --git a/src/Greenshot.Editor/Forms/TornEdgeSettingsForm.cs b/src/Greenshot.Editor/Forms/TornEdgeSettingsForm.cs index 46638fc6e..9d33a0543 100644 --- a/src/Greenshot.Editor/Forms/TornEdgeSettingsForm.cs +++ b/src/Greenshot.Editor/Forms/TornEdgeSettingsForm.cs @@ -41,7 +41,7 @@ namespace Greenshot.Editor.Forms { shadowCheckbox.Checked = _effect.GenerateShadow; // Fix to prevent BUG-1753 - shadowDarkness.Value = Math.Max(shadowDarkness.Minimum, Math.Min(shadowDarkness.Maximum, (int) (_effect.Darkness * shadowDarkness.Maximum))); + shadowDarkness.Value = Math.Max(shadowDarkness.Minimum, Math.Min(shadowDarkness.Maximum, (int)(_effect.Darkness * shadowDarkness.Maximum))); offsetX.Value = _effect.ShadowOffset.X; offsetY.Value = _effect.ShadowOffset.Y; toothsize.Value = _effect.ToothHeight; @@ -55,12 +55,12 @@ namespace Greenshot.Editor.Forms private void ButtonOK_Click(object sender, EventArgs e) { - _effect.Darkness = shadowDarkness.Value / (float) 40; - _effect.ShadowOffset = new NativePoint((int) offsetX.Value, (int) offsetY.Value); - _effect.ShadowSize = (int) thickness.Value; - _effect.ToothHeight = (int) toothsize.Value; - _effect.VerticalToothRange = (int) verticaltoothrange.Value; - _effect.HorizontalToothRange = (int) horizontaltoothrange.Value; + _effect.Darkness = shadowDarkness.Value / (float)40; + _effect.ShadowOffset = new NativePoint((int)offsetX.Value, (int)offsetY.Value); + _effect.ShadowSize = (int)thickness.Value; + _effect.ToothHeight = (int)toothsize.Value; + _effect.VerticalToothRange = (int)verticaltoothrange.Value; + _effect.HorizontalToothRange = (int)horizontaltoothrange.Value; _effect.Edges = new[] { top.Checked, right.Checked, bottom.Checked, left.Checked @@ -77,7 +77,6 @@ namespace Greenshot.Editor.Forms shadowDarkness.Enabled = shadowCheckbox.Checked; } - private void all_CheckedChanged(object sender, EventArgs e) { AnySideChangeChecked(top, all.Checked); diff --git a/src/Greenshot.Editor/Helpers/Colors.cs b/src/Greenshot.Editor/Helpers/Colors.cs index 52a32ba34..74ffe9aad 100644 --- a/src/Greenshot.Editor/Helpers/Colors.cs +++ b/src/Greenshot.Editor/Helpers/Colors.cs @@ -50,12 +50,7 @@ namespace Greenshot.Editor.Helpers } } - if (count == 0) - { - return Color.Empty; - } - - return Color.FromArgb(a / count, r / count, g / count, b / count); + return count == 0 ? Color.Empty : Color.FromArgb(a / count, r / count, g / count, b / count); } } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Helpers/GeometryHelper.cs b/src/Greenshot.Editor/Helpers/GeometryHelper.cs index 274e1fa02..2c104bfa2 100644 --- a/src/Greenshot.Editor/Helpers/GeometryHelper.cs +++ b/src/Greenshot.Editor/Helpers/GeometryHelper.cs @@ -45,7 +45,7 @@ namespace Greenshot.Editor.Helpers //Add both of the parts together double underRadical = part1 + part2; //Get the square root of the parts - return (int) Math.Sqrt(underRadical); + return (int)Math.Sqrt(underRadical); } /// diff --git a/src/Greenshot.Editor/Helpers/ScaleHelper.cs b/src/Greenshot.Editor/Helpers/ScaleHelper.cs index 8403bd939..567a8c4f1 100644 --- a/src/Greenshot.Editor/Helpers/ScaleHelper.cs +++ b/src/Greenshot.Editor/Helpers/ScaleHelper.cs @@ -94,22 +94,20 @@ namespace Greenshot.Editor.Helpers if ((options & ScaleOptions.Centered) == ScaleOptions.Centered) { // store center coordinates of rectangle - float rectCenterX = originalRectangle.Left + originalRectangle.Width / 2; - float rectCenterY = originalRectangle.Top + originalRectangle.Height / 2; + float rectCenterX = originalRectangle.Left + (originalRectangle.Width / 2); + float rectCenterY = originalRectangle.Top + (originalRectangle.Height / 2); // scale rectangle using handle coordinates originalRectangle = Scale(originalRectangle, resizeHandlePosition, resizeHandleCoords); // mirror handle coordinates via rectangle center coordinates resizeHandleCoords = resizeHandleCoords.Offset(-2 * (resizeHandleCoords.X - rectCenterX), -2 * (resizeHandleCoords.Y - rectCenterY)); // scale again with opposing handle and mirrored coordinates - resizeHandlePosition = (Positions) ((((int) resizeHandlePosition) + 4) % 8); - originalRectangle = Scale(originalRectangle, resizeHandlePosition, resizeHandleCoords); + resizeHandlePosition = (Positions)((((int)resizeHandlePosition) + 4) % 8); + return Scale(originalRectangle, resizeHandlePosition, resizeHandleCoords); } else { - originalRectangle = Scale(originalRectangle, resizeHandlePosition, resizeHandleCoords); + return Scale(originalRectangle, resizeHandlePosition, resizeHandleCoords); } - - return originalRectangle; } /// @@ -127,8 +125,10 @@ namespace Greenshot.Editor.Helpers Positions.TopCenter => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, originalRectangle.Width, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), Positions.TopRight => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), Positions.MiddleLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, originalRectangle.Height), - Positions.MiddleRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Height), Positions.BottomLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, resizeHandleCoords.Y - originalRectangle.Top), - Positions.BottomCenter => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, originalRectangle.Width, resizeHandleCoords.Y - originalRectangle.Top), Positions.BottomRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, resizeHandleCoords.Y - originalRectangle.Top), + Positions.MiddleRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Height), + Positions.BottomLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, resizeHandleCoords.Y - originalRectangle.Top), + Positions.BottomCenter => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, originalRectangle.Width, resizeHandleCoords.Y - originalRectangle.Top), + Positions.BottomRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, resizeHandleCoords.Y - originalRectangle.Top), _ => throw new ArgumentException("Position cannot be handled: " + resizeHandlePosition) }; } @@ -152,26 +152,22 @@ namespace Greenshot.Editor.Helpers case Positions.TopLeft: selectedRectangle = new NativeSizeFloat(originalRectangle.Right - resizeHandleCoords.X, originalRectangle.Bottom - resizeHandleCoords.Y); newSize = GetNewSizeForRationalScale(originalRectangle.Size, selectedRectangle); - resizeHandleCoords = new NativePointFloat(originalRectangle.Right - newSize.Width, originalRectangle.Bottom - newSize.Height); - break; + return new NativePointFloat(originalRectangle.Right - newSize.Width, originalRectangle.Bottom - newSize.Height); case Positions.TopRight: selectedRectangle = new NativeSizeFloat(resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Bottom - resizeHandleCoords.Y); newSize = GetNewSizeForRationalScale(originalRectangle.Size, selectedRectangle); - resizeHandleCoords = new NativePointFloat(originalRectangle.Left + newSize.Width, originalRectangle.Bottom - newSize.Height); - break; + return new NativePointFloat(originalRectangle.Left + newSize.Width, originalRectangle.Bottom - newSize.Height); case Positions.BottomLeft: selectedRectangle = new NativeSizeFloat(originalRectangle.Right - resizeHandleCoords.X, resizeHandleCoords.Y - originalRectangle.Top); newSize = GetNewSizeForRationalScale(originalRectangle.Size, selectedRectangle); - resizeHandleCoords = new NativePointFloat(originalRectangle.Right - newSize.Width, originalRectangle.Top + newSize.Height); - break; + return new NativePointFloat(originalRectangle.Right - newSize.Width, originalRectangle.Top + newSize.Height); case Positions.BottomRight: selectedRectangle = new NativeSizeFloat(resizeHandleCoords.X - originalRectangle.Left, resizeHandleCoords.Y - originalRectangle.Top); newSize = GetNewSizeForRationalScale(originalRectangle.Size, selectedRectangle); - resizeHandleCoords = new NativePointFloat(originalRectangle.Left + newSize.Width, originalRectangle.Top + newSize.Height); - break; + return new NativePointFloat(originalRectangle.Left + newSize.Width, originalRectangle.Top + newSize.Height); } return resizeHandleCoords; @@ -196,13 +192,13 @@ namespace Greenshot.Editor.Helpers { // scaled rectangle (ratio) would be wider than original // keep height and tweak width to maintain aspect ratio - newSize = newSize.ChangeWidth(selectedSize.Height * originalRatio * flippedRatioSign); + return newSize.ChangeWidth(selectedSize.Height * originalRatio * flippedRatioSign); } else if (Math.Abs(selectedRatio) < Math.Abs(originalRatio)) { // scaled rectangle (ratio) would be taller than original // keep width and tweak height to maintain aspect ratio - newSize = newSize.ChangeWidth(selectedSize.Width / originalRatio * flippedRatioSign); + return newSize.ChangeWidth(selectedSize.Width / originalRatio * flippedRatioSign); } return newSize; @@ -238,7 +234,7 @@ namespace Greenshot.Editor.Helpers result = result .ChangeWidth((int)Math.Round(dist * Math.Cos(angle / 180 * Math.PI))) - .ChangeHeight((int) Math.Round(dist * Math.Sin(angle / 180 * Math.PI))); + .ChangeHeight((int)Math.Round(dist * Math.Sin(angle / 180 * Math.PI))); } if (centeredScale) diff --git a/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs b/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs index ba173df9f..7fcd1284d 100644 --- a/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs +++ b/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs @@ -33,7 +33,7 @@ namespace Greenshot.Editor.Helpers public double Process(double angle) { - return Math.Round((angle + 45) / 90) * 90 - 45; + return (Math.Round((angle + 45) / 90) * 90) - 45; } } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs b/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs index 1d2825fc0..257e362c2 100644 --- a/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs +++ b/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs @@ -26,7 +26,7 @@ namespace Greenshot.Editor.Helpers { /// /// Enables or disables toolstrip items, taking care of the hierarchy. - /// (parent) OwnerItems are ENabled with ToolStripItems, + /// (parent) OwnerItems are ENabled with ToolStripItems, /// (child) DropDownItems are ENabled and DISabled with ToolStripItems. /// public static class ToolStripItemEndisabler @@ -58,7 +58,7 @@ namespace Greenshot.Editor.Helpers } /// - /// Enables the ToolStripItem, including children (ToolStripDropDownItem) + /// Enables the ToolStripItem, including children (ToolStripDropDownItem) /// and ancestor (OwnerItem) /// public static void Enable(ToolStripItem tsi) diff --git a/src/Greenshot.Editor/Memento/AddElementMemento.cs b/src/Greenshot.Editor/Memento/AddElementMemento.cs index b76858780..f9d60b7fb 100644 --- a/src/Greenshot.Editor/Memento/AddElementMemento.cs +++ b/src/Greenshot.Editor/Memento/AddElementMemento.cs @@ -62,7 +62,7 @@ namespace Greenshot.Editor.Memento _drawableContainer.Invalidate(); // Store the selected state, as it's overwritten by the RemoveElement - DeleteElementMemento oldState = new DeleteElementMemento(_surface, _drawableContainer); + DeleteElementMemento oldState = new(_surface, _drawableContainer); _surface.RemoveElement(_drawableContainer, false); _drawableContainer.Selected = true; diff --git a/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs b/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs index 70dba9252..bf5db52f3 100644 --- a/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs +++ b/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs @@ -58,16 +58,14 @@ namespace Greenshot.Editor.Memento { if (otherMemento is not ChangeFieldHolderMemento other) return false; - if (!other._drawableContainer.Equals(_drawableContainer)) return false; - - return other._fieldToBeChanged.Equals(_fieldToBeChanged); + return other._drawableContainer.Equals(_drawableContainer) && other._fieldToBeChanged.Equals(_fieldToBeChanged); } public IMemento Restore() { // Before _drawableContainer.Invalidate(); - ChangeFieldHolderMemento oldState = new ChangeFieldHolderMemento(_drawableContainer, _fieldToBeChanged); + ChangeFieldHolderMemento oldState = new(_drawableContainer, _fieldToBeChanged); _fieldToBeChanged.Value = _oldValue; // After _drawableContainer.Invalidate(); diff --git a/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs b/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs index 8c49614b4..a55c140f4 100644 --- a/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs +++ b/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs @@ -78,7 +78,7 @@ namespace Greenshot.Editor.Memento public IMemento Restore() { - SurfaceBackgroundChangeMemento oldState = new SurfaceBackgroundChangeMemento(_surface, _matrix); + SurfaceBackgroundChangeMemento oldState = new(_surface, _matrix); _surface.UndoBackgroundChange(_image, _matrix); _surface.Invalidate(); return oldState; diff --git a/src/Greenshot.Editor/Memento/TextChangeMemento.cs b/src/Greenshot.Editor/Memento/TextChangeMemento.cs index 46f33592b..71cc9ba99 100644 --- a/src/Greenshot.Editor/Memento/TextChangeMemento.cs +++ b/src/Greenshot.Editor/Memento/TextChangeMemento.cs @@ -53,16 +53,14 @@ namespace Greenshot.Editor.Memento public bool Merge(IMemento otherMemento) { - if (otherMemento is not TextChangeMemento other) return false; - - return other._textContainer.Equals(_textContainer); + return otherMemento is TextChangeMemento other && other._textContainer.Equals(_textContainer); } public IMemento Restore() { // Before _textContainer.Invalidate(); - TextChangeMemento oldState = new TextChangeMemento(_textContainer); + TextChangeMemento oldState = new(_textContainer); _textContainer.ChangeText(_oldText, false); // After _textContainer.Invalidate(); diff --git a/src/Greenshot.Plugin.Box/BoxConfiguration.cs b/src/Greenshot.Plugin.Box/BoxConfiguration.cs index c745fe985..cae945e9f 100644 --- a/src/Greenshot.Plugin.Box/BoxConfiguration.cs +++ b/src/Greenshot.Plugin.Box/BoxConfiguration.cs @@ -69,12 +69,7 @@ namespace Greenshot.Plugin.Box public bool ShowConfigDialog() { DialogResult result = new SettingsForm().ShowDialog(); - if (result == DialogResult.OK) - { - return true; - } - - return false; + return result == DialogResult.OK; } /// diff --git a/src/Greenshot.Plugin.Box/BoxDestination.cs b/src/Greenshot.Plugin.Box/BoxDestination.cs index 51ce877d1..0126fa1e2 100644 --- a/src/Greenshot.Plugin.Box/BoxDestination.cs +++ b/src/Greenshot.Plugin.Box/BoxDestination.cs @@ -43,14 +43,14 @@ namespace Greenshot.Plugin.Box { get { - ComponentResourceManager resources = new ComponentResourceManager(typeof(BoxPlugin)); - return (Image) resources.GetObject("Box"); + ComponentResourceManager resources = new(typeof(BoxPlugin)); + return (Image)resources.GetObject("Box"); } } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); string uploadUrl = _plugin.Upload(captureDetails, surface); if (uploadUrl != null) { diff --git a/src/Greenshot.Plugin.Box/BoxPlugin.cs b/src/Greenshot.Plugin.Box/BoxPlugin.cs index 71b2ad93b..db8c66bd6 100644 --- a/src/Greenshot.Plugin.Box/BoxPlugin.cs +++ b/src/Greenshot.Plugin.Box/BoxPlugin.cs @@ -79,7 +79,7 @@ namespace Greenshot.Plugin.Box SimpleServiceProvider.Current.AddService(new BoxDestination(this)); _itemPlugInConfig = new ToolStripMenuItem { - Image = (Image) _resources.GetObject("Box"), + Image = (Image)_resources.GetObject("Box"), Text = Language.GetString("box", LangKey.Configure) }; _itemPlugInConfig.Click += ConfigMenuClick; @@ -120,12 +120,12 @@ namespace Greenshot.Plugin.Box /// public string Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload) { - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false); + SurfaceOutputSettings outputSettings = new(_config.UploadFormat, _config.UploadJpegQuality, false); try { string url = null; string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails)); - SurfaceContainer imageToUpload = new SurfaceContainer(surfaceToUpload, outputSettings, filename); + SurfaceContainer imageToUpload = new(surfaceToUpload, outputSettings, filename); new PleaseWaitForm().ShowAndWait("Box", Language.GetString("box", LangKey.communication_wait), delegate { url = BoxUtils.UploadToBox(imageToUpload, captureDetails.Title, filename); } diff --git a/src/Greenshot.Plugin.Box/BoxUtils.cs b/src/Greenshot.Plugin.Box/BoxUtils.cs index af135fa2e..2ef33d35e 100644 --- a/src/Greenshot.Plugin.Box/BoxUtils.cs +++ b/src/Greenshot.Plugin.Box/BoxUtils.cs @@ -85,7 +85,6 @@ namespace Greenshot.Plugin.Box AccessTokenExpires = Config.AccessTokenExpires }; - // Copy the settings from the config, which is kept in memory and on the disk try @@ -149,7 +148,7 @@ namespace Greenshot.Plugin.Box byte[] content = Encoding.UTF8.GetBytes(jsonString); stream.Write(content, 0, content.Length); stream.Seek(0, SeekOrigin.Begin); - return (T) deserializer.ReadObject(stream); + return (T)deserializer.ReadObject(stream); } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Confluence.cs b/src/Greenshot.Plugin.Confluence/Confluence.cs index 56fee9d03..963c3e746 100644 --- a/src/Greenshot.Plugin.Confluence/Confluence.cs +++ b/src/Greenshot.Plugin.Confluence/Confluence.cs @@ -45,7 +45,7 @@ namespace Greenshot.Plugin.Confluence private ConfluenceSoapServiceService _confluence; private readonly int _timeout; private string _url; - private readonly Cache _pageCache = new Cache(60 * Config.Timeout); + private readonly Cache _pageCache = new(60 * Config.Timeout); public void Dispose() { diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs b/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs index 669087901..b043b5264 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs @@ -51,7 +51,7 @@ namespace Greenshot.Plugin.Confluence IsInitialized = false; try { - Uri confluenceIconUri = new Uri("/Greenshot.Plugin.Confluence;component/Images/Confluence.ico", UriKind.Relative); + Uri confluenceIconUri = new("/Greenshot.Plugin.Confluence;component/Images/Confluence.ico", UriKind.Relative); using (Stream iconStream = Application.GetResourceStream(confluenceIconUri)?.Stream) { // TODO: Replace with FileFormatHandler @@ -86,14 +86,9 @@ namespace Greenshot.Plugin.Confluence { get { - if (_page == null) - { - return Language.GetString("confluence", LangKey.upload_menu_item); - } - else - { - return Language.GetString("confluence", LangKey.upload_menu_item) + ": \"" + _page.Title + "\""; - } + return _page == null + ? Language.GetString("confluence", LangKey.upload_menu_item) + : Language.GetString("confluence", LangKey.upload_menu_item) + ": \"" + _page.Title + "\""; } } @@ -114,7 +109,7 @@ namespace Greenshot.Plugin.Confluence public override IEnumerable DynamicDestinations() { - if (ConfluencePlugin.ConfluenceConnectorNoLogin == null || !ConfluencePlugin.ConfluenceConnectorNoLogin.IsLoggedIn) + if (ConfluencePlugin.ConfluenceConnectorNoLogin?.IsLoggedIn != true) { yield break; } @@ -133,7 +128,7 @@ namespace Greenshot.Plugin.Confluence public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); // force password check to take place before the pages load if (!ConfluencePlugin.ConfluenceConnector.IsLoggedIn) { @@ -145,7 +140,7 @@ namespace Greenshot.Plugin.Confluence string filename = FilenameHelper.GetFilenameWithoutExtensionFromPattern(CoreConfig.OutputFileFilenamePattern, captureDetails); if (selectedPage == null) { - Forms.ConfluenceUpload confluenceUpload = new Forms.ConfluenceUpload(filename); + Forms.ConfluenceUpload confluenceUpload = new(filename); bool? dialogResult = confluenceUpload.ShowDialog(); if (dialogResult.HasValue && dialogResult.Value) { @@ -198,7 +193,7 @@ namespace Greenshot.Plugin.Confluence private bool Upload(ISurface surfaceToUpload, Page page, string filename, out string errorMessage) { SurfaceOutputSettings outputSettings = - new SurfaceOutputSettings(ConfluenceConfig.UploadFormat, ConfluenceConfig.UploadJpegQuality, ConfluenceConfig.UploadReduceColors); + new(ConfluenceConfig.UploadFormat, ConfluenceConfig.UploadJpegQuality, ConfluenceConfig.UploadReduceColors); errorMessage = null; try { diff --git a/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs b/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs index e9dc34d41..e3c24ac0a 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs @@ -91,7 +91,7 @@ namespace Greenshot.Plugin.Confluence try { - if (_confluenceConnector != null && !_confluenceConnector.IsLoggedIn) + if (_confluenceConnector?.IsLoggedIn == false) { _confluenceConnector.Login(); } @@ -152,7 +152,7 @@ namespace Greenshot.Plugin.Confluence public void Configure() { ConfluenceConfiguration clonedConfig = _config.Clone(); - ConfluenceConfigurationForm configForm = new ConfluenceConfigurationForm(clonedConfig); + ConfluenceConfigurationForm configForm = new(clonedConfig); string url = _config.Url; bool? dialogResult = configForm.ShowDialog(); if (dialogResult.HasValue && dialogResult.Value) diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs index 0482ce63b..a2cdd2806 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs @@ -38,9 +38,9 @@ namespace Greenshot.Plugin.Confluence public static List GetCurrentPages() { - List pages = new List(); - Regex pageIdRegex = new Regex(@"pageId=(\d+)"); - Regex spacePageRegex = new Regex(@"\/display\/([^\/]+)\/([^#]+)"); + List pages = new(); + Regex pageIdRegex = new(@"pageId=(\d+)"); + Regex spacePageRegex = new(@"\/display\/([^\/]+)\/([^#]+)"); foreach (string browserurl in GetBrowserUrls()) { string url; @@ -55,7 +55,7 @@ namespace Greenshot.Plugin.Confluence } MatchCollection pageIdMatch = pageIdRegex.Matches(url); - if (pageIdMatch != null && pageIdMatch.Count > 0) + if (pageIdMatch?.Count > 0) { long pageId = long.Parse(pageIdMatch[0].Groups[1].Value); try @@ -89,7 +89,7 @@ namespace Greenshot.Plugin.Confluence } MatchCollection spacePageMatch = spacePageRegex.Matches(url); - if (spacePageMatch != null && spacePageMatch.Count > 0) + if (spacePageMatch?.Count > 0) { if (spacePageMatch[0].Groups.Count >= 2) { @@ -140,7 +140,7 @@ namespace Greenshot.Plugin.Confluence private static IEnumerable GetBrowserUrls() { - HashSet urls = new HashSet(); + HashSet urls = new(); // FireFox foreach (WindowDetails window in WindowDetails.GetAllWindows("MozillaWindowClass")) diff --git a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs index 3a0e56ecf..2381c0d23 100644 --- a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs +++ b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs @@ -57,19 +57,19 @@ namespace Greenshot.Plugin.Confluence var genericTypeDefinition = typeof(Dictionary<,>).GetGenericTypeDefinition(); if (genericTypeDefinition != null) { - _reverseValues = (IDictionary) Activator.CreateInstance(genericTypeDefinition.MakeGenericType(typeof(string), _type)); + _reverseValues = (IDictionary)Activator.CreateInstance(genericTypeDefinition.MakeGenericType(typeof(string), _type)); } var typeDefinition = typeof(Dictionary<,>).GetGenericTypeDefinition(); if (typeDefinition != null) { - _displayValues = (IDictionary) Activator.CreateInstance(typeDefinition.MakeGenericType(_type, typeof(string))); + _displayValues = (IDictionary)Activator.CreateInstance(typeDefinition.MakeGenericType(_type, typeof(string))); } var fields = _type.GetFields(BindingFlags.Public | BindingFlags.Static); foreach (var field in fields) { - DisplayKeyAttribute[] a = (DisplayKeyAttribute[]) field.GetCustomAttributes(typeof(DisplayKeyAttribute), false); + DisplayKeyAttribute[] a = (DisplayKeyAttribute[])field.GetCustomAttributes(typeof(DisplayKeyAttribute), false); string displayKey = GetDisplayKeyValue(a); object enumValue = field.GetValue(null); @@ -77,7 +77,7 @@ namespace Greenshot.Plugin.Confluence string displayString; if (displayKey != null && Language.HasKey(displayKey)) { - displayString = Language.GetString(displayKey); + _ = Language.GetString(displayKey); } displayString = displayKey ?? enumValue.ToString(); @@ -86,7 +86,7 @@ namespace Greenshot.Plugin.Confluence _reverseValues.Add(displayString, enumValue); } - return new List((IEnumerable) _displayValues.Values).AsReadOnly(); + return new List((IEnumerable)_displayValues.Values).AsReadOnly(); } } diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs index 1bd43b915..0f48dbe5a 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs @@ -47,7 +47,7 @@ namespace Greenshot.Plugin.Confluence.Forms { if (PageListView.HasItems && PageListView.SelectedItems.Count > 0) { - _confluenceUpload.SelectedPage = (Page) PageListView.SelectedItem; + _confluenceUpload.SelectedPage = (Page)PageListView.SelectedItem; // Make sure the uploader knows we selected an already opened page _confluenceUpload.IsOpenPageSelected = true; } diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs index 82c9bd143..e473fd8ef 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs @@ -67,7 +67,7 @@ namespace Greenshot.Plugin.Confluence.Forms { if (PageListView.HasItems && PageListView.SelectedItems.Count > 0) { - _confluenceUpload.SelectedPage = (Page) PageListView.SelectedItem; + _confluenceUpload.SelectedPage = (Page)PageListView.SelectedItem; } else { @@ -82,7 +82,7 @@ namespace Greenshot.Plugin.Confluence.Forms private void DoSearch() { - string spaceKey = (string) SpaceComboBox.SelectedValue; + string spaceKey = (string)SpaceComboBox.SelectedValue; ConfluenceConfig.SearchSpaceKey = spaceKey; Pages.Clear(); foreach (var page in ConfluencePlugin.ConfluenceConnector.SearchPages(searchText.Text, spaceKey).OrderBy(p => p.Title)) diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceTreePicker.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceTreePicker.xaml.cs index dbbfa64b2..851219c6a 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceTreePicker.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceTreePicker.xaml.cs @@ -65,9 +65,9 @@ namespace Greenshot.Plugin.Confluence.Forms Log.Debug("Loading pages for page: " + page.Title); new Thread(() => { - Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) (() => { ShowBusy.Visibility = Visibility.Visible; })); + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => { ShowBusy.Visibility = Visibility.Visible; })); var pages = _confluenceConnector.GetPageChildren(page).OrderBy(p => p.Title); - Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) (() => + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => { foreach (var childPage in pages) { @@ -117,11 +117,11 @@ namespace Greenshot.Plugin.Confluence.Forms ShowBusy.Visibility = Visibility.Visible; new Thread(() => { - Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) (() => + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => { foreach (Space space in _confluenceUpload.Spaces) { - TreeViewItem spaceTreeViewItem = new TreeViewItem + TreeViewItem spaceTreeViewItem = new() { Header = space.Name, Tag = space @@ -131,7 +131,7 @@ namespace Greenshot.Plugin.Confluence.Forms try { Page page = _confluenceConnector.GetSpaceHomepage(space); - TreeViewItem pageTreeViewItem = new TreeViewItem + TreeViewItem pageTreeViewItem = new() { Header = page.Title, Tag = page diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs index 39210dd2e..be002b301 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs @@ -42,7 +42,7 @@ namespace Greenshot.Plugin.Confluence.Forms if (_pickerPage == null) { List pages = ConfluenceUtils.GetCurrentPages(); - if (pages != null && pages.Count > 0) + if (pages?.Count > 0) { _pickerPage = new ConfluencePagePicker(this, pages); } @@ -124,14 +124,14 @@ namespace Greenshot.Plugin.Confluence.Forms // Check if load is needed if (_spaces == null) { - (new Thread(() => + new Thread(() => { _spaces = ConfluencePlugin.ConfluenceConnector.GetSpaceSummaries().OrderBy(s => s.Name).ToList(); _lastLoad = DateTime.Now; }) { Name = "Loading spaces for confluence" - }).Start(); + }.Start(); } } diff --git a/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs b/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs index 6ca4ec384..29568023f 100644 --- a/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs +++ b/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs @@ -22,13 +22,13 @@ namespace Greenshot.Plugin.Confluence.Support protected override void StartListening(object source) { - var manager = (TranslationManager) source; + var manager = (TranslationManager)source; manager.LanguageChanged += OnLanguageChanged; } protected override void StopListening(object source) { - var manager = (TranslationManager) source; + var manager = (TranslationManager)source; manager.LanguageChanged -= OnLanguageChanged; } @@ -37,7 +37,7 @@ namespace Greenshot.Plugin.Confluence.Support get { Type managerType = typeof(LanguageChangedEventManager); - var manager = (LanguageChangedEventManager) GetCurrentManager(managerType); + var manager = (LanguageChangedEventManager)GetCurrentManager(managerType); if (manager == null) { manager = new LanguageChangedEventManager(); diff --git a/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs b/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs index e15e67555..330ae6b83 100644 --- a/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs +++ b/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs @@ -3,7 +3,7 @@ namespace Greenshot.Plugin.Confluence.Support { /// - /// + /// /// public class LanguageXMLTranslationProvider : ITranslationProvider { @@ -12,12 +12,7 @@ namespace Greenshot.Plugin.Confluence.Support /// public object Translate(string key) { - if (Language.HasKey("confluence", key)) - { - return Language.GetString("confluence", key); - } - - return key; + return Language.HasKey("confluence", key) ? Language.GetString("confluence", key) : (object)key; } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs b/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs index 012f0c552..6472e23a9 100644 --- a/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs +++ b/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs @@ -10,23 +10,17 @@ namespace Greenshot.Plugin.Confluence.Support /// public class TranslateExtension : MarkupExtension { - private string _key; - /// /// Initializes a new instance of the class. /// /// The key. public TranslateExtension(string key) { - _key = key; + Key = key; } [ConstructorArgument("key")] - public string Key - { - get { return _key; } - set { _key = value; } - } + public string Key { get; set; } /// /// See @@ -35,7 +29,7 @@ namespace Greenshot.Plugin.Confluence.Support { var binding = new Binding("Value") { - Source = new TranslationData(_key) + Source = new TranslationData(Key) }; return binding.ProvideValue(serviceProvider); } diff --git a/src/Greenshot.Plugin.Confluence/Support/TranslationManager.cs b/src/Greenshot.Plugin.Confluence/Support/TranslationManager.cs index 944269625..1d9787425 100644 --- a/src/Greenshot.Plugin.Confluence/Support/TranslationManager.cs +++ b/src/Greenshot.Plugin.Confluence/Support/TranslationManager.cs @@ -15,12 +15,7 @@ namespace Greenshot.Plugin.Confluence.Support public object Translate(string key) { object translatedValue = TranslationProvider?.Translate(key); - if (translatedValue != null) - { - return translatedValue; - } - - return $"!{key}!"; + return translatedValue ?? $"!{key}!"; } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Dropbox/DropboxConfiguration.cs b/src/Greenshot.Plugin.Dropbox/DropboxConfiguration.cs index d79db8686..d6c1eb181 100644 --- a/src/Greenshot.Plugin.Dropbox/DropboxConfiguration.cs +++ b/src/Greenshot.Plugin.Dropbox/DropboxConfiguration.cs @@ -63,12 +63,7 @@ namespace Greenshot.Plugin.Dropbox public bool ShowConfigDialog() { DialogResult result = new SettingsForm().ShowDialog(); - if (result == DialogResult.OK) - { - return true; - } - - return false; + return result == DialogResult.OK; } /// diff --git a/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs b/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs index d29c3cbd0..00f103cfe 100644 --- a/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs +++ b/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs @@ -46,14 +46,14 @@ namespace Greenshot.Plugin.Dropbox { get { - ComponentResourceManager resources = new ComponentResourceManager(typeof(DropboxPlugin)); - return (Image) resources.GetObject("Dropbox"); + ComponentResourceManager resources = new(typeof(DropboxPlugin)); + return (Image)resources.GetObject("Dropbox"); } } public override ExportInformation ExportCapture(bool manually, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); bool uploaded = _plugin.Upload(captureDetails, surface, out var uploadUrl); if (uploaded) { diff --git a/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs b/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs index 69026066c..ab32b5162 100644 --- a/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs +++ b/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs @@ -77,7 +77,7 @@ namespace Greenshot.Plugin.Dropbox _itemPlugInConfig = new ToolStripMenuItem { Text = Language.GetString("dropbox", LangKey.Configure), - Image = (Image) _resources.GetObject("Dropbox") + Image = (Image)_resources.GetObject("Dropbox") }; _itemPlugInConfig.Click += ConfigMenuClick; @@ -118,7 +118,7 @@ namespace Greenshot.Plugin.Dropbox public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) { uploadUrl = null; - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false); + SurfaceOutputSettings outputSettings = new(_config.UploadFormat, _config.UploadJpegQuality, false); try { bool result = false; diff --git a/src/Greenshot.Plugin.Dropbox/DropboxUtils.cs b/src/Greenshot.Plugin.Dropbox/DropboxUtils.cs index c7f6dcfe9..9ea7e11de 100644 --- a/src/Greenshot.Plugin.Dropbox/DropboxUtils.cs +++ b/src/Greenshot.Plugin.Dropbox/DropboxUtils.cs @@ -61,7 +61,7 @@ namespace Greenshot.Plugin.Dropbox try { string filename = Path.GetFileName(FilenameHelper.GetFilename(DropboxConfig.UploadFormat, captureDetails)); - SurfaceContainer image = new SurfaceContainer(surfaceToUpload, outputSettings, filename); + SurfaceContainer image = new(surfaceToUpload, outputSettings, filename); IDictionary arguments = new Dictionary { diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs index b58143f6b..b3d471a8f 100644 --- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs +++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs @@ -161,7 +161,7 @@ namespace Greenshot.Plugin.ExternalCommand public override object GetDefault(string property) => property switch { - nameof(DeletedBuildInCommands) => (object) new List(), + nameof(DeletedBuildInCommands) => (object)new List(), nameof(Commands) => new List(), nameof(Commandline) => new Dictionary(), nameof(Argument) => new Dictionary(), diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs index 4083827e3..9f57bca33 100644 --- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs +++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs @@ -41,7 +41,7 @@ namespace Greenshot.Plugin.ExternalCommand private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExternalCommandDestination)); private static readonly Regex URI_REGEXP = - new Regex( + new( @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)"); private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection(); @@ -65,8 +65,8 @@ namespace Greenshot.Plugin.ExternalCommand public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(); + ExportInformation exportInformation = new(Designation, Description); + SurfaceOutputSettings outputSettings = new(); outputSettings.PreventGreenshotFormat(); if (_presetCommand != null) @@ -83,7 +83,7 @@ namespace Greenshot.Plugin.ExternalCommand string error; if (runInBackground) { - Thread commandThread = new Thread(delegate() + Thread commandThread = new(delegate () { CallExternalCommand(exportInformation, fullPath, out output, out error); ProcessExport(exportInformation, surface); @@ -210,7 +210,7 @@ namespace Greenshot.Plugin.ExternalCommand error = null; if (!string.IsNullOrEmpty(commandline)) { - using Process process = new Process(); + using Process process = new(); // Fix variables commandline = FilenameHelper.FillVariables(commandline, true); commandline = FilenameHelper.FillCmdVariables(commandline, true); diff --git a/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs b/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs index 746dc30c4..992fff3f5 100644 --- a/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs +++ b/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs @@ -75,7 +75,7 @@ namespace Greenshot.Plugin.ExternalCommand if (ExternalCommandConfig.Commands != null) { listView1.ListViewItemSorter = new ListviewComparer(); - ImageList imageList = new ImageList(); + ImageList imageList = new(); listView1.SmallImageList = imageList; int imageNr = 0; foreach (string commando in ExternalCommandConfig.Commands) @@ -134,19 +134,19 @@ namespace Greenshot.Plugin.ExternalCommand { public int Compare(object x, object y) { - if (!(x is ListViewItem)) + if (x is not ListViewItem) { - return (0); + return 0; } - if (!(y is ListViewItem)) + if (y is not ListViewItem) { - return (0); + return 0; } - var l1 = (ListViewItem) x; - var l2 = (ListViewItem) y; - return string.Compare(l1.Text, l2.Text, StringComparison.Ordinal); + var l1 = (ListViewItem)x; + var l2 = (ListViewItem)y; + return string.CompareOrdinal(l1.Text, l2.Text); } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Flickr/FlickrConfiguration.cs b/src/Greenshot.Plugin.Flickr/FlickrConfiguration.cs index df5a428fa..090f56296 100644 --- a/src/Greenshot.Plugin.Flickr/FlickrConfiguration.cs +++ b/src/Greenshot.Plugin.Flickr/FlickrConfiguration.cs @@ -80,12 +80,7 @@ namespace Greenshot.Plugin.Flickr public bool ShowConfigDialog() { DialogResult result = new SettingsForm().ShowDialog(); - if (result == DialogResult.OK) - { - return true; - } - - return false; + return result == DialogResult.OK; } /// @@ -102,6 +97,5 @@ namespace Greenshot.Plugin.Flickr FlickrToken = null; FlickrTokenSecret = null; } - } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Flickr/FlickrDestination.cs b/src/Greenshot.Plugin.Flickr/FlickrDestination.cs index a42835abe..e1b2ed5e6 100644 --- a/src/Greenshot.Plugin.Flickr/FlickrDestination.cs +++ b/src/Greenshot.Plugin.Flickr/FlickrDestination.cs @@ -43,14 +43,14 @@ namespace Greenshot.Plugin.Flickr { get { - ComponentResourceManager resources = new ComponentResourceManager(typeof(FlickrPlugin)); - return (Image) resources.GetObject("flickr"); + ComponentResourceManager resources = new(typeof(FlickrPlugin)); + return (Image)resources.GetObject("flickr"); } } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); bool uploaded = _plugin.Upload(captureDetails, surface, out var uploadUrl); if (uploaded) { diff --git a/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs b/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs index dcad49473..597f00042 100644 --- a/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs +++ b/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs @@ -87,7 +87,7 @@ namespace Greenshot.Plugin.Flickr _itemPlugInConfig = new ToolStripMenuItem { Text = Language.GetString("flickr", LangKey.Configure), - Image = (Image) _resources.GetObject("flickr") + Image = (Image)_resources.GetObject("flickr") }; _itemPlugInConfig.Click += ConfigMenuClick; SimpleServiceProvider.Current.AddService(new FlickrDestination(this)); @@ -124,7 +124,7 @@ namespace Greenshot.Plugin.Flickr public bool Upload(ICaptureDetails captureDetails, ISurface surface, out string uploadUrl) { - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false); + SurfaceOutputSettings outputSettings = new(_config.UploadFormat, _config.UploadJpegQuality, false); uploadUrl = null; try { diff --git a/src/Greenshot.Plugin.Flickr/FlickrUtils.cs b/src/Greenshot.Plugin.Flickr/FlickrUtils.cs index c8db12160..59f995ae2 100644 --- a/src/Greenshot.Plugin.Flickr/FlickrUtils.cs +++ b/src/Greenshot.Plugin.Flickr/FlickrUtils.cs @@ -165,7 +165,7 @@ namespace Greenshot.Plugin.Flickr { try { - XmlDocument doc = new XmlDocument(); + XmlDocument doc = new(); doc.LoadXml(response); if (config.UsePageLink) { @@ -209,7 +209,7 @@ namespace Greenshot.Plugin.Flickr { try { - XmlDocument doc = new XmlDocument(); + XmlDocument doc = new(); doc.LoadXml(response); XmlNodeList nodes = doc.GetElementsByTagName("photoid"); if (nodes.Count > 0) diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosConfiguration.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosConfiguration.cs index 5765544b9..8d569a83b 100644 --- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosConfiguration.cs +++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosConfiguration.cs @@ -70,12 +70,7 @@ namespace Greenshot.Plugin.GooglePhotos public bool ShowConfigDialog() { DialogResult result = new SettingsForm().ShowDialog(); - if (result == DialogResult.OK) - { - return true; - } - - return false; + return result == DialogResult.OK; } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs index 79429ca4c..217e365d0 100644 --- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs +++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs @@ -42,14 +42,14 @@ namespace Greenshot.Plugin.GooglePhotos { get { - ComponentResourceManager resources = new ComponentResourceManager(typeof(GooglePhotosPlugin)); - return (Image) resources.GetObject("GooglePhotos"); + ComponentResourceManager resources = new(typeof(GooglePhotosPlugin)); + return (Image)resources.GetObject("GooglePhotos"); } } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); bool uploaded = _plugin.Upload(captureDetails, surface, out var uploadUrl); if (uploaded) { diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs index fae06e516..d0acc8c73 100644 --- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs +++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs @@ -79,7 +79,7 @@ namespace Greenshot.Plugin.GooglePhotos _itemPlugInRoot = new ToolStripMenuItem { Text = Language.GetString("googlephotos", LangKey.Configure), - Image = (Image) _resources.GetObject("GooglePhotos") + Image = (Image)_resources.GetObject("GooglePhotos") }; _itemPlugInRoot.Click += ConfigMenuClick; PluginUtils.AddToContextMenu(_itemPlugInRoot); @@ -117,7 +117,7 @@ namespace Greenshot.Plugin.GooglePhotos public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) { - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality); + SurfaceOutputSettings outputSettings = new(_config.UploadFormat, _config.UploadJpegQuality); try { string url = null; diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosUtils.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosUtils.cs index d8bcf54ef..4cb059712 100644 --- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosUtils.cs +++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosUtils.cs @@ -77,7 +77,7 @@ namespace Greenshot.Plugin.GooglePhotos webRequest.Headers.Add("Slug", NetworkHelper.EscapeDataString(filename)); } - SurfaceContainer container = new SurfaceContainer(surfaceToUpload, outputSettings, filename); + SurfaceContainer container = new(surfaceToUpload, outputSettings, filename); container.Upload(webRequest); string response = NetworkHelper.GetResponseAsString(webRequest); @@ -109,7 +109,7 @@ namespace Greenshot.Plugin.GooglePhotos try { - XmlDocument doc = new XmlDocument(); + XmlDocument doc = new(); doc.LoadXml(response); XmlNodeList nodes = doc.GetElementsByTagName("link", "*"); if (nodes.Count > 0) @@ -122,7 +122,7 @@ namespace Greenshot.Plugin.GooglePhotos url = node.Attributes["href"].Value; string rel = node.Attributes["rel"].Value; // Pictures with rel="http://schemas.google.com/photos/2007#canonical" are the direct link - if (rel != null && rel.EndsWith("canonical")) + if (rel?.EndsWith("canonical") == true) { break; } diff --git a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs index 7dd94bb6c..f0119183c 100644 --- a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs +++ b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs @@ -36,7 +36,7 @@ namespace Greenshot.Plugin.Imgur.Forms { private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurHistory)); private readonly GreenshotColumnSorter _columnSorter; - private static readonly object Lock = new object(); + private static readonly object Lock = new(); private static readonly ImgurConfiguration Config = IniConfig.GetIniSection(); private static ImgurHistory _instance; @@ -144,7 +144,7 @@ namespace Greenshot.Plugin.Imgur.Forms clipboardButton.Enabled = true; if (listview_imgur_uploads.SelectedItems.Count == 1) { - ImgurInfo imgurInfo = (ImgurInfo) listview_imgur_uploads.SelectedItems[0].Tag; + ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[0].Tag; pictureBox1.Image = imgurInfo.Image; } } @@ -163,7 +163,7 @@ namespace Greenshot.Plugin.Imgur.Forms { for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) { - ImgurInfo imgurInfo = (ImgurInfo) listview_imgur_uploads.SelectedItems[i].Tag; + ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag; DialogResult result = MessageBox.Show(Language.GetFormattedString("imgur", LangKey.delete_question, imgurInfo.Title), Language.GetFormattedString("imgur", LangKey.delete_title, imgurInfo.Hash), MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result != DialogResult.Yes) @@ -193,12 +193,12 @@ namespace Greenshot.Plugin.Imgur.Forms private void ClipboardButtonClick(object sender, EventArgs e) { - StringBuilder links = new StringBuilder(); + StringBuilder links = new(); if (listview_imgur_uploads.SelectedItems.Count > 0) { for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) { - ImgurInfo imgurInfo = (ImgurInfo) listview_imgur_uploads.SelectedItems[i].Tag; + ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag; links.AppendLine(Config.UsePageLink ? imgurInfo.Page : imgurInfo.Original); } } @@ -229,7 +229,7 @@ namespace Greenshot.Plugin.Imgur.Forms { for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) { - ImgurInfo imgurInfo = (ImgurInfo) listview_imgur_uploads.SelectedItems[i].Tag; + ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag; System.Diagnostics.Process.Start(imgurInfo.Page); } } @@ -254,7 +254,6 @@ namespace Greenshot.Plugin.Imgur.Forms listview_imgur_uploads.Sort(); } - private void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e) { _instance = null; diff --git a/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs b/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs index 3dc145d0b..18f7b6e1f 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs @@ -82,7 +82,7 @@ namespace Greenshot.Plugin.Imgur public Dictionary ImgurUploadHistory { get; set; } // Not stored, only run-time! - public Dictionary runtimeImgurHistory = new Dictionary(); + public Dictionary runtimeImgurHistory = new(); public int Credits { get; set; } /// @@ -119,7 +119,7 @@ namespace Greenshot.Plugin.Imgur /// bool true if OK was pressed, false if cancel public bool ShowConfigDialog() { - SettingsForm settingsForm = new SettingsForm(); + SettingsForm settingsForm = new(); DialogResult result = settingsForm.ShowDialog(); return result == DialogResult.OK; } diff --git a/src/Greenshot.Plugin.Imgur/ImgurDestination.cs b/src/Greenshot.Plugin.Imgur/ImgurDestination.cs index e277318ff..c6be4d20e 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurDestination.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurDestination.cs @@ -46,14 +46,14 @@ namespace Greenshot.Plugin.Imgur { get { - ComponentResourceManager resources = new ComponentResourceManager(typeof(ImgurPlugin)); - return (Image) resources.GetObject("Imgur"); + ComponentResourceManager resources = new(typeof(ImgurPlugin)); + return (Image)resources.GetObject("Imgur"); } } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description) + ExportInformation exportInformation = new(Designation, Description) { ExportMade = _plugin.Upload(captureDetails, surface, out var uploadUrl), Uri = uploadUrl diff --git a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs index 63ac90127..438ae8638 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs @@ -112,10 +112,10 @@ namespace Greenshot.Plugin.Imgur response = response.Replace("©", "©"); response = response.Replace("®", "®"); - ImgurInfo imgurInfo = new ImgurInfo(); + ImgurInfo imgurInfo = new(); try { - XmlDocument doc = new XmlDocument(); + XmlDocument doc = new(); doc.LoadXml(response); XmlNodeList nodes = doc.GetElementsByTagName("id"); if (nodes.Count > 0) diff --git a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs index d105916a2..11befa5ef 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs @@ -92,9 +92,9 @@ namespace Greenshot.Plugin.Imgur _config = IniConfig.GetIniSection(); _resources = new ComponentResourceManager(typeof(ImgurPlugin)); - ToolStripMenuItem itemPlugInRoot = new ToolStripMenuItem("Imgur") + ToolStripMenuItem itemPlugInRoot = new("Imgur") { - Image = (Image) _resources.GetObject("Imgur") + Image = (Image)_resources.GetObject("Imgur") }; // Provide the IDestination @@ -138,7 +138,7 @@ namespace Greenshot.Plugin.Imgur try { var form = SimpleServiceProvider.Current.GetInstance
(); - form.BeginInvoke((MethodInvoker) delegate + form.BeginInvoke((MethodInvoker)delegate { var historyMenuItem = _historyMenuItem; if (historyMenuItem == null) @@ -185,7 +185,7 @@ namespace Greenshot.Plugin.Imgur /// true if the upload succeeded public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) { - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, _config.UploadReduceColors); + SurfaceOutputSettings outputSettings = new(_config.UploadFormat, _config.UploadJpegQuality, _config.UploadReduceColors); try { string filename = Path.GetFileName(FilenameHelper.GetFilenameFromPattern(_config.FilenamePattern, _config.UploadFormat, captureDetails)); diff --git a/src/Greenshot.Plugin.Imgur/ImgurUtils.cs b/src/Greenshot.Plugin.Imgur/ImgurUtils.cs index 02af34e56..56da1c39e 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurUtils.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurUtils.cs @@ -95,7 +95,7 @@ namespace Greenshot.Plugin.Imgur bool redirected = false; if (wE.Status == WebExceptionStatus.ProtocolError) { - HttpWebResponse response = (HttpWebResponse) wE.Response; + HttpWebResponse response = (HttpWebResponse)wE.Response; if (response.StatusCode == HttpStatusCode.Forbidden) { @@ -187,7 +187,7 @@ namespace Greenshot.Plugin.Imgur var responseStream = response.GetResponseStream(); if (responseStream != null) { - using StreamReader reader = new StreamReader(responseStream, true); + using StreamReader reader = new(responseStream, true); responseString = reader.ReadToEnd(); } } @@ -235,12 +235,7 @@ namespace Greenshot.Plugin.Imgur } } - if (string.IsNullOrEmpty(responseString)) - { - return null; - } - - return ImgurInfo.ParseResponse(responseString); + return string.IsNullOrEmpty(responseString) ? null : ImgurInfo.ParseResponse(responseString); } /// @@ -291,7 +286,7 @@ namespace Greenshot.Plugin.Imgur var responseStream = response.GetResponseStream(); if (responseStream != null) { - using StreamReader reader = new StreamReader(responseStream, true); + using StreamReader reader = new(responseStream, true); responseString = reader.ReadToEnd(); } } @@ -299,7 +294,7 @@ namespace Greenshot.Plugin.Imgur { if (wE.Status == WebExceptionStatus.ProtocolError) { - if (((HttpWebResponse) wE.Response).StatusCode == HttpStatusCode.NotFound) + if (((HttpWebResponse)wE.Response).StatusCode == HttpStatusCode.NotFound) { return null; } @@ -340,7 +335,7 @@ namespace Greenshot.Plugin.Imgur var responseStream = response.GetResponseStream(); if (responseStream != null) { - using StreamReader reader = new StreamReader(responseStream, true); + using StreamReader reader = new(responseStream, true); responseString = reader.ReadToEnd(); } } @@ -352,7 +347,7 @@ namespace Greenshot.Plugin.Imgur // Allow "Bad request" this means we already deleted it if (wE.Status == WebExceptionStatus.ProtocolError) { - if (((HttpWebResponse) wE.Response).StatusCode != HttpStatusCode.BadRequest) + if (((HttpWebResponse)wE.Response).StatusCode != HttpStatusCode.BadRequest) { throw; } diff --git a/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs b/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs index 364124660..3cb3f78d8 100644 --- a/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs +++ b/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs @@ -35,9 +35,9 @@ namespace Greenshot.Plugin.Jira public abstract class AsyncMemoryCache where TResult : class { private static readonly Task EmptyValueTask = Task.FromResult(null); - private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); - private readonly MemoryCache _cache = new MemoryCache(Guid.NewGuid().ToString()); - private readonly LogSource _log = new LogSource(); + private readonly SemaphoreSlim _semaphoreSlim = new(1, 1); + private readonly MemoryCache _cache = new(Guid.NewGuid().ToString()); + private readonly LogSource _log = new(); /// /// Set the timespan for items to expire. diff --git a/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs b/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs index 29b75e9bb..a7c9b87c1 100644 --- a/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs +++ b/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs @@ -139,7 +139,7 @@ namespace Greenshot.Plugin.Jira.Forms if (_jiraConnector.IsLoggedIn) { uploadButton.Enabled = false; - var filter = (Filter) jiraFilterBox.SelectedItem; + var filter = (Filter)jiraFilterBox.SelectedItem; if (filter == null) { return; @@ -225,7 +225,7 @@ namespace Greenshot.Plugin.Jira.Forms { if (jiraListView.SelectedItems.Count > 0) { - _selectedIssue = (Issue) jiraListView.SelectedItems[0].Tag; + _selectedIssue = (Issue)jiraListView.SelectedItems[0].Tag; jiraKey.Text = _selectedIssue.Key; uploadButton.Enabled = true; } diff --git a/src/Greenshot.Plugin.Jira/JiraDestination.cs b/src/Greenshot.Plugin.Jira/JiraDestination.cs index 5e93f4992..abfd4da7f 100644 --- a/src/Greenshot.Plugin.Jira/JiraDestination.cs +++ b/src/Greenshot.Plugin.Jira/JiraDestination.cs @@ -100,7 +100,7 @@ namespace Greenshot.Plugin.Jira if (displayIcon == null) { var resources = new ComponentResourceManager(typeof(JiraPlugin)); - displayIcon = (Image) resources.GetObject("Jira"); + displayIcon = (Image)resources.GetObject("Jira"); } return displayIcon; @@ -110,7 +110,7 @@ namespace Greenshot.Plugin.Jira public override IEnumerable DynamicDestinations() { var jiraConnector = SimpleServiceProvider.Current.GetInstance(); - if (jiraConnector == null || !jiraConnector.IsLoggedIn) + if (jiraConnector?.IsLoggedIn != true) { yield break; } @@ -123,9 +123,9 @@ namespace Greenshot.Plugin.Jira public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surfaceToUpload, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); string filename = Path.GetFileName(FilenameHelper.GetFilename(Config.UploadFormat, captureDetails)); - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(Config.UploadFormat, Config.UploadJpegQuality, Config.UploadReduceColors); + SurfaceOutputSettings outputSettings = new(Config.UploadFormat, Config.UploadJpegQuality, Config.UploadReduceColors); var jiraConnector = SimpleServiceProvider.Current.GetInstance(); if (_jiraIssue != null) { diff --git a/src/Greenshot.Plugin.Jira/JiraMonitor.cs b/src/Greenshot.Plugin.Jira/JiraMonitor.cs index 81a62b759..4bd06ac87 100644 --- a/src/Greenshot.Plugin.Jira/JiraMonitor.cs +++ b/src/Greenshot.Plugin.Jira/JiraMonitor.cs @@ -40,8 +40,8 @@ namespace Greenshot.Plugin.Jira /// public class JiraMonitor : IDisposable { - private static readonly LogSource Log = new LogSource(); - private readonly Regex _jiraKeyPattern = new Regex(@"[A-Z][A-Z0-9]+\-[0-9]+"); + private static readonly LogSource Log = new(); + private readonly Regex _jiraKeyPattern = new(@"[A-Z][A-Z0-9]+\-[0-9]+"); private readonly IDisposable _monitor; private readonly IList _jiraInstances = new List(); private readonly IDictionary _projectJiraClientMap = new Dictionary(); @@ -101,9 +101,9 @@ namespace Greenshot.Plugin.Jira /// Get the "list" of recently seen Jiras /// public IEnumerable RecentJiras => - (from jiraDetails in _recentJiras.Values - orderby jiraDetails.SeenAt descending - select jiraDetails); + from jiraDetails in _recentJiras.Values + orderby jiraDetails.SeenAt descending + select jiraDetails; /// /// Check if this monitor has active instances @@ -216,8 +216,8 @@ namespace Greenshot.Plugin.Jira { // Add it to the list of recent Jiras _recentJiras = (from jiraDetails in _recentJiras.Values.ToList() - orderby jiraDetails.SeenAt descending - select jiraDetails).Take(_maxEntries).ToDictionary(jd => jd.JiraKey, jd => jd); + orderby jiraDetails.SeenAt descending + select jiraDetails).Take(_maxEntries).ToDictionary(jd => jd.JiraKey, jd => jd); } // Now we can get the title from JIRA itself diff --git a/src/Greenshot.Plugin.Jira/JiraPlugin.cs b/src/Greenshot.Plugin.Jira/JiraPlugin.cs index e784f0ef8..7b2483f21 100644 --- a/src/Greenshot.Plugin.Jira/JiraPlugin.cs +++ b/src/Greenshot.Plugin.Jira/JiraPlugin.cs @@ -123,7 +123,7 @@ namespace Greenshot.Plugin.Jira { // check for re-login var jiraConnector = SimpleServiceProvider.Current.GetInstance(); - if (jiraConnector != null && jiraConnector.IsLoggedIn && !string.IsNullOrEmpty(url)) + if (jiraConnector?.IsLoggedIn == true && !string.IsNullOrEmpty(url)) { if (!url.Equals(_config.Url)) { @@ -142,12 +142,7 @@ namespace Greenshot.Plugin.Jira { var settingsForm = new SettingsForm(); var result = settingsForm.ShowDialog(); - if (result == DialogResult.OK) - { - return true; - } - - return false; + return result == DialogResult.OK; } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Jira/Log4NetLogger.cs b/src/Greenshot.Plugin.Jira/Log4NetLogger.cs index 2bd3a4883..07b9ffb43 100644 --- a/src/Greenshot.Plugin.Jira/Log4NetLogger.cs +++ b/src/Greenshot.Plugin.Jira/Log4NetLogger.cs @@ -100,22 +100,15 @@ namespace Greenshot.Plugin.Jira public override bool IsLogLevelEnabled(LogLevels level, LogSource logSource = null) { var log = GetLogger(logSource); - switch (level) + return level switch { - case LogLevels.Verbose: - case LogLevels.Debug: - return log.IsDebugEnabled; - case LogLevels.Error: - return log.IsErrorEnabled; - case LogLevels.Fatal: - return log.IsFatalEnabled; - case LogLevels.Info: - return log.IsInfoEnabled; - case LogLevels.Warn: - return log.IsWarnEnabled; - } - - return false; + LogLevels.Verbose or LogLevels.Debug => log.IsDebugEnabled, + LogLevels.Error => log.IsErrorEnabled, + LogLevels.Fatal => log.IsFatalEnabled, + LogLevels.Info => log.IsInfoEnabled, + LogLevels.Warn => log.IsWarnEnabled, + _ => false, + }; } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/Com/DisposableCom.cs b/src/Greenshot.Plugin.Office/Com/DisposableCom.cs index e722f48e3..5b24384e8 100644 --- a/src/Greenshot.Plugin.Office/Com/DisposableCom.cs +++ b/src/Greenshot.Plugin.Office/Com/DisposableCom.cs @@ -16,12 +16,7 @@ namespace Greenshot.Plugin.Office.Com /// IDisposableCom of type T public static IDisposableCom Create(T comObject) { - if (Equals(comObject, default(T))) - { - return null; - } - - return new DisposableComImplementation(comObject); + return Equals(comObject, default(T)) ? null : (IDisposableCom)new DisposableComImplementation(comObject); } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/Com/Ole32Api.cs b/src/Greenshot.Plugin.Office/Com/Ole32Api.cs index 1a57aa6c9..3f99df5bb 100644 --- a/src/Greenshot.Plugin.Office/Com/Ole32Api.cs +++ b/src/Greenshot.Plugin.Office/Com/Ole32Api.cs @@ -20,12 +20,7 @@ namespace Greenshot.Plugin.Office.Com /// Guid with the clsId public static Guid ClassIdFromProgId(string programId) { - if (CLSIDFromProgID(programId, out Guid clsId).Succeeded()) - { - return clsId; - } - - return clsId; + return CLSIDFromProgID(programId, out Guid clsId).Succeeded() ? clsId : clsId; } /// @@ -35,6 +30,6 @@ namespace Greenshot.Plugin.Office.Com /// Guid /// HResult [DllImport("ole32.dll", ExactSpelling = true)] - private static extern HResult CLSIDFromProgID([In] [MarshalAs(UnmanagedType.LPWStr)] string progId, [Out] out Guid clsId); + private static extern HResult CLSIDFromProgID([In][MarshalAs(UnmanagedType.LPWStr)] string progId, [Out] out Guid clsId); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs b/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs index ea0f1b0c9..7993b7365 100644 --- a/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs +++ b/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs @@ -21,12 +21,7 @@ namespace Greenshot.Plugin.Office.Com /// IDisposableCom of T public static IDisposableCom GetActiveObject(ref Guid clsId) { - if (GetActiveObject(ref clsId, IntPtr.Zero, out object comObject).Succeeded()) - { - return DisposableCom.Create((T) comObject); - } - - return null; + return GetActiveObject(ref clsId, IntPtr.Zero, out object comObject).Succeeded() ? DisposableCom.Create((T)comObject) : null; } /// diff --git a/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs b/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs index fb1930c8c..b4109da28 100644 --- a/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs @@ -84,7 +84,7 @@ namespace Greenshot.Plugin.Office.Destinations public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); bool createdFile = false; string imageFile = captureDetails.Filename; if (imageFile == null || surface.Modified || !Regex.IsMatch(imageFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) diff --git a/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs b/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs index 387810494..8f51ff5df 100644 --- a/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs @@ -37,7 +37,7 @@ namespace Greenshot.Plugin.Office.Destinations public const string DESIGNATION = "OneNote"; private static readonly string exePath; private readonly OneNotePage page; - private readonly OneNoteExporter _oneNoteExporter = new OneNoteExporter(); + private readonly OneNoteExporter _oneNoteExporter = new(); static OneNoteDestination() { @@ -70,14 +70,7 @@ namespace Greenshot.Plugin.Office.Destinations { get { - if (page == null) - { - return "Microsoft OneNote"; - } - else - { - return page.DisplayName; - } + return page == null ? "Microsoft OneNote" : page.DisplayName; } } @@ -111,7 +104,7 @@ namespace Greenshot.Plugin.Office.Destinations public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); if (page == null) { diff --git a/src/Greenshot.Plugin.Office/Destinations/OutlookDestination.cs b/src/Greenshot.Plugin.Office/Destinations/OutlookDestination.cs index 6d93c4096..7e106a929 100644 --- a/src/Greenshot.Plugin.Office/Destinations/OutlookDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/OutlookDestination.cs @@ -75,7 +75,6 @@ namespace Greenshot.Plugin.Office.Destinations } } - private static string GetOutlookExePath() => RegistryHive.LocalMachine.ReadKey64Or32(@"Microsoft\Windows\CurrentVersion\App Paths\OUTLOOK.EXE"); /// @@ -85,12 +84,7 @@ namespace Greenshot.Plugin.Office.Destinations private static bool HasOutlook() { string outlookPath = GetOutlookExePath(); - if (outlookPath == null) - { - return false; - } - - return File.Exists(outlookPath); + return outlookPath != null && File.Exists(outlookPath); } public OutlookDestination() @@ -155,7 +149,7 @@ namespace Greenshot.Plugin.Office.Destinations /// public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); // Outlook logic string tmpFile = captureDetails.Filename; if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) @@ -193,7 +187,7 @@ namespace Greenshot.Plugin.Office.Destinations if (!manuallyInitiated) { var inspectorCaptions = _outlookEmailExporter.RetrievePossibleTargets(); - if (inspectorCaptions != null && inspectorCaptions.Count > 0) + if (inspectorCaptions?.Count > 0) { var destinations = new List { diff --git a/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs b/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs index 3b9ce4bc8..8dcaadc0d 100644 --- a/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs @@ -41,7 +41,7 @@ namespace Greenshot.Plugin.Office.Destinations private static readonly string ExePath; private readonly string _presentationName; - private readonly PowerpointExporter _powerpointExporter = new PowerpointExporter(); + private readonly PowerpointExporter _powerpointExporter = new(); static PowerpointDestination() { @@ -71,12 +71,7 @@ namespace Greenshot.Plugin.Office.Destinations { get { - if (_presentationName == null) - { - return "Microsoft Powerpoint"; - } - - return _presentationName; + return _presentationName ?? "Microsoft Powerpoint"; } } @@ -90,12 +85,9 @@ namespace Greenshot.Plugin.Office.Destinations { get { - if (!string.IsNullOrEmpty(_presentationName)) - { - return PluginUtils.GetCachedExeIcon(ExePath, IconPresentation); - } - - return PluginUtils.GetCachedExeIcon(ExePath, IconApplication); + return !string.IsNullOrEmpty(_presentationName) + ? PluginUtils.GetCachedExeIcon(ExePath, IconPresentation) + : PluginUtils.GetCachedExeIcon(ExePath, IconApplication); } } @@ -109,7 +101,7 @@ namespace Greenshot.Plugin.Office.Destinations public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); string tmpFile = captureDetails.Filename; Size imageSize = Size.Empty; if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) @@ -127,7 +119,7 @@ namespace Greenshot.Plugin.Office.Destinations if (!manuallyInitiated) { var presentations = _powerpointExporter.GetPowerpointPresentations().ToList(); - if (presentations != null && presentations.Count > 0) + if (presentations?.Count > 0) { var destinations = new List { diff --git a/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs b/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs index 99cf4693c..6bc4d0d6e 100644 --- a/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs @@ -42,7 +42,7 @@ namespace Greenshot.Plugin.Office.Destinations private const int IconDocument = 1; private static readonly string ExePath; private readonly string _documentCaption; - private readonly WordExporter _wordExporter = new WordExporter(); + private readonly WordExporter _wordExporter = new(); static WordDestination() { @@ -84,7 +84,7 @@ namespace Greenshot.Plugin.Office.Destinations public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); string tmpFile = captureDetails.Filename; if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) { @@ -118,7 +118,7 @@ namespace Greenshot.Plugin.Office.Destinations if (!manuallyInitiated) { var documents = _wordExporter.GetWordDocuments().ToList(); - if (documents != null && documents.Count > 0) + if (documents?.Count > 0) { var destinations = new List { diff --git a/src/Greenshot.Plugin.Office/OfficeExport/Entities/OneNotePage.cs b/src/Greenshot.Plugin.Office/OfficeExport/Entities/OneNotePage.cs index e6fcd4bff..22ba34042 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/Entities/OneNotePage.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/Entities/OneNotePage.cs @@ -30,12 +30,9 @@ namespace Greenshot.Plugin.Office.OfficeExport.Entities get { var notebook = Parent.Parent; - if (string.IsNullOrEmpty(notebook.Name)) - { - return string.Format("{0} / {1}", Parent.Name, Name); - } - - return string.Format("{0} / {1} / {2}", Parent.Parent.Name, Parent.Name, Name); + return string.IsNullOrEmpty(notebook.Name) + ? string.Format("{0} / {1}", Parent.Name, Name) + : string.Format("{0} / {1} / {2}", Parent.Parent.Name, Parent.Name, Name); } } diff --git a/src/Greenshot.Plugin.Office/OfficeExport/ExcelExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/ExcelExporter.cs index cfffff5f6..f71342e1f 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/ExcelExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/ExcelExporter.cs @@ -115,7 +115,7 @@ namespace Greenshot.Plugin.Office.OfficeExport if (!Version.TryParse(excelApplication.ComObject.Version, out _excelVersion)) { LOG.Warn("Assuming Excel version 1997."); - _excelVersion = new Version((int) OfficeVersions.Office97, 0, 0, 0); + _excelVersion = new Version((int)OfficeVersions.Office97, 0, 0, 0); } } @@ -136,8 +136,8 @@ namespace Greenshot.Plugin.Office.OfficeExport using var workbooks = DisposableCom.Create(excelApplication.ComObject.Workbooks); for (int i = 1; i <= workbooks.ComObject.Count; i++) { - using var workbook = DisposableCom.Create((_Workbook) workbooks.ComObject[i]); - if ((workbook != null) && workbook.ComObject.Name.StartsWith(workbookName)) + using var workbook = DisposableCom.Create((_Workbook)workbooks.ComObject[i]); + if (workbook?.ComObject.Name.StartsWith(workbookName) == true) { InsertIntoExistingWorkbook(workbook, tmpFile, imageSize); } @@ -177,7 +177,7 @@ namespace Greenshot.Plugin.Office.OfficeExport shape.ComObject.ScaleWidth(1, MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromTopLeft); workbook.ComObject.Activate(); using var application = DisposableCom.Create(workbook.ComObject.Application); - User32Api.SetForegroundWindow((IntPtr) application.ComObject.Hwnd); + User32Api.SetForegroundWindow((IntPtr)application.ComObject.Hwnd); } /// @@ -195,7 +195,7 @@ namespace Greenshot.Plugin.Office.OfficeExport excelApplication.ComObject.Visible = true; using var workbooks = DisposableCom.Create(excelApplication.ComObject.Workbooks); - using var workbook = DisposableCom.Create((_Workbook) workbooks.ComObject.Add()); + using var workbook = DisposableCom.Create((_Workbook)workbooks.ComObject.Add()); InsertIntoExistingWorkbook(workbook, tmpFile, imageSize); } } diff --git a/src/Greenshot.Plugin.Office/OfficeExport/OneNoteExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/OneNoteExporter.cs index 645623780..80cf9dadb 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/OneNoteExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/OneNoteExporter.cs @@ -61,8 +61,7 @@ namespace Greenshot.Plugin.Office.OfficeExport return false; } - string pageId; - oneNoteApplication.ComObject.CreateNewPage(unfiledNotesSectionId, out pageId, NewPageStyle.npsDefault); + oneNoteApplication.ComObject.CreateNewPage(unfiledNotesSectionId, out string pageId, NewPageStyle.npsDefault); newPage.Id = pageId; // Set the new name, this is automatically done in the export to page newPage.Name = surfaceToUpload.CaptureDetails.Title; @@ -163,8 +162,7 @@ namespace Greenshot.Plugin.Office.OfficeExport if (oneNoteApplication != null) { // ReSharper disable once RedundantAssignment - string notebookXml = ""; - oneNoteApplication.ComObject.GetHierarchy("", HierarchyScope.hsPages, out notebookXml, XMLSchema.xs2010); + oneNoteApplication.ComObject.GetHierarchy("", HierarchyScope.hsPages, out string notebookXml, XMLSchema.xs2010); if (!string.IsNullOrEmpty(notebookXml)) { LOG.Debug(notebookXml); @@ -231,17 +229,14 @@ namespace Greenshot.Plugin.Office.OfficeExport } finally { - if (reader != null) - { - reader.Dispose(); - } + reader?.Dispose(); } } } } catch (COMException cEx) { - if (cEx.ErrorCode == unchecked((int) 0x8002801D)) + if (cEx.ErrorCode == unchecked((int)0x8002801D)) { LOG.Warn( "Wrong registry keys, to solve this remove the OneNote key as described here: https://microsoftmercenary.com/wp/outlook-excel-interop-calls-breaking-solved/"); @@ -256,12 +251,9 @@ namespace Greenshot.Plugin.Office.OfficeExport pages.Sort((page1, page2) => { - if (page1.IsCurrentlyViewed || page2.IsCurrentlyViewed) - { - return page2.IsCurrentlyViewed.CompareTo(page1.IsCurrentlyViewed); - } - - return string.Compare(page1.DisplayName, page2.DisplayName, StringComparison.Ordinal); + return page1.IsCurrentlyViewed || page2.IsCurrentlyViewed + ? page2.IsCurrentlyViewed.CompareTo(page1.IsCurrentlyViewed) + : string.CompareOrdinal(page1.DisplayName, page2.DisplayName); }); return pages; } @@ -280,12 +272,10 @@ namespace Greenshot.Plugin.Office.OfficeExport } // ReSharper disable once RedundantAssignment - string unfiledNotesPath = ""; - oneNoteApplication.ComObject.GetSpecialLocation(specialLocation, out unfiledNotesPath); + oneNoteApplication.ComObject.GetSpecialLocation(specialLocation, out string unfiledNotesPath); // ReSharper disable once RedundantAssignment - string notebookXml = ""; - oneNoteApplication.ComObject.GetHierarchy("", HierarchyScope.hsPages, out notebookXml, XMLSchema.xs2010); + oneNoteApplication.ComObject.GetHierarchy("", HierarchyScope.hsPages, out string notebookXml, XMLSchema.xs2010); if (!string.IsNullOrEmpty(notebookXml)) { LOG.Debug(notebookXml); @@ -311,10 +301,7 @@ namespace Greenshot.Plugin.Office.OfficeExport } finally { - if (reader != null) - { - reader.Dispose(); - } + reader?.Dispose(); } } diff --git a/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs index 72724c40b..7bba19734 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs @@ -51,12 +51,12 @@ namespace Greenshot.Plugin.Office.OfficeExport private const string DefaultProfileValue = "DefaultProfile"; // Schema definitions for the MAPI properties, see: http://msdn.microsoft.com/en-us/library/aa454438.aspx and: http://msdn.microsoft.com/en-us/library/bb446117.aspx - private const string AttachmentContentId = @"http://schemas.microsoft.com/mapi/proptag/0x3712001E"; + private const string AttachmentContentId = "http://schemas.microsoft.com/mapi/proptag/0x3712001E"; private static readonly string SignaturePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Signatures"); private static Version _outlookVersion; private static string _currentUser; - private readonly WordExporter _wordExporter = new WordExporter(); + private readonly WordExporter _wordExporter = new(); /// /// Export the image stored in tmpFile to the Inspector with the caption @@ -75,12 +75,12 @@ namespace Greenshot.Plugin.Office.OfficeExport } // The activeexplorer inline response only works with >= 2013, Microsoft Outlook 15.0 Object Library - if (_outlookVersion.Major >= (int) OfficeVersions.Office2013) + if (_outlookVersion.Major >= (int)OfficeVersions.Office2013) { // Check inline "panel" for Outlook 2013 - using var activeExplorer = DisposableCom.Create((_Explorer) outlookApplication.ComObject.ActiveExplorer()); + using var activeExplorer = DisposableCom.Create((_Explorer)outlookApplication.ComObject.ActiveExplorer()); // Only if we have one and if the capture is the one we selected - if ((activeExplorer != null) && activeExplorer.ComObject.Caption.StartsWith(inspectorCaption)) + if (activeExplorer?.ComObject.Caption.StartsWith(inspectorCaption) == true) { var untypedInlineResponse = activeExplorer.ComObject.ActiveInlineResponse; using (DisposableCom.Create(untypedInlineResponse)) @@ -95,7 +95,7 @@ namespace Greenshot.Plugin.Office.OfficeExport break; case AppointmentItem appointmentItem: - if ((_outlookVersion.Major >= (int) OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) + if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) { if (!string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) { @@ -118,7 +118,7 @@ namespace Greenshot.Plugin.Office.OfficeExport LOG.DebugFormat("Got {0} inspectors to check", inspectors.ComObject.Count); for (int i = 1; i <= inspectors.ComObject.Count; i++) { - using var inspector = DisposableCom.Create((_Inspector) inspectors.ComObject[i]); + using var inspector = DisposableCom.Create((_Inspector)inspectors.ComObject[i]); string currentCaption = inspector.ComObject.Caption; if (!currentCaption.StartsWith(inspectorCaption)) { @@ -147,7 +147,7 @@ namespace Greenshot.Plugin.Office.OfficeExport break; case AppointmentItem appointmentItem: - if ((_outlookVersion.Major >= (int) OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) + if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) { if (!string.IsNullOrEmpty(appointmentItem.Organizer) && !appointmentItem.Organizer.Equals(_currentUser)) { @@ -219,16 +219,16 @@ namespace Greenshot.Plugin.Office.OfficeExport // https://msdn.microsoft.com/en-us/library/dd492012%28v=office.12%29.aspx // Earlier versions of Outlook also supported an Inspector.HTMLEditor object property, but since Internet Explorer is no longer the rendering engine for HTML messages and posts, HTMLEditor is no longer supported. IDisposableCom<_Document> wordDocument = null; - if ((explorer != null) && (_outlookVersion.Major >= (int) OfficeVersions.Office2013)) + if ((explorer != null) && (_outlookVersion.Major >= (int)OfficeVersions.Office2013)) { // TODO: Needs to have the Microsoft Outlook 15.0 Object Library installed - wordDocument = DisposableCom.Create((_Document) explorer.ComObject.ActiveInlineResponseWordEditor); + wordDocument = DisposableCom.Create((_Document)explorer.ComObject.ActiveInlineResponseWordEditor); } else if (inspector != null) { if (inspector.ComObject.IsWordMail() && (inspector.ComObject.EditorType == OlEditorType.olEditorWord)) { - var tmpWordDocument = (_Document) inspector.ComObject.WordEditor; + var tmpWordDocument = (_Document)inspector.ComObject.WordEditor; wordDocument = DisposableCom.Create(tmpWordDocument); } } @@ -270,7 +270,7 @@ namespace Greenshot.Plugin.Office.OfficeExport } string contentId; - if (_outlookVersion.Major >= (int) OfficeVersions.Office2007) + if (_outlookVersion.Major >= (int)OfficeVersions.Office2007) { contentId = Guid.NewGuid().ToString(); } @@ -298,7 +298,7 @@ namespace Greenshot.Plugin.Office.OfficeExport var selection = document2.selection; if (selection != null) { - var range = (IHTMLTxtRange) selection.createRange(); + var range = (IHTMLTxtRange)selection.createRange(); if (range != null) { // First paste, than attach (otherwise the range is wrong!) @@ -330,7 +330,7 @@ namespace Greenshot.Plugin.Office.OfficeExport // Create the attachment (if inlined the attachment isn't visible as attachment!) using var attachments = DisposableCom.Create(mailItem.Attachments); using var attachment = DisposableCom.Create(attachments.ComObject.Add(tmpFile, OlAttachmentType.olByValue, inlinePossible ? 0 : 1, attachmentName)); - if (_outlookVersion.Major >= (int) OfficeVersions.Office2007) + if (_outlookVersion.Major >= (int)OfficeVersions.Office2007) { // Add the content id to the attachment, this only works for Outlook >= 2007 try @@ -397,7 +397,7 @@ namespace Greenshot.Plugin.Office.OfficeExport private void ExportToNewEmail(IDisposableCom outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string cc, string bcc, string url) { - using var newItem = DisposableCom.Create((MailItem) outlookApplication.ComObject.CreateItem(OlItemType.olMailItem)); + using var newItem = DisposableCom.Create((MailItem)outlookApplication.ComObject.CreateItem(OlItemType.olMailItem)); if (newItem == null) { return; @@ -458,7 +458,7 @@ namespace Greenshot.Plugin.Office.OfficeExport { using var attachment = DisposableCom.Create(attachments.ComObject.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)); // add content ID to the attachment - if (_outlookVersion.Major >= (int) OfficeVersions.Office2007) + if (_outlookVersion.Major >= (int)OfficeVersions.Office2007) { try { @@ -517,7 +517,7 @@ namespace Greenshot.Plugin.Office.OfficeExport // So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();) newMail.Display(false); - using var inspector = DisposableCom.Create((_Inspector) newMail.GetInspector); + using var inspector = DisposableCom.Create((_Inspector)newMail.GetInspector); if (inspector != null) { try @@ -601,7 +601,7 @@ namespace Greenshot.Plugin.Office.OfficeExport return null; } - if ((outlookApplication != null) && (outlookApplication.ComObject != null)) + if (outlookApplication?.ComObject != null) { InitializeVariables(outlookApplication); } @@ -622,7 +622,7 @@ namespace Greenshot.Plugin.Office.OfficeExport return null; } - string defaultProfile = (string) profilesKey.GetValue(DefaultProfileValue); + string defaultProfile = (string)profilesKey.GetValue(DefaultProfileValue); LOG.DebugFormat("defaultProfile={0}", defaultProfile); using var profileKey = profilesKey.OpenSubKey(defaultProfile + @"\" + AccountKey, false); if (profileKey != null) @@ -634,7 +634,7 @@ namespace Greenshot.Plugin.Office.OfficeExport using var numberKey = profileKey.OpenSubKey(number, false); if (numberKey != null) { - byte[] val = (byte[]) numberKey.GetValue(NewSignatureValue); + byte[] val = (byte[])numberKey.GetValue(NewSignatureValue); if (val == null) { continue; @@ -645,7 +645,7 @@ namespace Greenshot.Plugin.Office.OfficeExport { if (b != 0) { - signatureName += (char) b; + signatureName += (char)b; } } @@ -669,7 +669,6 @@ namespace Greenshot.Plugin.Office.OfficeExport return null; } - /// /// Initialize static outlook variables like version and currentuser /// @@ -684,11 +683,11 @@ namespace Greenshot.Plugin.Office.OfficeExport if (!Version.TryParse(outlookApplication.ComObject.Version, out _outlookVersion)) { LOG.Warn("Assuming outlook version 1997."); - _outlookVersion = new Version((int) OfficeVersions.Office97, 0, 0, 0); + _outlookVersion = new Version((int)OfficeVersions.Office97, 0, 0, 0); } // Preventing retrieval of currentUser if Outlook is older than 2007 - if (_outlookVersion.Major >= (int) OfficeVersions.Office2007) + if (_outlookVersion.Major >= (int)OfficeVersions.Office2007) { try { @@ -723,7 +722,7 @@ namespace Greenshot.Plugin.Office.OfficeExport } // The activeexplorer inline response only works with >= 2013, Microsoft Outlook 15.0 Object Library - if (_outlookVersion.Major >= (int) OfficeVersions.Office2013) + if (_outlookVersion.Major >= (int)OfficeVersions.Office2013) { // Check inline "panel" for Outlook 2013 using var activeExplorer = DisposableCom.Create(outlookApplication.ComObject.ActiveExplorer()); @@ -745,7 +744,7 @@ namespace Greenshot.Plugin.Office.OfficeExport break; case AppointmentItem appointmentItem: - if ((_outlookVersion.Major >= (int) OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) + if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) { if (!string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) { @@ -761,7 +760,7 @@ namespace Greenshot.Plugin.Office.OfficeExport } using var inspectors = DisposableCom.Create(outlookApplication.ComObject.Inspectors); - if ((inspectors != null) && (inspectors.ComObject.Count > 0)) + if (inspectors?.ComObject.Count > 0) { for (int i = 1; i <= inspectors.ComObject.Count; i++) { @@ -787,7 +786,7 @@ namespace Greenshot.Plugin.Office.OfficeExport inspectorCaptions.Add(caption, mailItem.Class); break; case AppointmentItem appointmentItem: - if ((_outlookVersion.Major >= (int) OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) + if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) { if (!string.IsNullOrEmpty(appointmentItem.Organizer) && !appointmentItem.Organizer.Equals(_currentUser)) { diff --git a/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs index 21862f38d..01bdd99b6 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs @@ -57,8 +57,8 @@ namespace Greenshot.Plugin.Office.OfficeExport float left, top; using (var pageSetup = DisposableCom.Create(presentation.ComObject.PageSetup)) { - left = pageSetup.ComObject.SlideWidth / 2 - imageSize.Width / 2f; - top = pageSetup.ComObject.SlideHeight / 2 - imageSize.Height / 2f; + left = (pageSetup.ComObject.SlideWidth / 2) - (imageSize.Width / 2f); + top = (pageSetup.ComObject.SlideHeight / 2) - (imageSize.Height / 2f); } float width = imageSize.Width; @@ -98,7 +98,7 @@ namespace Greenshot.Plugin.Office.OfficeExport } else { - top = shapeForLocation.ComObject.Top + shapeForLocation.ComObject.Height / 2 - imageSize.Height / 2f; + top = shapeForLocation.ComObject.Top + (shapeForLocation.ComObject.Height / 2) - (imageSize.Height / 2f); } shapeForLocation.ComObject.Height = imageSize.Height; @@ -318,7 +318,7 @@ namespace Greenshot.Plugin.Office.OfficeExport if (!Version.TryParse(powerpointApplication.ComObject.Version, out _powerpointVersion)) { LOG.Warn("Assuming Powerpoint version 1997."); - _powerpointVersion = new Version((int) OfficeVersions.Office97, 0, 0, 0); + _powerpointVersion = new Version((int)OfficeVersions.Office97, 0, 0, 0); } } @@ -357,7 +357,7 @@ namespace Greenshot.Plugin.Office.OfficeExport private bool IsAfter2003() { - return _powerpointVersion.Major > (int) OfficeVersions.Office2003; + return _powerpointVersion.Major > (int)OfficeVersions.Office2003; } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs index 8100bf650..21e954ab8 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs @@ -92,7 +92,7 @@ namespace Greenshot.Plugin.Office.OfficeExport return null; } - if ((wordApplication != null) && (wordApplication.ComObject != null)) + if (wordApplication?.ComObject != null) { InitializeVariables(wordApplication); } @@ -148,7 +148,7 @@ namespace Greenshot.Plugin.Office.OfficeExport if (!Version.TryParse(wordApplication.ComObject.Version, out _wordVersion)) { LOG.Warn("Assuming Word version 1997."); - _wordVersion = new Version((int) OfficeVersions.Office97, 0, 0, 0); + _wordVersion = new Version((int)OfficeVersions.Office97, 0, 0, 0); } } @@ -170,7 +170,7 @@ namespace Greenshot.Plugin.Office.OfficeExport using var documents = DisposableCom.Create(wordApplication.ComObject.Documents); for (int i = 1; i <= documents.ComObject.Count; i++) { - using var wordDocument = DisposableCom.Create((_Document) documents.ComObject[i]); + using var wordDocument = DisposableCom.Create((_Document)documents.ComObject[i]); using var activeWindow = DisposableCom.Create(wordDocument.ComObject.ActiveWindow); if (activeWindow.ComObject.Caption.StartsWith(wordCaption)) { @@ -358,7 +358,7 @@ namespace Greenshot.Plugin.Office.OfficeExport /// private bool IsAfter2003() { - return _wordVersion.Major > (int) OfficeVersions.Office2003; + return _wordVersion.Major > (int)OfficeVersions.Office2003; } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/OfficePlugin.cs b/src/Greenshot.Plugin.Office/OfficePlugin.cs index 54eb25c22..a9f85e45d 100644 --- a/src/Greenshot.Plugin.Office/OfficePlugin.cs +++ b/src/Greenshot.Plugin.Office/OfficePlugin.cs @@ -130,7 +130,6 @@ namespace Greenshot.Plugin.Office } } - /// /// Implementation of the IGreenshotPlugin.Initialize /// diff --git a/src/Greenshot.Plugin.Photobucket/PhotobucketConfiguration.cs b/src/Greenshot.Plugin.Photobucket/PhotobucketConfiguration.cs index 1aea1594f..a6879dcbd 100644 --- a/src/Greenshot.Plugin.Photobucket/PhotobucketConfiguration.cs +++ b/src/Greenshot.Plugin.Photobucket/PhotobucketConfiguration.cs @@ -70,12 +70,7 @@ namespace Greenshot.Plugin.Photobucket delegate { settingsForm = new SettingsForm(); } ); DialogResult result = settingsForm.ShowDialog(); - if (result == DialogResult.OK) - { - return true; - } - - return false; + return result == DialogResult.OK; } } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs b/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs index 75c067f60..6809724dd 100644 --- a/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs +++ b/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs @@ -52,12 +52,7 @@ namespace Greenshot.Plugin.Photobucket { get { - if (_albumPath != null) - { - return _albumPath; - } - - return Language.GetString("photobucket", LangKey.upload_menu_item); + return _albumPath ?? Language.GetString("photobucket", LangKey.upload_menu_item); } } @@ -65,8 +60,8 @@ namespace Greenshot.Plugin.Photobucket { get { - ComponentResourceManager resources = new ComponentResourceManager(typeof(PhotobucketPlugin)); - return (Image) resources.GetObject("Photobucket"); + ComponentResourceManager resources = new(typeof(PhotobucketPlugin)); + return (Image)resources.GetObject("Photobucket"); } } @@ -104,7 +99,7 @@ namespace Greenshot.Plugin.Photobucket /// public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); bool uploaded = _plugin.Upload(captureDetails, surface, _albumPath, out var uploadUrl); if (uploaded) { diff --git a/src/Greenshot.Plugin.Photobucket/PhotobucketInfo.cs b/src/Greenshot.Plugin.Photobucket/PhotobucketInfo.cs index 21897301f..bc7e4a378 100644 --- a/src/Greenshot.Plugin.Photobucket/PhotobucketInfo.cs +++ b/src/Greenshot.Plugin.Photobucket/PhotobucketInfo.cs @@ -45,10 +45,10 @@ namespace Greenshot.Plugin.Photobucket public static PhotobucketInfo FromUploadResponse(string response) { Log.Debug(response); - PhotobucketInfo photobucketInfo = new PhotobucketInfo(); + PhotobucketInfo photobucketInfo = new(); try { - XmlDocument doc = new XmlDocument(); + XmlDocument doc = new(); doc.LoadXml(response); var nodes = doc.GetElementsByTagName("url"); if (nodes.Count > 0) diff --git a/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs b/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs index 62a933a63..0dc64760e 100644 --- a/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs +++ b/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs @@ -80,7 +80,7 @@ namespace Greenshot.Plugin.Photobucket _itemPlugInConfig = new ToolStripMenuItem(Language.GetString("photobucket", LangKey.configure)) { - Image = (Image) _resources.GetObject("Photobucket") + Image = (Image)_resources.GetObject("Photobucket") }; _itemPlugInConfig.Click += delegate { _config.ShowConfigDialog(); }; @@ -121,7 +121,7 @@ namespace Greenshot.Plugin.Photobucket /// true if the upload succeeded public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, string albumPath, out string uploadUrl) { - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, _config.UploadReduceColors); + SurfaceOutputSettings outputSettings = new(_config.UploadFormat, _config.UploadJpegQuality, _config.UploadReduceColors); try { string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails)); diff --git a/src/Greenshot.Plugin.Photobucket/PhotobucketUtils.cs b/src/Greenshot.Plugin.Photobucket/PhotobucketUtils.cs index 0126f46e0..ede23e380 100644 --- a/src/Greenshot.Plugin.Photobucket/PhotobucketUtils.cs +++ b/src/Greenshot.Plugin.Photobucket/PhotobucketUtils.cs @@ -90,7 +90,7 @@ namespace Greenshot.Plugin.Photobucket }; try { - string apiUrl = "https://api.photobucket.com/album/!/upload"; + const string apiUrl = "https://api.photobucket.com/album/!/upload"; responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, apiUrl, apiUrl.Replace("api.photobucket.com", PhotobucketConfig.SubDomain), signedParameters, unsignedParameters, null); } @@ -235,9 +235,9 @@ namespace Greenshot.Plugin.Photobucket try { - XmlDocument doc = new XmlDocument(); + XmlDocument doc = new(); doc.LoadXml(responseString); - List albums = new List(); + List albums = new(); var xmlNode = doc.GetElementsByTagName("content").Item(0); if (xmlNode != null) { diff --git a/src/Greenshot.Plugin.Photobucket/Properties/AssemblyInfo.cs b/src/Greenshot.Plugin.Photobucket/Properties/AssemblyInfo.cs index 783762320..96293a12d 100644 --- a/src/Greenshot.Plugin.Photobucket/Properties/AssemblyInfo.cs +++ b/src/Greenshot.Plugin.Photobucket/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using System.Reflection; using System.Runtime.InteropServices; - // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. diff --git a/src/Greenshot.Plugin.Win10/Destinations/Win10ShareDestination.cs b/src/Greenshot.Plugin.Win10/Destinations/Win10ShareDestination.cs index fa31d3a11..36a9e7840 100644 --- a/src/Greenshot.Plugin.Win10/Destinations/Win10ShareDestination.cs +++ b/src/Greenshot.Plugin.Win10/Destinations/Win10ShareDestination.cs @@ -93,7 +93,7 @@ namespace Greenshot.Plugin.Win10.Destinations if (wei.WinEvent == WinEvents.EVENT_OBJECT_CREATE) { var windowTitle = User32Api.GetText(wei.Handle); - if ("Windows Shell Experience Host" == windowTitle) + if (windowTitle == "Windows Shell Experience Host") { shareInfo.SharingHwnd = wei.Handle; } diff --git a/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs b/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs index 08bf7eeb6..9ef117638 100644 --- a/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs +++ b/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs @@ -32,7 +32,7 @@ namespace Greenshot.Plugin.Win10.Internal /// public IInputStream GetInputStreamAt(ulong position) { - Seek((long) position, SeekOrigin.Begin); + Seek((long)position, SeekOrigin.Begin); return this.AsInputStream(); } @@ -40,19 +40,19 @@ namespace Greenshot.Plugin.Win10.Internal /// public IOutputStream GetOutputStreamAt(ulong position) { - Seek((long) position, SeekOrigin.Begin); + Seek((long)position, SeekOrigin.Begin); return this.AsOutputStream(); } /// - ulong IRandomAccessStream.Position => (ulong) Position; + ulong IRandomAccessStream.Position => (ulong)Position; /// public ulong Size { - get { return (ulong) Length; } - set { SetLength((long) value); } + get { return (ulong)Length; } + set { SetLength((long)value); } } /// @@ -66,7 +66,7 @@ namespace Greenshot.Plugin.Win10.Internal /// public void Seek(ulong position) { - Seek((long) position, SeekOrigin.Begin); + Seek((long)position, SeekOrigin.Begin); } /// diff --git a/src/Greenshot.Plugin.Win10/Native/DataTransferManagerHelper.cs b/src/Greenshot.Plugin.Win10/Native/DataTransferManagerHelper.cs index 1ef1059c4..6a22d1418 100644 --- a/src/Greenshot.Plugin.Win10/Native/DataTransferManagerHelper.cs +++ b/src/Greenshot.Plugin.Win10/Native/DataTransferManagerHelper.cs @@ -52,7 +52,7 @@ namespace Greenshot.Plugin.Win10.Native IActivationFactory activationFactory = WindowsRuntimeMarshal.GetActivationFactory(typeof(DataTransferManager)); // ReSharper disable once SuspiciousTypeConversion.Global - _dataTransferManagerInterOp = (IDataTransferManagerInterOp) activationFactory; + _dataTransferManagerInterOp = (IDataTransferManagerInterOp)activationFactory; _windowHandle = handle; var riid = new Guid(DataTransferManagerId); diff --git a/src/Greenshot.Plugin.Win10/ToastNotificationService.cs b/src/Greenshot.Plugin.Win10/ToastNotificationService.cs index b9120fee7..9af83c14d 100644 --- a/src/Greenshot.Plugin.Win10/ToastNotificationService.cs +++ b/src/Greenshot.Plugin.Win10/ToastNotificationService.cs @@ -122,8 +122,8 @@ namespace Greenshot.Plugin.Win10 //.AddAppLogoOverride(new Uri($@"file://{_imageFilePath}"), ToastGenericAppLogoCrop.None) .Show(toast => { - // Windows 10 first with 1903: ExpiresOnReboot = true - toast.ExpirationTime = timeout.HasValue ? DateTimeOffset.Now.Add(timeout.Value) : (DateTimeOffset?)null; + // Windows 10 first with 1903: ExpiresOnReboot = true + toast.ExpirationTime = timeout.HasValue ? DateTimeOffset.Now.Add(timeout.Value) : (DateTimeOffset?)null; void ToastActivatedHandler(ToastNotification toastNotification, object sender) { @@ -162,15 +162,14 @@ namespace Greenshot.Plugin.Win10 } toast.Dismissed -= ToastDismissedHandler; - // Remove the other handler too - toast.Activated -= ToastActivatedHandler; + // Remove the other handler too + toast.Activated -= ToastActivatedHandler; toast.Failed -= ToastOnFailed; } toast.Dismissed += ToastDismissedHandler; toast.Failed += ToastOnFailed; }); - } catch (Exception ex) { diff --git a/src/Greenshot.Plugin.Win10/Win10OcrProvider.cs b/src/Greenshot.Plugin.Win10/Win10OcrProvider.cs index e33909581..c7caadb0f 100644 --- a/src/Greenshot.Plugin.Win10/Win10OcrProvider.cs +++ b/src/Greenshot.Plugin.Win10/Win10OcrProvider.cs @@ -170,8 +170,8 @@ namespace Greenshot.Plugin.Win10 for (var index = 0; index < ocrLine.Words.Count; index++) { var ocrWord = ocrLine.Words[index]; - var location = new NativeRect((int) ocrWord.BoundingRect.X, (int) ocrWord.BoundingRect.Y, - (int) ocrWord.BoundingRect.Width, (int) ocrWord.BoundingRect.Height); + var location = new NativeRect((int)ocrWord.BoundingRect.X, (int)ocrWord.BoundingRect.Y, + (int)ocrWord.BoundingRect.Width, (int)ocrWord.BoundingRect.Height); var word = line.Words[index]; word.Text = ocrWord.Text; diff --git a/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs b/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs index 0a9a511c7..2addc0a8e 100644 --- a/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs +++ b/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs @@ -52,7 +52,7 @@ namespace Greenshot.Controls } NativeRect old = e.ImageRectangle; - ToolStripItemImageRenderEventArgs clone = new ToolStripItemImageRenderEventArgs(e.Graphics, e.Item, _scaledCheckbox, new NativeRect(old.X, 0, old.Width, old.Height)); + ToolStripItemImageRenderEventArgs clone = new(e.Graphics, e.Item, _scaledCheckbox, new NativeRect(old.X, 0, old.Width, old.Height)); base.OnRenderItemCheck(clone); } } diff --git a/src/Greenshot/Destinations/ClipboardDestination.cs b/src/Greenshot/Destinations/ClipboardDestination.cs index 7093e43ec..7db8514ec 100644 --- a/src/Greenshot/Destinations/ClipboardDestination.cs +++ b/src/Greenshot/Destinations/ClipboardDestination.cs @@ -58,7 +58,7 @@ namespace Greenshot.Destinations public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); try { ClipboardHelper.SetClipboardData(surface); diff --git a/src/Greenshot/Destinations/EmailDestination.cs b/src/Greenshot/Destinations/EmailDestination.cs index 356e3d27c..83369e10d 100644 --- a/src/Greenshot/Destinations/EmailDestination.cs +++ b/src/Greenshot/Destinations/EmailDestination.cs @@ -89,7 +89,7 @@ namespace Greenshot.Destinations public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); MapiMailMessage.SendImage(surface, captureDetails); exportInformation.ExportMade = true; ProcessExport(exportInformation, surface); diff --git a/src/Greenshot/Destinations/FileWithDialogDestination.cs b/src/Greenshot/Destinations/FileWithDialogDestination.cs index 72924689f..5c863e0c5 100644 --- a/src/Greenshot/Destinations/FileWithDialogDestination.cs +++ b/src/Greenshot/Destinations/FileWithDialogDestination.cs @@ -42,7 +42,6 @@ namespace Greenshot.Destinations public override int Priority => 0; - public override Keys EditorShortcutKeys { get { return Keys.Control | Keys.Shift | Keys.S; } @@ -55,7 +54,7 @@ namespace Greenshot.Destinations public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); // Bug #2918756 don't overwrite path if SaveWithDialog returns null! var savedTo = ImageIO.SaveWithDialog(surface, captureDetails); if (savedTo != null) diff --git a/src/Greenshot/Destinations/PickerDestination.cs b/src/Greenshot/Destinations/PickerDestination.cs index fd2f0bc05..789c1be11 100644 --- a/src/Greenshot/Destinations/PickerDestination.cs +++ b/src/Greenshot/Destinations/PickerDestination.cs @@ -38,7 +38,6 @@ namespace Greenshot.Destinations public override int Priority => 1; - /// /// Export the capture with the destination picker /// @@ -48,7 +47,7 @@ namespace Greenshot.Destinations /// true if export was made public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - List destinations = new List(); + List destinations = new(); foreach (var destination in SimpleServiceProvider.Current.GetAllInstances()) { diff --git a/src/Greenshot/Destinations/PrinterDestination.cs b/src/Greenshot/Destinations/PrinterDestination.cs index 7265c4576..4086264ed 100644 --- a/src/Greenshot/Destinations/PrinterDestination.cs +++ b/src/Greenshot/Destinations/PrinterDestination.cs @@ -54,12 +54,9 @@ namespace Greenshot.Destinations { get { - if (_printerName != null) - { - return Language.GetString(LangKey.settings_destination_printer) + " - " + _printerName; - } - - return Language.GetString(LangKey.settings_destination_printer); + return _printerName != null + ? Language.GetString(LangKey.settings_destination_printer) + " - " + _printerName + : Language.GetString(LangKey.settings_destination_printer); } } @@ -77,28 +74,23 @@ namespace Greenshot.Destinations /// IEnumerable of IDestination public override IEnumerable DynamicDestinations() { - PrinterSettings settings = new PrinterSettings(); + PrinterSettings settings = new(); string defaultPrinter = settings.PrinterName; - List printers = new List(); + List printers = new(); foreach (string printer in PrinterSettings.InstalledPrinters) { printers.Add(printer); } - printers.Sort(delegate(string p1, string p2) + printers.Sort(delegate (string p1, string p2) { if (defaultPrinter.Equals(p1)) { return -1; } - if (defaultPrinter.Equals(p2)) - { - return 1; - } - - return string.Compare(p1, p2, StringComparison.Ordinal); + return defaultPrinter.Equals(p2) ? 1 : string.CompareOrdinal(p1, p2); }); foreach (string printer in printers) { @@ -115,22 +107,22 @@ namespace Greenshot.Destinations /// ExportInformation public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); + ExportInformation exportInformation = new(Designation, Description); PrinterSettings printerSettings; if (!string.IsNullOrEmpty(_printerName)) { - using PrintHelper printHelper = new PrintHelper(surface, captureDetails); + using PrintHelper printHelper = new(surface, captureDetails); printerSettings = printHelper.PrintTo(_printerName); } else if (!manuallyInitiated) { - PrinterSettings settings = new PrinterSettings(); - using PrintHelper printHelper = new PrintHelper(surface, captureDetails); + PrinterSettings settings = new(); + using PrintHelper printHelper = new(surface, captureDetails); printerSettings = printHelper.PrintTo(settings.PrinterName); } else { - using PrintHelper printHelper = new PrintHelper(surface, captureDetails); + using PrintHelper printHelper = new(surface, captureDetails); printerSettings = printHelper.PrintWithDialog(); } diff --git a/src/Greenshot/Forms/AboutForm.cs b/src/Greenshot/Forms/AboutForm.cs index a9cfc2cfc..62cbf1263 100644 --- a/src/Greenshot/Forms/AboutForm.cs +++ b/src/Greenshot/Forms/AboutForm.cs @@ -70,7 +70,7 @@ namespace Greenshot.Forms /// /// The location of every dot in the "G" /// - private readonly List _gSpots = new List + private readonly List _gSpots = new() { // Top row new(P2, P1), // 0 @@ -153,7 +153,7 @@ namespace Greenshot.Forms _bitmap = ImageHelper.CreateEmpty(90, 90, PixelFormat.Format24bppRgb, BackColor, 96, 96); pictureBox1.Image = _bitmap; - lblTitle.Text = $@"Greenshot {EnvironmentInfo.GetGreenshotVersion()} {(IniConfig.IsPortable ? " Portable" : "")} ({OsInfo.Bits}) bit)"; + lblTitle.Text = $"Greenshot {EnvironmentInfo.GetGreenshotVersion()} {(IniConfig.IsPortable ? " Portable" : "")} ({OsInfo.Bits}) bit)"; // Number of frames the pixel animation takes int frames = FramesForMillis(2000); @@ -171,7 +171,7 @@ namespace Greenshot.Forms RectangleAnimator pixelAnimation; // Make the pixel grow from the middle, if this offset isn't used it looks like it's shifted - int offset = (W - 2) / 2; + const int offset = (W - 2) / 2; // If the optimize for Terminal Server is set we make the animation without much ado if (IsTerminalServerSession) @@ -182,7 +182,7 @@ namespace Greenshot.Forms else { // Create the animation, first we do nothing (on the final destination) - NativeRect standingStill = new NativeRect(gSpot.X + offset, gSpot.Y + offset, 0, 0); + NativeRect standingStill = new(gSpot.X + offset, gSpot.Y + offset, 0, 0); pixelAnimation = new RectangleAnimator(standingStill, standingStill, pixelWaitFrames, EasingType.Quintic, EasingMode.EaseIn); // And than we size to the wanted size. pixelAnimation.QueueDestinationLeg(new NativeRect(gSpot.X, gSpot.Y, W - 2, W - 2), frames); @@ -200,7 +200,7 @@ namespace Greenshot.Forms _hasAnimationsLeft = true; // Pixel Color cycle colors, here we use a pre-animated loop which stores the values. - ColorAnimator pixelColorAnimator = new ColorAnimator(_pixelColor, Color.FromArgb(255, 255, 255), 6, EasingType.Quadratic, EasingMode.EaseIn); + ColorAnimator pixelColorAnimator = new(_pixelColor, Color.FromArgb(255, 255, 255), 6, EasingType.Quadratic, EasingMode.EaseIn); pixelColorAnimator.QueueDestinationLeg(_pixelColor, 6, EasingType.Quadratic, EasingMode.EaseOut); do { @@ -301,7 +301,7 @@ namespace Greenshot.Forms graphics.TranslateTransform(2, -2); graphics.RotateTransform(20); - using SolidBrush brush = new SolidBrush(_pixelColor); + using SolidBrush brush = new(_pixelColor); int index = 0; // We assume there is nothing to animate in the next Animate loop _hasAnimationsLeft = false; @@ -350,12 +350,12 @@ namespace Greenshot.Forms } else { - MessageBox.Show(@"Greenshot can't find the logfile, it should have been here: " + MainForm.LogFileLocation); + MessageBox.Show("Greenshot can't find the logfile, it should have been here: " + MainForm.LogFileLocation); } } catch (Exception) { - MessageBox.Show(@"Couldn't open the greenshot.log, it's located here: " + MainForm.LogFileLocation, @"Error opening greenshot.log", + MessageBox.Show("Couldn't open the greenshot.log, it's located here: " + MainForm.LogFileLocation, "Error opening greenshot.log", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } @@ -369,7 +369,7 @@ namespace Greenshot.Forms } catch (Exception) { - MessageBox.Show(@"Couldn't open the greenshot.ini, it's located here: " + IniConfig.ConfigLocation, @"Error opening greenshot.ini", + MessageBox.Show("Couldn't open the greenshot.ini, it's located here: " + IniConfig.ConfigLocation, "Error opening greenshot.ini", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } diff --git a/src/Greenshot/Forms/BugReportForm.cs b/src/Greenshot/Forms/BugReportForm.cs index 61502c836..ec3d70065 100644 --- a/src/Greenshot/Forms/BugReportForm.cs +++ b/src/Greenshot/Forms/BugReportForm.cs @@ -45,7 +45,7 @@ namespace Greenshot.Forms private void LinkLblBugsLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { - openLink((LinkLabel) sender); + openLink((LinkLabel)sender); } private void openLink(LinkLabel link) diff --git a/src/Greenshot/Forms/CaptureForm.cs b/src/Greenshot/Forms/CaptureForm.cs index 68e57f040..e5d206769 100644 --- a/src/Greenshot/Forms/CaptureForm.cs +++ b/src/Greenshot/Forms/CaptureForm.cs @@ -58,7 +58,7 @@ namespace Greenshot.Forms private static readonly ILog Log = LogManager.GetLogger(typeof(CaptureForm)); private static readonly CoreConfiguration Conf = IniConfig.GetIniSection(); private static readonly Brush GreenOverlayBrush = new SolidBrush(Color.FromArgb(50, Color.MediumSeaGreen)); - private static readonly Pen OverlayPen = new Pen(Color.FromArgb(50, Color.Black)); + private static readonly Pen OverlayPen = new(Color.FromArgb(50, Color.Black)); private static CaptureForm _currentForm; private static readonly Brush BackgroundBrush; @@ -169,7 +169,7 @@ namespace Greenshot.Forms InitializeComponent(); // Only double-buffer when we are not in a TerminalServerSession DoubleBuffered = !IsTerminalServerSession; - Text = @"Greenshot capture form"; + Text = "Greenshot capture form"; // Make sure we never capture the capture-form WindowDetails.RegisterIgnoreHandle(Handle); @@ -196,7 +196,7 @@ namespace Greenshot.Forms private void CaptureForm_Resize(object sender, EventArgs e) { - Log.DebugFormat("Resize was called, new size: {0}", this.Bounds); + Log.DebugFormat("Resize was called, new size: {0}", Bounds); if (Bounds.Equals(_capture.ScreenBounds)) { // We have the correct size @@ -538,12 +538,7 @@ namespace Greenshot.Forms /// private bool IsAnimating(IAnimator animator) { - if (animator == null) - { - return false; - } - - return animator.HasNext; + return animator != null && animator.HasNext; } /// @@ -596,7 +591,7 @@ namespace Greenshot.Forms } } - if (_selectedCaptureWindow != null && !_selectedCaptureWindow.Equals(lastWindow)) + if (_selectedCaptureWindow?.Equals(lastWindow) == false) { _capture.CaptureDetails.Title = _selectedCaptureWindow.Text; _capture.CaptureDetails.AddMetaData("windowtitle", _selectedCaptureWindow.Text); @@ -631,7 +626,7 @@ namespace Greenshot.Forms int textForWidth = Math.Max(Math.Abs(_mX - _cursorPos.X), Math.Abs(_mX - lastPos.X)); int textForHeight = Math.Max(Math.Abs(_mY - _cursorPos.Y), Math.Abs(_mY - lastPos.Y)); - using (Font rulerFont = new Font(FontFamily.GenericSansSerif, 8)) + using (Font rulerFont = new(FontFamily.GenericSansSerif, 8)) { Size measureWidth = TextRenderer.MeasureText(textForWidth.ToString(CultureInfo.InvariantCulture), rulerFont); x1 -= measureWidth.Width + 15; @@ -672,7 +667,7 @@ namespace Greenshot.Forms } else { - if (_selectedCaptureWindow != null && !_selectedCaptureWindow.Equals(lastWindow)) + if (_selectedCaptureWindow?.Equals(lastWindow) == false) { // Window changes, make new animation from current to target _windowAnimator.ChangeDestination(_captureRect, FramesForMillis(700)); @@ -855,7 +850,7 @@ namespace Greenshot.Forms if (_isZoomerTransparent) { //create a color matrix object to change the opacy - ColorMatrix opacyMatrix = new ColorMatrix + ColorMatrix opacyMatrix = new() { Matrix33 = Conf.ZoomerOpacity }; @@ -872,7 +867,7 @@ namespace Greenshot.Forms graphics.CompositingQuality = CompositingQuality.HighSpeed; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - using (GraphicsPath path = new GraphicsPath()) + using (GraphicsPath path = new()) { path.AddEllipse(destinationRectangle); graphics.SetClip(path); @@ -887,12 +882,12 @@ namespace Greenshot.Forms } } - int alpha = (int) (255 * Conf.ZoomerOpacity); + int alpha = (int)(255 * Conf.ZoomerOpacity); Color opacyWhite = Color.FromArgb(alpha, 255, 255, 255); Color opacyBlack = Color.FromArgb(alpha, 0, 0, 0); // Draw the circle around the zoomer - using (Pen pen = new Pen(opacyWhite, 2)) + using (Pen pen = new(opacyWhite, 2)) { graphics.DrawEllipse(pen, destinationRectangle); } @@ -904,27 +899,27 @@ namespace Greenshot.Forms // Calculate some values int pixelThickness = destinationRectangle.Width / sourceRectangle.Width; int halfWidth = destinationRectangle.Width / 2; - int halfWidthEnd = destinationRectangle.Width / 2 - pixelThickness / 2; + int halfWidthEnd = (destinationRectangle.Width / 2) - (pixelThickness / 2); int halfHeight = destinationRectangle.Height / 2; - int halfHeightEnd = destinationRectangle.Height / 2 - pixelThickness / 2; + int halfHeightEnd = (destinationRectangle.Height / 2) - (pixelThickness / 2); int drawAtHeight = destinationRectangle.Y + halfHeight; int drawAtWidth = destinationRectangle.X + halfWidth; int padding = pixelThickness; // Pen to draw - using (Pen pen = new Pen(opacyBlack, pixelThickness)) + using (Pen pen = new(opacyBlack, pixelThickness)) { // Draw the cross-hair-lines // Vertical top to middle graphics.DrawLine(pen, drawAtWidth, destinationRectangle.Y + padding, drawAtWidth, destinationRectangle.Y + halfHeightEnd - padding); // Vertical middle + 1 to bottom - graphics.DrawLine(pen, drawAtWidth, destinationRectangle.Y + halfHeightEnd + 2 * padding, drawAtWidth, + graphics.DrawLine(pen, drawAtWidth, destinationRectangle.Y + halfHeightEnd + (2 * padding), drawAtWidth, destinationRectangle.Y + destinationRectangle.Width - padding); // Horizontal left to middle graphics.DrawLine(pen, destinationRectangle.X + padding, drawAtHeight, destinationRectangle.X + halfWidthEnd - padding, drawAtHeight); // Horizontal middle + 1 to right - graphics.DrawLine(pen, destinationRectangle.X + halfWidthEnd + 2 * padding, drawAtHeight, destinationRectangle.X + destinationRectangle.Width - padding, + graphics.DrawLine(pen, destinationRectangle.X + halfWidthEnd + (2 * padding), drawAtHeight, destinationRectangle.X + destinationRectangle.Width - padding, drawAtHeight); // Fix offset for drawing the white rectangle around the cross-hair-lines @@ -936,13 +931,13 @@ namespace Greenshot.Forms pen.Color = opacyWhite; pen.Width = 1; // Vertical top to middle - graphics.DrawRectangle(pen, drawAtWidth, destinationRectangle.Y + padding, pixelThickness, halfHeightEnd - 2 * padding - 1); + graphics.DrawRectangle(pen, drawAtWidth, destinationRectangle.Y + padding, pixelThickness, halfHeightEnd - (2 * padding) - 1); // Vertical middle + 1 to bottom - graphics.DrawRectangle(pen, drawAtWidth, destinationRectangle.Y + halfHeightEnd + 2 * padding, pixelThickness, halfHeightEnd - 2 * padding - 1); + graphics.DrawRectangle(pen, drawAtWidth, destinationRectangle.Y + halfHeightEnd + (2 * padding), pixelThickness, halfHeightEnd - (2 * padding) - 1); // Horizontal left to middle - graphics.DrawRectangle(pen, destinationRectangle.X + padding, drawAtHeight, halfWidthEnd - 2 * padding - 1, pixelThickness); + graphics.DrawRectangle(pen, destinationRectangle.X + padding, drawAtHeight, halfWidthEnd - (2 * padding) - 1, pixelThickness); // Horizontal middle + 1 to right - graphics.DrawRectangle(pen, destinationRectangle.X + halfWidthEnd + 2 * padding, drawAtHeight, halfWidthEnd - 2 * padding - 1, pixelThickness); + graphics.DrawRectangle(pen, destinationRectangle.X + halfWidthEnd + (2 * padding), drawAtHeight, halfWidthEnd - (2 * padding) - 1, pixelThickness); } attributes?.Dispose(); @@ -1040,29 +1035,29 @@ namespace Greenshot.Forms captureHeight = (_captureRect.Height + 1).ToString(CultureInfo.InvariantCulture); } - using (Font rulerFont = new Font(FontFamily.GenericSansSerif, 8)) + using (Font rulerFont = new(FontFamily.GenericSansSerif, 8)) { Size measureWidth = TextRenderer.MeasureText(captureWidth, rulerFont); Size measureHeight = TextRenderer.MeasureText(captureHeight, rulerFont); int hSpace = measureWidth.Width + 3; int vSpace = measureHeight.Height + 3; Brush bgBrush = new SolidBrush(Color.FromArgb(200, 217, 240, 227)); - Pen rulerPen = new Pen(Color.SeaGreen); + Pen rulerPen = new(Color.SeaGreen); // horizontal ruler if (fixedRect.Width > hSpace + 3) { using GraphicsPath p = CreateRoundedRectangle( - fixedRect.X + (fixedRect.Width / 2 - hSpace / 2) + 3, + fixedRect.X + ((fixedRect.Width / 2) - (hSpace / 2)) + 3, fixedRect.Y - dist - 7, measureWidth.Width - 3, measureWidth.Height, 3); graphics.FillPath(bgBrush, p); graphics.DrawPath(rulerPen, p); - graphics.DrawString(captureWidth, rulerFont, rulerPen.Brush, fixedRect.X + (fixedRect.Width / 2 - hSpace / 2) + 3, fixedRect.Y - dist - 7); - graphics.DrawLine(rulerPen, fixedRect.X, fixedRect.Y - dist, fixedRect.X + (fixedRect.Width / 2 - hSpace / 2), fixedRect.Y - dist); - graphics.DrawLine(rulerPen, fixedRect.X + fixedRect.Width / 2 + hSpace / 2, fixedRect.Y - dist, fixedRect.X + fixedRect.Width, fixedRect.Y - dist); + graphics.DrawString(captureWidth, rulerFont, rulerPen.Brush, fixedRect.X + ((fixedRect.Width / 2) - (hSpace / 2)) + 3, fixedRect.Y - dist - 7); + graphics.DrawLine(rulerPen, fixedRect.X, fixedRect.Y - dist, fixedRect.X + ((fixedRect.Width / 2) - (hSpace / 2)), fixedRect.Y - dist); + graphics.DrawLine(rulerPen, fixedRect.X + (fixedRect.Width / 2) + (hSpace / 2), fixedRect.Y - dist, fixedRect.X + fixedRect.Width, fixedRect.Y - dist); graphics.DrawLine(rulerPen, fixedRect.X, fixedRect.Y - dist - 3, fixedRect.X, fixedRect.Y - dist + 3); graphics.DrawLine(rulerPen, fixedRect.X + fixedRect.Width, fixedRect.Y - dist - 3, fixedRect.X + fixedRect.Width, fixedRect.Y - dist + 3); } @@ -1072,15 +1067,15 @@ namespace Greenshot.Forms { using GraphicsPath p = CreateRoundedRectangle( fixedRect.X - measureHeight.Width + 1, - fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2) + 2, + fixedRect.Y + ((fixedRect.Height / 2) - (vSpace / 2)) + 2, measureHeight.Width - 3, measureHeight.Height - 1, 3); graphics.FillPath(bgBrush, p); graphics.DrawPath(rulerPen, p); - graphics.DrawString(captureHeight, rulerFont, rulerPen.Brush, fixedRect.X - measureHeight.Width + 1, fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2) + 2); - graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y, fixedRect.X - dist, fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2)); - graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y + fixedRect.Height / 2 + vSpace / 2, fixedRect.X - dist, fixedRect.Y + fixedRect.Height); + graphics.DrawString(captureHeight, rulerFont, rulerPen.Brush, fixedRect.X - measureHeight.Width + 1, fixedRect.Y + ((fixedRect.Height / 2) - (vSpace / 2)) + 2); + graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y, fixedRect.X - dist, fixedRect.Y + ((fixedRect.Height / 2) - (vSpace / 2))); + graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y + (fixedRect.Height / 2) + (vSpace / 2), fixedRect.X - dist, fixedRect.Y + fixedRect.Height); graphics.DrawLine(rulerPen, fixedRect.X - dist - 3, fixedRect.Y, fixedRect.X - dist + 3, fixedRect.Y); graphics.DrawLine(rulerPen, fixedRect.X - dist - 3, fixedRect.Y + fixedRect.Height, fixedRect.X - dist + 3, fixedRect.Y + fixedRect.Height); } @@ -1091,7 +1086,7 @@ namespace Greenshot.Forms // Display size of selected rectangle // Prepare the font and text. - using Font sizeFont = new Font(FontFamily.GenericSansSerif, 12); + using Font sizeFont = new(FontFamily.GenericSansSerif, 12); // When capturing a Region we need to add 1 to the height/width for correction string sizeText; if (_captureMode == CaptureMode.Region || _captureMode == CaptureMode.Text) @@ -1120,15 +1115,15 @@ namespace Greenshot.Forms } // Draw the size. - using Font newSizeFont = new Font(FontFamily.GenericSansSerif, newSize, FontStyle.Bold); - PointF sizeLocation = new PointF(fixedRect.X + _captureRect.Width / 2 - extent.Width / 2, fixedRect.Y + _captureRect.Height / 2 - newSizeFont.GetHeight() / 2); + using Font newSizeFont = new(FontFamily.GenericSansSerif, newSize, FontStyle.Bold); + PointF sizeLocation = new(fixedRect.X + (_captureRect.Width / 2) - (extent.Width / 2), fixedRect.Y + (_captureRect.Height / 2) - (newSizeFont.GetHeight() / 2)); graphics.DrawString(sizeText, newSizeFont, Brushes.LightSeaGreen, sizeLocation); if (_showDebugInfo && _selectedCaptureWindow != null) { string title = $"#{_selectedCaptureWindow.Handle.ToInt64():X} - {(_selectedCaptureWindow.Text.Length > 0 ? _selectedCaptureWindow.Text : _selectedCaptureWindow.Process.ProcessName)}"; - PointF debugLocation = new PointF(fixedRect.X, fixedRect.Y); + PointF debugLocation = new(fixedRect.X, fixedRect.Y); graphics.DrawString(title, sizeFont, Brushes.DarkOrange, debugLocation); } } @@ -1137,7 +1132,7 @@ namespace Greenshot.Forms { if (!IsTerminalServerSession) { - using (Pen pen = new Pen(Color.LightSeaGreen)) + using (Pen pen = new(Color.LightSeaGreen)) { pen.DashStyle = DashStyle.Dot; NativeRect screenBounds = _capture.ScreenBounds; @@ -1146,7 +1141,7 @@ namespace Greenshot.Forms } string xy = _cursorPos.X + " x " + _cursorPos.Y; - using Font f = new Font(FontFamily.GenericSansSerif, 8); + using Font f = new(FontFamily.GenericSansSerif, 8); Size xySize = TextRenderer.MeasureText(xy, f); using GraphicsPath gp = CreateRoundedRectangle(_cursorPos.X + 5, _cursorPos.Y + 5, xySize.Width - 3, xySize.Height, 3); using (Brush bgBrush = new SolidBrush(Color.FromArgb(200, 217, 240, 227))) @@ -1154,10 +1149,10 @@ namespace Greenshot.Forms graphics.FillPath(bgBrush, gp); } - using (Pen pen = new Pen(Color.SeaGreen)) + using (Pen pen = new(Color.SeaGreen)) { graphics.DrawPath(pen, gp); - Point coordinatePosition = new Point(_cursorPos.X + 5, _cursorPos.Y + 5); + Point coordinatePosition = new(_cursorPos.X + 5, _cursorPos.Y + 5); graphics.DrawString(xy, f, pen.Brush, coordinatePosition); } } @@ -1169,7 +1164,7 @@ namespace Greenshot.Forms const int zoomSourceWidth = 25; const int zoomSourceHeight = 25; - var sourceRectangle = new NativeRect(_cursorPos.X - zoomSourceWidth / 2, _cursorPos.Y - zoomSourceHeight / 2, zoomSourceWidth, zoomSourceHeight); + var sourceRectangle = new NativeRect(_cursorPos.X - (zoomSourceWidth / 2), _cursorPos.Y - (zoomSourceHeight / 2), zoomSourceWidth, zoomSourceHeight); var destinationRectangle = _zoomAnimator.Current; destinationRectangle = destinationRectangle.Offset(_cursorPos); @@ -1180,13 +1175,13 @@ namespace Greenshot.Forms private static GraphicsPath CreateRoundedRectangle(int x, int y, int width, int height, int radius) { var gp = new GraphicsPath(); - gp.AddLine(x + radius, y, x + width - radius * 2, y); // Line - gp.AddArc(x + width - radius * 2, y, radius * 2, radius * 2, 270, 90); // Corner - gp.AddLine(x + width, y + radius, x + width, y + height - radius * 2); // Line - gp.AddArc(x + width - radius * 2, y + height - radius * 2, radius * 2, radius * 2, 0, 90); // Corner - gp.AddLine(x + width - radius * 2, y + height, x + radius, y + height); // Line - gp.AddArc(x, y + height - radius * 2, radius * 2, radius * 2, 90, 90); // Corner - gp.AddLine(x, y + height - radius * 2, x, y + radius); // Line + gp.AddLine(x + radius, y, x + width - (radius * 2), y); // Line + gp.AddArc(x + width - (radius * 2), y, radius * 2, radius * 2, 270, 90); // Corner + gp.AddLine(x + width, y + radius, x + width, y + height - (radius * 2)); // Line + gp.AddArc(x + width - (radius * 2), y + height - (radius * 2), radius * 2, radius * 2, 0, 90); // Corner + gp.AddLine(x + width - (radius * 2), y + height, x + radius, y + height); // Line + gp.AddArc(x, y + height - (radius * 2), radius * 2, radius * 2, 90, 90); // Corner + gp.AddLine(x, y + height - (radius * 2), x, y + radius); // Line gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner gp.CloseFigure(); diff --git a/src/Greenshot/Forms/MainForm.cs b/src/Greenshot/Forms/MainForm.cs index 081084d0b..04b6789cb 100644 --- a/src/Greenshot/Forms/MainForm.cs +++ b/src/Greenshot/Forms/MainForm.cs @@ -104,7 +104,7 @@ namespace Greenshot.Forms if (arguments.Length > 0 && LOG.IsDebugEnabled) { - StringBuilder argumentString = new StringBuilder(); + StringBuilder argumentString = new(); foreach (string argument in arguments) { argumentString.Append("[").Append(argument).Append("] "); @@ -223,7 +223,7 @@ namespace Greenshot.Forms } // Finished parsing the command line arguments, see if we need to do anything - CopyDataTransport transport = new CopyDataTransport(); + CopyDataTransport transport = new(); if (filesToOpen.Count > 0) { foreach (string fileToOpen in filesToOpen) @@ -241,7 +241,7 @@ namespace Greenshot.Forms } else { - StringBuilder instanceInfo = new StringBuilder(); + StringBuilder instanceInfo = new(); bool matchedThisProcess = false; int index = 1; int currentProcessId; @@ -254,7 +254,7 @@ namespace Greenshot.Forms { try { - instanceInfo.Append(index++ + ": ").AppendLine(Kernel32Api.GetProcessPath(greenshotProcess.Id)); + instanceInfo.Append(index++).Append(": ").AppendLine(Kernel32Api.GetProcessPath(greenshotProcess.Id)); if (currentProcessId == greenshotProcess.Id) { matchedThisProcess = true; @@ -271,11 +271,11 @@ namespace Greenshot.Forms if (!matchedThisProcess) { using Process currentProcess = Process.GetCurrentProcess(); - instanceInfo.Append(index + ": ").AppendLine(Kernel32Api.GetProcessPath(currentProcess.Id)); + instanceInfo.Append(index).Append(": ").AppendLine(Kernel32Api.GetProcessPath(currentProcess.Id)); } // A dirty fix to make sure the message box is visible as a Greenshot window on the taskbar - using Form dummyForm = new Form + using Form dummyForm = new() { Icon = GreenshotResources.GetGreenshotIcon(), ShowInTaskbar = true, @@ -339,7 +339,7 @@ namespace Greenshot.Forms private static void SendData(CopyDataTransport dataTransport) { string appName = Application.ProductName; - CopyData copyData = new CopyData(); + CopyData copyData = new(); copyData.Channels.Add(appName); copyData.Channels[appName].Send(dataTransport); } @@ -376,13 +376,13 @@ namespace Greenshot.Forms private AboutForm _aboutForm; // Timer for the double click test - private readonly Timer _doubleClickTimer = new Timer(); + private readonly Timer _doubleClickTimer = new(); public MainForm(CopyDataTransport dataTransport) { var uiContext = TaskScheduler.FromCurrentSynchronizationContext(); SimpleServiceProvider.Current.AddService(uiContext); - + // The most important form is this SimpleServiceProvider.Current.AddService(this); // Also as itself @@ -395,9 +395,9 @@ namespace Greenshot.Forms EditorInitialize.Initialize(); // Factory for surface objects - ISurface SurfaceFactory() => new Surface(); + static ISurface SurfaceFactory() => new Surface(); - SimpleServiceProvider.Current.AddService((Func) SurfaceFactory); + SimpleServiceProvider.Current.AddService((Func)SurfaceFactory); // // The InitializeComponent() call is required for Windows Forms designer support. @@ -524,7 +524,7 @@ namespace Greenshot.Forms new EmailDestination(), new PickerDestination() }; - + bool useEditor = false; if (WindowsVersion.IsWindows10OrLater) { @@ -536,7 +536,8 @@ namespace Greenshot.Forms { useEditor = true; } - } else + } + else { useEditor = true; } @@ -587,7 +588,7 @@ namespace Greenshot.Forms private void CopyDataDataReceived(object sender, CopyDataReceivedEventArgs copyDataReceivedEventArgs) { // Cast the data to the type of object we sent: - var dataTransport = (CopyDataTransport) copyDataReceivedEventArgs.Data; + var dataTransport = (CopyDataTransport)copyDataReceivedEventArgs.Data; HandleDataTransport(dataTransport); } @@ -614,7 +615,7 @@ namespace Greenshot.Forms try { IniConfig.Reload(); - Invoke((MethodInvoker) delegate + Invoke((MethodInvoker)delegate { // Even update language when needed UpdateUi(); @@ -635,7 +636,7 @@ namespace Greenshot.Forms LOG.InfoFormat("Open file requested: {0}", filename); if (File.Exists(filename)) { - BeginInvoke((MethodInvoker) delegate { CaptureHelper.CaptureFile(filename); }); + BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureFile(filename); }); } else { @@ -786,7 +787,7 @@ namespace Greenshot.Forms } bool success = true; - StringBuilder failedKeys = new StringBuilder(); + StringBuilder failedKeys = new(); if (!RegisterWrapper(failedKeys, "CaptureRegion", "RegionHotkey", _instance.CaptureRegion, ignoreFailedRegistration)) { @@ -878,7 +879,7 @@ namespace Greenshot.Forms /// private static bool HandleFailedHotkeyRegistration(string failedKeys) { - bool success = false; + const bool success = false; var warningTitle = Language.GetString(LangKey.warning); var message = string.Format(Language.GetString(LangKey.warning_hotkeys), failedKeys, IsOneDriveBlockingHotkey() ? " (OneDrive)" : ""); var mainForm = SimpleServiceProvider.Current.GetInstance(); @@ -887,13 +888,13 @@ namespace Greenshot.Forms { LOG.DebugFormat("Re-trying to register hotkeys"); HotkeyControl.UnregisterHotkeys(); - success = RegisterHotkeys(false); + return RegisterHotkeys(false); } else if (dr == DialogResult.Ignore) { LOG.DebugFormat("Ignoring failed hotkey registration"); HotkeyControl.UnregisterHotkeys(); - success = RegisterHotkeys(true); + return RegisterHotkeys(true); } return success; @@ -917,7 +918,6 @@ namespace Greenshot.Forms } } - private void MainFormFormClosing(object sender, FormClosingEventArgs e) { LOG.DebugFormat("Mainform closing, reason: {0}", e.CloseReason); @@ -929,7 +929,7 @@ namespace Greenshot.Forms { Hide(); ShowInTaskbar = false; - + // TODO: Do we really need this? //using var loProcess = Process.GetCurrentProcess(); //loProcess.MaxWorkingSet = (IntPtr)750000; @@ -948,7 +948,7 @@ namespace Greenshot.Forms var openFileDialog = new OpenFileDialog { - Filter = @$"Image files ({string.Join(", ", extensions)})|{string.Join("; ", extensions)}" + Filter = $"Image files ({string.Join(", ", extensions)})|{string.Join("; ", extensions)}" }; if (openFileDialog.ShowDialog() != DialogResult.OK) { @@ -999,7 +999,6 @@ namespace Greenshot.Forms } } - private void ContextMenuOpening(object sender, CancelEventArgs e) { var factor = DeviceDpi / 96f; @@ -1046,7 +1045,7 @@ namespace Greenshot.Forms { // birthday var resources = new ComponentResourceManager(typeof(MainForm)); - contextmenu_donate.Image = (Image) resources.GetObject("contextmenu_present.Image"); + contextmenu_donate.Image = (Image)resources.GetObject("contextmenu_present.Image"); } } @@ -1075,7 +1074,7 @@ namespace Greenshot.Forms { contextmenu_captureie.Enabled = true; contextmenu_captureiefromlist.Enabled = true; - Dictionary counter = new Dictionary(); + Dictionary counter = new(); foreach (KeyValuePair tabData in tabs) { @@ -1096,14 +1095,7 @@ namespace Greenshot.Forms captureIeTabItem.Tag = new KeyValuePair(tabData.Key, index++); captureIeTabItem.Click += Contextmenu_CaptureIeFromList_Click; contextmenu_captureiefromlist.DropDownItems.Add(captureIeTabItem); - if (counter.ContainsKey(tabData.Key)) - { - counter[tabData.Key] = index; - } - else - { - counter.Add(tabData.Key, index); - } + counter[tabData.Key] = index; } } else @@ -1125,15 +1117,17 @@ namespace Greenshot.Forms /// private void MultiScreenDropDownOpening(object sender, EventArgs e) { - ToolStripMenuItem captureScreenMenuItem = (ToolStripMenuItem) sender; + ToolStripMenuItem captureScreenMenuItem = (ToolStripMenuItem)sender; captureScreenMenuItem.DropDownItems.Clear(); if (DisplayInfo.AllDisplayInfos.Length <= 1) return; var allScreensBounds = DisplayInfo.ScreenBounds; var captureScreenItem = new ToolStripMenuItem(Language.GetString(LangKey.contextmenu_capturefullscreen_all)); - captureScreenItem.Click += delegate { - BeginInvoke((MethodInvoker) delegate { + captureScreenItem.Click += delegate + { + BeginInvoke((MethodInvoker)delegate + { CaptureHelper.CaptureFullscreen(false, ScreenCaptureMode.FullScreen); }); }; @@ -1143,7 +1137,7 @@ namespace Greenshot.Forms { var displayToCapture = displayInfo; string deviceAlignment = displayToCapture.DeviceName; - + if (displayInfo.Bounds.Top == allScreensBounds.Top && displayInfo.Bounds.Bottom != allScreensBounds.Bottom) { deviceAlignment += " " + Language.GetString(LangKey.contextmenu_capturefullscreen_top); @@ -1165,7 +1159,7 @@ namespace Greenshot.Forms captureScreenItem = new ToolStripMenuItem(deviceAlignment); captureScreenItem.Click += delegate { - BeginInvoke((MethodInvoker) delegate + BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureRegion(false, displayToCapture.Bounds); }); @@ -1181,7 +1175,7 @@ namespace Greenshot.Forms /// private void MultiScreenDropDownClosing(object sender, EventArgs e) { - ToolStripMenuItem captureScreenMenuItem = (ToolStripMenuItem) sender; + ToolStripMenuItem captureScreenMenuItem = (ToolStripMenuItem)sender; captureScreenMenuItem.DropDownItems.Clear(); } @@ -1193,7 +1187,7 @@ namespace Greenshot.Forms // The Capture window context menu item used to go to the following code: // captureForm.MakeCapture(CaptureMode.Window, false); // Now we check which windows are there to capture - ToolStripMenuItem captureWindowFromListMenuItem = (ToolStripMenuItem) sender; + ToolStripMenuItem captureWindowFromListMenuItem = (ToolStripMenuItem)sender; AddCaptureWindowMenuItems(captureWindowFromListMenuItem, Contextmenu_CaptureWindowFromList_Click); } @@ -1206,12 +1200,7 @@ namespace Greenshot.Forms { if (sender is not ToolStripMenuItem captureWindowItem) return; var window = captureWindowItem.Tag as WindowDetails; - if (_thumbnailForm == null) - { - _thumbnailForm = new ThumbnailForm(); - } - - _thumbnailForm.ShowThumbnail(window, captureWindowItem.GetCurrentParent().TopLevelControl); + (_thumbnailForm ??= new ThumbnailForm()).ShowThumbnail(window, captureWindowItem.GetCurrentParent().TopLevelControl); } private void HideThumbnailOnLeave(object sender, EventArgs e) @@ -1274,42 +1263,42 @@ namespace Greenshot.Forms private void CaptureAreaToolStripMenuItemClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker) delegate { CaptureHelper.CaptureRegion(false); }); + BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureRegion(false); }); } private void CaptureClipboardToolStripMenuItemClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker) delegate { CaptureHelper.CaptureClipboard(); }); + BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureClipboard(); }); } private void OpenFileToolStripMenuItemClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker) delegate { CaptureFile(); }); + BeginInvoke((MethodInvoker)delegate { CaptureFile(); }); } private void CaptureFullScreenToolStripMenuItemClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker) delegate { CaptureHelper.CaptureFullscreen(false, _conf.ScreenCaptureMode); }); + BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureFullscreen(false, _conf.ScreenCaptureMode); }); } private void Contextmenu_CaptureLastRegionClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker) delegate { CaptureHelper.CaptureLastRegion(false); }); + BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureLastRegion(false); }); } private void Contextmenu_CaptureWindow_Click(object sender, EventArgs e) { - BeginInvoke((MethodInvoker) delegate { CaptureHelper.CaptureWindowInteractive(false); }); + BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureWindowInteractive(false); }); } private void Contextmenu_CaptureWindowFromList_Click(object sender, EventArgs e) { - ToolStripMenuItem clickedItem = (ToolStripMenuItem) sender; - BeginInvoke((MethodInvoker) delegate + ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender; + BeginInvoke((MethodInvoker)delegate { try { - WindowDetails windowToCapture = (WindowDetails) clickedItem.Tag; + WindowDetails windowToCapture = (WindowDetails)clickedItem.Tag; CaptureHelper.CaptureWindow(windowToCapture); } catch (Exception exception) @@ -1332,9 +1321,9 @@ namespace Greenshot.Forms return; } - ToolStripMenuItem clickedItem = (ToolStripMenuItem) sender; - KeyValuePair tabData = (KeyValuePair) clickedItem.Tag; - BeginInvoke((MethodInvoker) delegate + ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender; + KeyValuePair tabData = (KeyValuePair)clickedItem.Tag; + BeginInvoke((MethodInvoker)delegate { WindowDetails ieWindowToCapture = tabData.Key; if (ieWindowToCapture != null && (!ieWindowToCapture.Visible || ieWindowToCapture.Iconic)) @@ -1369,7 +1358,7 @@ namespace Greenshot.Forms /// EventArgs private void Contextmenu_DonateClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker) delegate { Process.Start("https://getgreenshot.org/support/?version=" + EnvironmentInfo.GetGreenshotVersion(true)); }); + BeginInvoke((MethodInvoker)delegate { Process.Start("https://getgreenshot.org/support/?version=" + EnvironmentInfo.GetGreenshotVersion(true)); }); } /// @@ -1379,7 +1368,7 @@ namespace Greenshot.Forms /// private void Contextmenu_SettingsClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker) ShowSetting); + BeginInvoke((MethodInvoker)ShowSetting); } /// @@ -1486,7 +1475,7 @@ namespace Greenshot.Forms if (!_conf.Values["CaptureMousepointer"].IsFixed) { // For the capture mouse-cursor option - ToolStripMenuSelectListItem captureMouseItem = new ToolStripMenuSelectListItem + ToolStripMenuSelectListItem captureMouseItem = new() { Text = Language.GetString("settings_capture_mousepointer"), Checked = _conf.CaptureMousepointer, @@ -1546,7 +1535,7 @@ namespace Greenshot.Forms iniValue = _conf.Values[propertyName]; if (iniValue.Attributes.LanguageKey != null && !iniValue.IsFixed) { - selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool) iniValue.Value); + selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); } } } @@ -1566,13 +1555,13 @@ namespace Greenshot.Forms iniValue = _conf.Values["PlayCameraSound"]; if (!iniValue.IsFixed) { - selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool) iniValue.Value); + selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); } iniValue = _conf.Values["ShowTrayNotification"]; if (!iniValue.IsFixed) { - selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool) iniValue.Value); + selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); } if (selectList.DropDownItems.Count > 0) @@ -1584,8 +1573,8 @@ namespace Greenshot.Forms private void QuickSettingCaptureModeChanged(object sender, EventArgs e) { - ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs) e).Item; - WindowCaptureMode windowsCaptureMode = (WindowCaptureMode) item.Data; + ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item; + WindowCaptureMode windowsCaptureMode = (WindowCaptureMode)item.Data; if (item.Checked) { _conf.WindowCaptureMode = windowsCaptureMode; @@ -1594,7 +1583,7 @@ namespace Greenshot.Forms private void QuickSettingBoolItemChanged(object sender, EventArgs e) { - ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs) e).Item; + ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item; if (item.Data is IniValue iniValue) { iniValue.Value = item.Checked; @@ -1604,8 +1593,8 @@ namespace Greenshot.Forms private void QuickSettingDestinationChanged(object sender, EventArgs e) { - ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs) e).Item; - IDestination selectedDestination = (IDestination) item.Data; + ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item; + IDestination selectedDestination = (IDestination)item.Data; if (item.Checked) { if (selectedDestination.Designation.Equals(nameof(WellKnownDestinations.Picker))) @@ -1668,7 +1657,7 @@ namespace Greenshot.Forms string exceptionText = EnvironmentInfo.BuildReport(exceptionToLog); LOG.Error("Exception caught in the UnhandledException handler."); LOG.Error(exceptionText); - if (exceptionText != null && exceptionText.Contains("InputLanguageChangedEventArgs")) + if (exceptionText?.Contains("InputLanguageChangedEventArgs") == true) { // Ignore for BUG-1809 return; @@ -1683,7 +1672,7 @@ namespace Greenshot.Forms string exceptionText = EnvironmentInfo.BuildReport(exceptionToLog); LOG.Error("Exception caught in the ThreadException handler."); LOG.Error(exceptionText); - if (exceptionText != null && exceptionText.Contains("InputLanguageChangedEventArgs")) + if (exceptionText?.Contains("InputLanguageChangedEventArgs") == true) { // Ignore for BUG-1809 return; @@ -1740,7 +1729,7 @@ namespace Greenshot.Forms { _doubleClickTimer.Elapsed -= NotifyIconSingleClickTest; _doubleClickTimer.Stop(); - BeginInvoke((MethodInvoker) delegate { NotifyIconClick(_conf.LeftClickAction); }); + BeginInvoke((MethodInvoker)delegate { NotifyIconClick(_conf.LeftClickAction); }); } /// @@ -1849,7 +1838,7 @@ namespace Greenshot.Forms LOG.Info("Exit: " + EnvironmentInfo.EnvironmentToString(false)); // Close all open forms (except this), use a separate List to make sure we don't get a "InvalidOperationException: Collection was modified" - List formsToClose = new List(); + List formsToClose = new(); foreach (Form form in Application.OpenForms) { if (form.Handle != Handle && form.GetType() != typeof(ImageEditorForm)) @@ -1864,7 +1853,7 @@ namespace Greenshot.Forms { LOG.InfoFormat("Closing form: {0}", form.Name); Form formCapturedVariable = form; - Invoke((MethodInvoker) delegate { formCapturedVariable.Close(); }); + Invoke((MethodInvoker)delegate { formCapturedVariable.Close(); }); } catch (Exception e) { diff --git a/src/Greenshot/Forms/PrintOptionsDialog.cs b/src/Greenshot/Forms/PrintOptionsDialog.cs index 098dea374..96cb6a66c 100644 --- a/src/Greenshot/Forms/PrintOptionsDialog.cs +++ b/src/Greenshot/Forms/PrintOptionsDialog.cs @@ -39,7 +39,6 @@ namespace Greenshot.Forms checkbox_dontaskagain.Checked = false; } - private void Button_okClick(object sender, EventArgs e) { // update config diff --git a/src/Greenshot/Forms/SettingsForm.cs b/src/Greenshot/Forms/SettingsForm.cs index 12f2f07cb..a182cd13a 100644 --- a/src/Greenshot/Forms/SettingsForm.cs +++ b/src/Greenshot/Forms/SettingsForm.cs @@ -49,7 +49,7 @@ namespace Greenshot.Forms public partial class SettingsForm : BaseForm { private static readonly ILog Log = LogManager.GetLogger(typeof(SettingsForm)); - private readonly ToolTip _toolTip = new ToolTip(); + private readonly ToolTip _toolTip = new(); private bool _inHotkey; private int _daysBetweenCheckPreviousValue; @@ -102,7 +102,7 @@ namespace Greenshot.Forms item.Checked = coreConfiguration.ClipboardFormats.Contains(clipboardFormat); } - _daysBetweenCheckPreviousValue = (int) numericUpDown_daysbetweencheck.Value; + _daysBetweenCheckPreviousValue = (int)numericUpDown_daysbetweencheck.Value; DisplayPluginTab(); UpdateUi(); ExpertSettingsEnableState(false); @@ -117,7 +117,7 @@ namespace Greenshot.Forms /// EventArgs private void NumericUpDownDaysbetweencheckOnValueChanged(object sender, EventArgs eventArgs) { - int currentValue = (int) numericUpDown_daysbetweencheck.Value; + int currentValue = (int)numericUpDown_daysbetweencheck.Value; // Check if we can into the forbidden range if (currentValue > 0 && currentValue < 7) @@ -132,17 +132,17 @@ namespace Greenshot.Forms } } - if ((int) numericUpDown_daysbetweencheck.Value < 0) + if ((int)numericUpDown_daysbetweencheck.Value < 0) { numericUpDown_daysbetweencheck.Value = 0; } - if ((int) numericUpDown_daysbetweencheck.Value > 365) + if ((int)numericUpDown_daysbetweencheck.Value > 365) { numericUpDown_daysbetweencheck.Value = 365; } - _daysBetweenCheckPreviousValue = (int) numericUpDown_daysbetweencheck.Value; + _daysBetweenCheckPreviousValue = (int)numericUpDown_daysbetweencheck.Value; } private void EnterHotkeyControl(object sender, EventArgs e) @@ -197,7 +197,6 @@ namespace Greenshot.Forms comboBox.SelectedItem = Language.Translate(selectedValue); } - /// /// Get the selected enum value from the combobox, uses generics /// @@ -207,7 +206,7 @@ namespace Greenshot.Forms { string enumTypeName = typeof(TEnum).Name; string selectedValue = comboBox.SelectedItem as string; - TEnum[] availableValues = (TEnum[]) Enum.GetValues(typeof(TEnum)); + TEnum[] availableValues = (TEnum[])Enum.GetValues(typeof(TEnum)); TEnum returnValue = availableValues[0]; foreach (TEnum enumValue in availableValues) { @@ -251,7 +250,7 @@ namespace Greenshot.Forms private void DisplayPluginTab() { - if (!SimpleServiceProvider.Current.GetAllInstances().Any()) + if (SimpleServiceProvider.Current.GetAllInstances().Count == 0) { tabcontrol.TabPages.Remove(tab_plugins); return; @@ -402,7 +401,7 @@ namespace Greenshot.Forms { foreach (ListViewItem item in listview_clipboardformats.Items) { - ClipboardFormat cf = (ClipboardFormat) item.Tag; + ClipboardFormat cf = (ClipboardFormat)item.Tag; item.Text = Language.Translate(cf); } } @@ -423,7 +422,7 @@ namespace Greenshot.Forms listview_destinations.Items.Clear(); var scaledIconSize = DpiCalculator.ScaleWithDpi(coreConfiguration.IconSize, NativeDpiMethods.GetDpi(Handle)); listview_destinations.ListViewItemSorter = new ListviewWithDestinationComparer(); - ImageList imageList = new ImageList + ImageList imageList = new() { ImageSize = scaledIconSize }; @@ -555,7 +554,7 @@ namespace Greenshot.Forms var item = listview_clipboardformats.Items[index]; if (item.Checked) { - clipboardFormats.Add((ClipboardFormat) item.Tag); + clipboardFormats.Add((ClipboardFormat)item.Tag); } } @@ -569,7 +568,7 @@ namespace Greenshot.Forms coreConfiguration.OutputFileJpegQuality = trackBarJpegQuality.Value; - List destinations = new List(); + List destinations = new(); if (checkbox_picker.Checked) { destinations.Add(nameof(WellKnownDestinations.Picker)); @@ -586,11 +585,11 @@ namespace Greenshot.Forms } coreConfiguration.OutputDestinations = destinations; - coreConfiguration.CaptureDelay = (int) numericUpDownWaitTime.Value; + coreConfiguration.CaptureDelay = (int)numericUpDownWaitTime.Value; coreConfiguration.DWMBackgroundColor = colorButton_window_background.SelectedColor; - coreConfiguration.UpdateCheckInterval = (int) numericUpDown_daysbetweencheck.Value; + coreConfiguration.UpdateCheckInterval = (int)numericUpDown_daysbetweencheck.Value; - coreConfiguration.IconSize = new Size((int) numericUpdownIconSize.Value, (int) numericUpdownIconSize.Value); + coreConfiguration.IconSize = new Size((int)numericUpdownIconSize.Value, (int)numericUpdownIconSize.Value); try { @@ -655,7 +654,7 @@ namespace Greenshot.Forms if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { // Only change if there is a change, otherwise we might overwrite the environment variables - if (folderBrowserDialog1.SelectedPath != null && !folderBrowserDialog1.SelectedPath.Equals(FilenameHelper.FillVariables(textbox_storagelocation.Text, false))) + if (folderBrowserDialog1.SelectedPath?.Equals(FilenameHelper.FillVariables(textbox_storagelocation.Text, false)) == false) { textbox_storagelocation.Text = folderBrowserDialog1.SelectedPath; } @@ -667,12 +666,11 @@ namespace Greenshot.Forms textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(CultureInfo.InvariantCulture); } - private void BtnPatternHelpClick(object sender, EventArgs e) { string filenamepatternText = Language.GetString(LangKey.settings_message_filenamepattern); // Convert %NUM% to ${NUM} for old language files! - filenamepatternText = Regex.Replace(filenamepatternText, "%([a-zA-Z_0-9]+)%", @"${$1}"); + filenamepatternText = Regex.Replace(filenamepatternText, "%([a-zA-Z_0-9]+)%", "${$1}"); MessageBox.Show(filenamepatternText, Language.GetString(LangKey.settings_filenamepattern)); } @@ -693,8 +691,8 @@ namespace Greenshot.Forms WindowCaptureMode selectedWindowCaptureMode = GetSelected(combobox_window_capture_mode); if (combobox_language.SelectedItem != null) { - Log.Debug("Setting language to: " + (string) combobox_language.SelectedValue); - Language.CurrentLanguage = (string) combobox_language.SelectedValue; + Log.Debug("Setting language to: " + (string)combobox_language.SelectedValue); + Language.CurrentLanguage = (string)combobox_language.SelectedValue; } // Reflect language changes to the settings form @@ -848,15 +846,10 @@ namespace Greenshot.Forms if (firstDestination != null && firstDestination.Priority == secondDestination.Priority) { - return string.Compare(firstDestination.Description, secondDestination.Description, StringComparison.Ordinal); + return string.CompareOrdinal(firstDestination.Description, secondDestination.Description); } - if (firstDestination != null) - { - return firstDestination.Priority - secondDestination.Priority; - } - - return 0; + return firstDestination != null ? firstDestination.Priority - secondDestination.Priority : 0; } } } \ No newline at end of file diff --git a/src/Greenshot/Forms/ToolStripMenuSelectList.cs b/src/Greenshot/Forms/ToolStripMenuSelectList.cs index 2e2c9845c..6e73874b1 100644 --- a/src/Greenshot/Forms/ToolStripMenuSelectList.cs +++ b/src/Greenshot/Forms/ToolStripMenuSelectList.cs @@ -57,7 +57,6 @@ namespace Greenshot.Forms UpdateImage(); } - private void UpdateImage() { var newSize = DpiCalculator.ScaleWithDpi(CoreConfig.IconSize, _provideDeviceDpi.DeviceDpi); @@ -78,7 +77,7 @@ namespace Greenshot.Forms return; } - var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem) sender; + var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem)sender; _updateInProgress = true; if (toolStripMenuSelectListItem.Checked && !_multiCheckAllowed) { @@ -128,7 +127,6 @@ namespace Greenshot.Forms DropDownItems.Add(toolStripMenuSelectListItem); } - /// /// adds an item to the select list /// @@ -148,7 +146,7 @@ namespace Greenshot.Forms IEnumerator items = DropDownItems.GetEnumerator(); while (items.MoveNext()) { - var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem) items.Current; + var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem)items.Current; if (toolStripMenuSelectListItem != null) { toolStripMenuSelectListItem.Checked = false; diff --git a/src/Greenshot/Helpers/CaptureHelper.cs b/src/Greenshot/Helpers/CaptureHelper.cs index e51b51ebe..719e63cea 100644 --- a/src/Greenshot/Helpers/CaptureHelper.cs +++ b/src/Greenshot/Helpers/CaptureHelper.cs @@ -53,9 +53,8 @@ namespace Greenshot.Helpers private static readonly ILog Log = LogManager.GetLogger(typeof(CaptureHelper)); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); - + private List _windows = new(); - private WindowDetails _selectedCaptureWindow; private NativeRect _captureRect = NativeRect.Empty; private readonly bool _captureMouseCursor; private ICapture _capture; @@ -88,7 +87,7 @@ namespace Greenshot.Helpers // Unfortunately we can't dispose the capture, this might still be used somewhere else. _windows = null; - _selectedCaptureWindow = null; + SelectedCaptureWindow = null; _capture = null; // Empty working set after capturing if (CoreConfig.MinimizeWorkingSetSize) @@ -99,7 +98,7 @@ namespace Greenshot.Helpers public static void CaptureClipboard(IDestination destination = null) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.Clipboard); + using CaptureHelper captureHelper = new(CaptureMode.Clipboard); if (destination != null) { captureHelper.AddDestination(destination); @@ -110,25 +109,25 @@ namespace Greenshot.Helpers public static void CaptureRegion(bool captureMouse) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.Region, captureMouse); + using CaptureHelper captureHelper = new(CaptureMode.Region, captureMouse); captureHelper.MakeCapture(); } public static void CaptureRegion(bool captureMouse, IDestination destination) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.Region, captureMouse, destination); + using CaptureHelper captureHelper = new(CaptureMode.Region, captureMouse, destination); captureHelper.MakeCapture(); } public static void CaptureRegion(bool captureMouse, NativeRect region) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.Region, captureMouse); + using CaptureHelper captureHelper = new(CaptureMode.Region, captureMouse); captureHelper.MakeCapture(region); } public static void CaptureFullscreen(bool captureMouse, ScreenCaptureMode screenCaptureMode) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.FullScreen, captureMouse) + using CaptureHelper captureHelper = new(CaptureMode.FullScreen, captureMouse) { _screenCaptureMode = screenCaptureMode }; @@ -137,13 +136,13 @@ namespace Greenshot.Helpers public static void CaptureLastRegion(bool captureMouse) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.LastRegion, captureMouse); + using CaptureHelper captureHelper = new(CaptureMode.LastRegion, captureMouse); captureHelper.MakeCapture(); } public static void CaptureIe(bool captureMouse, WindowDetails windowToCapture) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.IE, captureMouse) + using CaptureHelper captureHelper = new(CaptureMode.IE, captureMouse) { SelectedCaptureWindow = windowToCapture }; @@ -152,13 +151,13 @@ namespace Greenshot.Helpers public static void CaptureWindow(bool captureMouse) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.ActiveWindow, captureMouse); + using CaptureHelper captureHelper = new(CaptureMode.ActiveWindow, captureMouse); captureHelper.MakeCapture(); } public static void CaptureWindow(WindowDetails windowToCapture) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.ActiveWindow) + using CaptureHelper captureHelper = new(CaptureMode.ActiveWindow) { SelectedCaptureWindow = windowToCapture }; @@ -167,13 +166,13 @@ namespace Greenshot.Helpers public static void CaptureWindowInteractive(bool captureMouse) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.Window, captureMouse); + using CaptureHelper captureHelper = new(CaptureMode.Window, captureMouse); captureHelper.MakeCapture(); } public static void CaptureFile(string filename, IDestination destination = null) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.File); + using CaptureHelper captureHelper = new(CaptureMode.File); if (destination != null) { @@ -185,7 +184,7 @@ namespace Greenshot.Helpers public static void ImportCapture(ICapture captureToImport) { - using CaptureHelper captureHelper = new CaptureHelper(CaptureMode.File) + using CaptureHelper captureHelper = new(CaptureMode.File) { _capture = captureToImport }; @@ -220,11 +219,7 @@ namespace Greenshot.Helpers _capture.CaptureDetails.AddDestination(destination); } - public WindowDetails SelectedCaptureWindow - { - get => _selectedCaptureWindow; - set => _selectedCaptureWindow = value; - } + public WindowDetails SelectedCaptureWindow { get; set; } private void DoCaptureFeedback() { @@ -254,7 +249,6 @@ namespace Greenshot.Helpers MakeCapture(); } - /// /// Make Capture with specified destinations /// @@ -507,11 +501,11 @@ namespace Greenshot.Helpers // Set capture title, fixing bug #3569703 foreach (WindowDetails window in WindowDetails.GetVisibleWindows()) { - NativePoint estimatedLocation = new NativePoint(CoreConfig.LastCapturedRegion.X + CoreConfig.LastCapturedRegion.Width / 2, - CoreConfig.LastCapturedRegion.Y + CoreConfig.LastCapturedRegion.Height / 2); + NativePoint estimatedLocation = new(CoreConfig.LastCapturedRegion.X + (CoreConfig.LastCapturedRegion.Width / 2), + CoreConfig.LastCapturedRegion.Y + (CoreConfig.LastCapturedRegion.Height / 2)); if (!window.Contains(estimatedLocation)) continue; - _selectedCaptureWindow = window; - _capture.CaptureDetails.Title = _selectedCaptureWindow.Text; + SelectedCaptureWindow = window; + _capture.CaptureDetails.Title = SelectedCaptureWindow.Text; break; } @@ -564,7 +558,7 @@ namespace Greenshot.Helpers { _windows = new List(); - Thread getWindowDetailsThread = new Thread(RetrieveWindowDetails) + Thread getWindowDetailsThread = new(RetrieveWindowDetails) { Name = "Retrieve window details", IsBackground = true @@ -730,7 +724,7 @@ namespace Greenshot.Helpers // Make sure the resolution is set correctly! if (_capture.CaptureDetails != null) { - ((Bitmap) _capture.Image)?.SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY); + ((Bitmap)_capture.Image)?.SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY); } DoCaptureFeedback(); @@ -745,7 +739,7 @@ namespace Greenshot.Helpers } // Create Surface with capture, this way elements can be added automatically (like the mouse cursor) - Surface surface = new Surface(_capture) + Surface surface = new(_capture) { Modified = !outputMade }; @@ -816,39 +810,39 @@ namespace Greenshot.Helpers { bool presupplied = false; Log.Debug("CaptureActiveWindow"); - if (_selectedCaptureWindow != null) + if (SelectedCaptureWindow != null) { Log.Debug("Using supplied window"); presupplied = true; } else { - _selectedCaptureWindow = WindowDetails.GetActiveWindow(); - if (_selectedCaptureWindow != null) + SelectedCaptureWindow = WindowDetails.GetActiveWindow(); + if (SelectedCaptureWindow != null) { if (Log.IsDebugEnabled) { - Log.DebugFormat("Capturing window: {0} with {1}", _selectedCaptureWindow.Text, _selectedCaptureWindow.WindowRectangle); + Log.DebugFormat("Capturing window: {0} with {1}", SelectedCaptureWindow.Text, SelectedCaptureWindow.WindowRectangle); } } } - if (_selectedCaptureWindow == null || (!presupplied && _selectedCaptureWindow.Iconic)) + if (SelectedCaptureWindow == null || (!presupplied && SelectedCaptureWindow.Iconic)) { Log.Warn("No window to capture!"); // Nothing to capture, code up in the stack will capture the full screen return false; } - if (!presupplied && _selectedCaptureWindow != null && _selectedCaptureWindow.Iconic) + if (!presupplied && SelectedCaptureWindow?.Iconic == true) { // Restore the window making sure it's visible! // This is done mainly for a screen capture, but some applications like Excel and TOAD have weird behaviour! - _selectedCaptureWindow.Restore(); + SelectedCaptureWindow.Restore(); } - _selectedCaptureWindow = SelectCaptureWindow(_selectedCaptureWindow); - if (_selectedCaptureWindow == null) + SelectedCaptureWindow = SelectCaptureWindow(SelectedCaptureWindow); + if (SelectedCaptureWindow == null) { Log.Warn("No window to capture, after SelectCaptureWindow!"); // Nothing to capture, code up in the stack will capture the full screen @@ -856,8 +850,8 @@ namespace Greenshot.Helpers } // Fix for Bug #3430560 - CoreConfig.LastCapturedRegion = _selectedCaptureWindow.WindowRectangle; - bool returnValue = CaptureWindow(_selectedCaptureWindow, _capture, CoreConfig.WindowCaptureMode) != null; + CoreConfig.LastCapturedRegion = SelectedCaptureWindow.WindowRectangle; + bool returnValue = CaptureWindow(SelectedCaptureWindow, _capture, CoreConfig.WindowCaptureMode) != null; return returnValue; } @@ -1176,13 +1170,13 @@ namespace Greenshot.Helpers previouslyActiveWindow?.ToForeground(); if (_capture.CaptureDetails != null) { - ((Bitmap) _capture.Image)?.SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY); + ((Bitmap)_capture.Image)?.SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY); } } private void CaptureWithFeedback() { - using CaptureForm captureForm = new CaptureForm(_capture, _windows); + using CaptureForm captureForm = new(_capture, _windows); // Make sure the form is hidden after showing, even if an exception occurs, so all errors will be shown DialogResult result; try @@ -1197,12 +1191,12 @@ namespace Greenshot.Helpers if (result != DialogResult.OK) return; - _selectedCaptureWindow = captureForm.SelectedCaptureWindow; + SelectedCaptureWindow = captureForm.SelectedCaptureWindow; _captureRect = captureForm.CaptureRectangle; // Get title - if (_selectedCaptureWindow != null) + if (SelectedCaptureWindow != null) { - _capture.CaptureDetails.Title = _selectedCaptureWindow.Text; + _capture.CaptureDetails.Title = SelectedCaptureWindow.Text; } if (_captureRect.Height > 0 && _captureRect.Width > 0) diff --git a/src/Greenshot/Helpers/CopyData.cs b/src/Greenshot/Helpers/CopyData.cs index 8cdc8aa24..88ca89cab 100644 --- a/src/Greenshot/Helpers/CopyData.cs +++ b/src/Greenshot/Helpers/CopyData.cs @@ -45,12 +45,11 @@ namespace Greenshot.Helpers [Serializable()] public class CopyDataTransport { - private readonly List> _commands; - public List> Commands => _commands; + public List> Commands { get; } public CopyDataTransport() { - _commands = new List>(); + Commands = new List>(); } public CopyDataTransport(CommandEnum command) : this() @@ -65,12 +64,12 @@ namespace Greenshot.Helpers public void AddCommand(CommandEnum command) { - _commands.Add(new KeyValuePair(command, null)); + Commands.Add(new KeyValuePair(command, null)); } public void AddCommand(CommandEnum command, string commandData) { - _commands.Add(new KeyValuePair(command, commandData)); + Commands.Add(new KeyValuePair(command, commandData)); } } @@ -88,7 +87,7 @@ namespace Greenshot.Helpers public class CopyData : NativeWindow, IDisposable { /// - /// Event raised when data is received on any of the channels + /// Event raised when data is received on any of the channels /// this class is subscribed to. /// public event CopyDataReceivedEventHandler CopyDataReceived; @@ -115,20 +114,20 @@ namespace Greenshot.Helpers { if (m.Msg == WM_COPYDATA) { - var cds = (COPYDATASTRUCT) Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT)); + var cds = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT)); if (cds.cbData > 0) { byte[] data = new byte[cds.cbData]; Marshal.Copy(cds.lpData, data, 0, cds.cbData); - MemoryStream stream = new MemoryStream(data); - BinaryFormatter b = new BinaryFormatter(); - CopyDataObjectData cdo = (CopyDataObjectData) b.Deserialize(stream); + MemoryStream stream = new(data); + BinaryFormatter b = new(); + CopyDataObjectData cdo = (CopyDataObjectData)b.Deserialize(stream); - if (_channels != null && _channels.Contains(cdo.Channel)) + if (_channels?.Contains(cdo.Channel) == true) { - CopyDataReceivedEventArgs d = new CopyDataReceivedEventArgs(cdo.Channel, cdo.Data, cdo.Sent); + CopyDataReceivedEventArgs d = new(cdo.Channel, cdo.Data, cdo.Sent); OnCopyDataReceived(d); - m.Result = (IntPtr) 1; + m.Result = (IntPtr)1; } } } @@ -295,7 +294,7 @@ namespace Greenshot.Helpers /// /// Returns the CopyDataChannel for the specified channelName /// - public CopyDataChannel this[string channelName] => (CopyDataChannel) Dictionary[channelName]; + public CopyDataChannel this[string channelName] => (CopyDataChannel)Dictionary[channelName]; /// /// Adds a new channel on which this application can send and @@ -303,7 +302,7 @@ namespace Greenshot.Helpers /// public void Add(string channelName) { - CopyDataChannel cdc = new CopyDataChannel(_owner, channelName); + CopyDataChannel cdc = new(_owner, channelName); Dictionary.Add(channelName, cdc); } @@ -348,7 +347,7 @@ namespace Greenshot.Helpers /// just been removed protected override void OnRemoveComplete(object key, object data) { - ((CopyDataChannel) data).Dispose(); + ((CopyDataChannel)data).Dispose(); OnRemove(key, data); } @@ -431,21 +430,20 @@ namespace Greenshot.Helpers AddChannel(); } - CopyDataObjectData cdo = new CopyDataObjectData(obj, ChannelName); - + CopyDataObjectData cdo = new(obj, ChannelName); // Try to do a binary serialization on obj. // This will throw and exception if the object to // be passed isn't serializable. - BinaryFormatter b = new BinaryFormatter(); - MemoryStream stream = new MemoryStream(); + BinaryFormatter b = new(); + MemoryStream stream = new(); b.Serialize(stream, cdo); stream.Flush(); // Now move the data into a pointer so we can send // it using WM_COPYDATA: // Get the length of the data: - int dataSize = (int) stream.Length; + int dataSize = (int)stream.Length; if (dataSize > 0) { // This isn't very efficient if your data is very large. @@ -467,7 +465,7 @@ namespace Greenshot.Helpers { if (GetProp(window.Handle, ChannelName) != IntPtr.Zero) { - COPYDATASTRUCT cds = new COPYDATASTRUCT + COPYDATASTRUCT cds = new() { cbData = dataSize, dwData = IntPtr.Zero, diff --git a/src/Greenshot/Helpers/IECaptureHelper.cs b/src/Greenshot/Helpers/IECaptureHelper.cs index 0da3d35dc..facfc841b 100644 --- a/src/Greenshot/Helpers/IECaptureHelper.cs +++ b/src/Greenshot/Helpers/IECaptureHelper.cs @@ -62,7 +62,7 @@ namespace Greenshot.Helpers // Bring window to the front ieWindowDetails.Restore(); // Get accessible - Accessible ieAccessible = new Accessible(directUiWindowDetails.Handle); + Accessible ieAccessible = new(directUiWindowDetails.Handle); // Activate Tab ieAccessible.ActivateIETab(tabIndex); } @@ -79,12 +79,8 @@ namespace Greenshot.Helpers return true; } - if (CoreConfig.WindowClassesToCheckForIE != null && CoreConfig.WindowClassesToCheckForIE.Contains(someWindow.ClassName)) - { - return someWindow.GetChild("Internet Explorer_Server") != null; - } - - return false; + return CoreConfig.WindowClassesToCheckForIE?.Contains(someWindow.ClassName) == true +&& someWindow.GetChild("Internet Explorer_Server") != null; } /// @@ -149,7 +145,7 @@ namespace Greenshot.Helpers browserWindows.Add(ieWindow, accessible.IETabCaptions); } } - else if (CoreConfig.WindowClassesToCheckForIE != null && CoreConfig.WindowClassesToCheckForIE.Contains(ieWindow.ClassName)) + else if (CoreConfig.WindowClassesToCheckForIE?.Contains(ieWindow.ClassName) == true) { var singleWindowText = new List(); try @@ -220,7 +216,7 @@ namespace Greenshot.Helpers IHTMLDocument2 document2; if (response != UIntPtr.Zero) { - document2 = (IHTMLDocument2) Accessible.ObjectFromLresult(response, typeof(IHTMLDocument).GUID, IntPtr.Zero); + document2 = (IHTMLDocument2)Accessible.ObjectFromLresult(response, typeof(IHTMLDocument).GUID, IntPtr.Zero); if (document2 == null) { Log.Error("No IHTMLDocument2 found"); @@ -289,7 +285,7 @@ namespace Greenshot.Helpers } // Get the content window handle for the shellWindow.Document - IOleWindow oleWindow = (IOleWindow) document2; + IOleWindow oleWindow = (IOleWindow)document2; IntPtr contentWindowHandle = IntPtr.Zero; oleWindow?.GetWindow(out contentWindowHandle); @@ -297,7 +293,7 @@ namespace Greenshot.Helpers { // Get the HTMLDocument to check the hasFocus // See: https://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/60c6c95d-377c-4bf4-860d-390840fce31c/ - IHTMLDocument4 document4 = (IHTMLDocument4) document2; + IHTMLDocument4 document4 = (IHTMLDocument4)document2; if (document4.hasFocus()) { @@ -393,7 +389,7 @@ namespace Greenshot.Helpers windowToCapture ??= WindowDetails.GetActiveWindow(); // Show backgroundform after retrieving the active window.. - BackgroundForm backgroundForm = new BackgroundForm(Language.GetString(LangKey.contextmenu_captureie), Language.GetString(LangKey.wait_ie_capture)); + BackgroundForm backgroundForm = new(Language.GetString(LangKey.contextmenu_captureie), Language.GetString(LangKey.wait_ie_capture)); backgroundForm.Show(); //BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(language.GetString(LangKey.contextmenu_captureie), language.GetString(LangKey.wait_ie_capture)); try @@ -455,7 +451,6 @@ namespace Greenshot.Helpers // LOG.Warn("An error occurred while creating the capture elements: ", elementsException); //} - if (returnBitmap == null) { return null; @@ -483,7 +478,7 @@ namespace Greenshot.Helpers { try { - Uri uri = new Uri(documentContainer.Url); + Uri uri = new(documentContainer.Url); capture.CaptureDetails.AddMetaData("URL", uri.OriginalString); // As the URL can hardly be used in a filename, the following can be used if (!string.IsNullOrEmpty(uri.Scheme)) @@ -655,7 +650,7 @@ namespace Greenshot.Helpers WindowDetails contentWindowDetails = documentContainer.ContentWindow; //Create a target bitmap to draw into with the calculated page size - Bitmap returnBitmap = new Bitmap(pageSize.Width, pageSize.Height, PixelFormat.Format24bppRgb); + Bitmap returnBitmap = new(pageSize.Width, pageSize.Height, PixelFormat.Format24bppRgb); using (Graphics graphicsTarget = Graphics.FromImage(returnBitmap)) { // Clear the target with the backgroundcolor @@ -741,8 +736,8 @@ namespace Greenshot.Helpers targetOffset = targetOffset.ChangeY(documentContainer.ScrollTop); // Draw the captured fragment to the target, but "crop" the scrollbars etc while capturing - NativeSize viewPortSize = new NativeSize(viewportWidth, viewportHeight); - NativeRect clientRectangle = new NativeRect(documentContainer.SourceLocation, viewPortSize); + NativeSize viewPortSize = new(viewportWidth, viewportHeight); + NativeRect clientRectangle = new(documentContainer.SourceLocation, viewPortSize); Image fragment = contentWindowDetails.PrintWindow(); if (fragment != null) { @@ -761,7 +756,7 @@ namespace Greenshot.Helpers // Crop to clientRectangle if (ImageHelper.Crop(ref fragment, ref clientRectangle)) { - NativePoint targetLocation = new NativePoint(documentContainer.DestinationLocation.X, documentContainer.DestinationLocation.Y); + NativePoint targetLocation = new(documentContainer.DestinationLocation.X, documentContainer.DestinationLocation.Y); Log.DebugFormat("Fragment targetLocation is {0}", targetLocation); targetLocation = targetLocation.Offset(targetOffset); Log.DebugFormat("After offsetting the fragment targetLocation is {0}", targetLocation); diff --git a/src/Greenshot/Helpers/IEInterop/IEContainer.cs b/src/Greenshot/Helpers/IEInterop/IEContainer.cs index 178dc5643..01cbaa703 100644 --- a/src/Greenshot/Helpers/IEInterop/IEContainer.cs +++ b/src/Greenshot/Helpers/IEInterop/IEContainer.cs @@ -36,22 +36,18 @@ namespace Greenshot.Helpers.IEInterop public class DocumentContainer { private static readonly ILog LOG = LogManager.GetLogger(typeof(DocumentContainer)); - private const int E_ACCESSDENIED = unchecked((int) 0x80070005L); - private static readonly Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046"); - private static readonly Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"); + private const int E_ACCESSDENIED = unchecked((int)0x80070005L); + private static readonly Guid IID_IWebBrowserApp = new("0002DF05-0000-0000-C000-000000000046"); + private static readonly Guid IID_IWebBrowser2 = new("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"); private static int _counter; private readonly NativePoint _startLocation = NativePoint.Empty; private IHTMLDocument2 _document2; private IHTMLDocument3 _document3; - private NativePoint _sourceLocation; - private NativePoint _destinationLocation; private NativeRect _viewportRectangle = NativeRect.Empty; private bool _isDtd; - private DocumentContainer _parent; private WindowDetails _contentWindow; private double _zoomLevelX = 1; private double _zoomLevelY = 1; - private readonly IList _frames = new List(); private DocumentContainer(IHTMLWindow2 frameWindow, WindowDetails contentWindow, DocumentContainer parent) { @@ -86,10 +82,10 @@ namespace Greenshot.Helpers.IEInterop // Ignore } - _parent = parent; + Parent = parent; // Calculate startLocation for the frames IHTMLWindow2 window2 = document2.parentWindow; - IHTMLWindow3 window3 = (IHTMLWindow3) window2; + IHTMLWindow3 window3 = (IHTMLWindow3)window2; NativePoint contentWindowLocation = contentWindow.WindowRectangle.Location; int x = window3.screenLeft - contentWindowLocation.X; int y = window3.screenTop - contentWindowLocation.Y; @@ -131,7 +127,7 @@ namespace Greenshot.Helpers.IEInterop _contentWindow = contentWindow; _document3 = document2 as IHTMLDocument3; // Check what access method is needed for the document - IHTMLDocument5 document5 = (IHTMLDocument5) document2; + IHTMLDocument5 document5 = (IHTMLDocument5)document2; //compatibility mode affects how height is computed _isDtd = false; @@ -156,22 +152,21 @@ namespace Greenshot.Helpers.IEInterop IHTMLWindow2 window2 = document2.parentWindow; //IHTMLWindow3 window3 = (IHTMLWindow3)document2.parentWindow; IHTMLScreen screen = window2.screen; - IHTMLScreen2 screen2 = (IHTMLScreen2) screen; - if (_parent != null) + IHTMLScreen2 screen2 = (IHTMLScreen2)screen; + if (Parent != null) { // Copy parent values - _zoomLevelX = _parent._zoomLevelX; - _zoomLevelY = _parent._zoomLevelY; - _viewportRectangle = _parent._viewportRectangle; + _zoomLevelX = Parent._zoomLevelX; + _zoomLevelY = Parent._zoomLevelY; + _viewportRectangle = Parent._viewportRectangle; } else { //DisableScrollbars(document2); // Calculate zoom level - _zoomLevelX = screen2.deviceXDPI / (double) screen2.logicalXDPI; - _zoomLevelY = screen2.deviceYDPI / (double) screen2.logicalYDPI; - + _zoomLevelX = screen2.deviceXDPI / (double)screen2.logicalXDPI; + _zoomLevelY = screen2.deviceYDPI / (double)screen2.logicalYDPI; // Calculate the viewport rectangle, needed if there is a frame around the html window LOG.DebugFormat("Screen {0}x{1}", ScaleX(screen.width), ScaleY(screen.height)); @@ -202,7 +197,6 @@ namespace Greenshot.Helpers.IEInterop LOG.Warn("Can't get certain properties for documents, using default. Due to: ", e); } - try { LOG.DebugFormat("Calculated location {0} for {1}", _startLocation, document2.title); @@ -225,28 +219,28 @@ namespace Greenshot.Helpers.IEInterop LOG.Warn("Problem while trying to get document url!", e); } - _sourceLocation = new NativePoint(ScaleX(_startLocation.X), ScaleY(_startLocation.Y)); - _destinationLocation = new NativePoint(ScaleX(_startLocation.X), ScaleY(_startLocation.Y)); + SourceLocation = new NativePoint(ScaleX(_startLocation.X), ScaleY(_startLocation.Y)); + DestinationLocation = new NativePoint(ScaleX(_startLocation.X), ScaleY(_startLocation.Y)); - if (_parent != null) + if (Parent != null) { return; } try { - IHTMLFramesCollection2 frameCollection = (IHTMLFramesCollection2) document2.frames; + IHTMLFramesCollection2 frameCollection = (IHTMLFramesCollection2)document2.frames; for (int frame = 0; frame < frameCollection.length; frame++) { try { IHTMLWindow2 frameWindow = frameCollection.item(frame); - DocumentContainer frameData = new DocumentContainer(frameWindow, contentWindow, this); + DocumentContainer frameData = new(frameWindow, contentWindow, this); // check if frame is hidden if (!frameData.IsHidden) { LOG.DebugFormat("Creating DocumentContainer for Frame {0} found in window with rectangle {1}", frameData.Name, frameData.SourceRectangle); - _frames.Add(frameData); + Frames.Add(frameData); } else { @@ -317,14 +311,14 @@ namespace Greenshot.Helpers.IEInterop oldElement = element; } while (element != null); - var elementLocation = new NativePoint((int) x, (int) y); - IHTMLElement2 element2 = (IHTMLElement2) frameElement; + var elementLocation = new NativePoint((int)x, (int)y); + IHTMLElement2 element2 = (IHTMLElement2)frameElement; IHTMLRect rec = element2.getBoundingClientRect(); var elementBoundingLocation = new NativePoint(rec.left, rec.top); // Release IHTMLRect ReleaseCom(rec); LOG.DebugFormat("Looking for iframe to correct at {0}", elementBoundingLocation); - foreach (DocumentContainer foundFrame in _frames) + foreach (DocumentContainer foundFrame in Frames) { NativePoint frameLocation = foundFrame.SourceLocation; if (frameLocation.Equals(elementBoundingLocation)) @@ -385,7 +379,7 @@ namespace Greenshot.Helpers.IEInterop try { // Convert IHTMLWindow2 to IWebBrowser2 using IServiceProvider. - IServiceProvider sp = (IServiceProvider) htmlWindow; + IServiceProvider sp = (IServiceProvider)htmlWindow; // Use IServiceProvider.QueryService to get IWebBrowser2 object. Guid webBrowserApp = IID_IWebBrowserApp; @@ -393,9 +387,9 @@ namespace Greenshot.Helpers.IEInterop sp.QueryService(ref webBrowserApp, ref webBrowser2, out var brws); // Get the document from IWebBrowser2. - IWebBrowser2 browser = (IWebBrowser2) brws; + IWebBrowser2 browser = (IWebBrowser2)brws; - return (IHTMLDocument2) browser.Document; + return (IHTMLDocument2)browser.Document; } catch (Exception ex2) { @@ -411,7 +405,7 @@ namespace Greenshot.Helpers.IEInterop { try { - string bgColor = (string) _document2.bgColor; + string bgColor = (string)_document2.bgColor; if (bgColor != null) { int rgbInt = int.Parse(bgColor.Substring(1), NumberStyles.HexNumber); @@ -431,30 +425,26 @@ namespace Greenshot.Helpers.IEInterop public WindowDetails ContentWindow => _contentWindow; - public DocumentContainer Parent - { - get { return _parent; } - set { _parent = value; } - } + public DocumentContainer Parent { get; set; } private int ScaleX(int physicalValue) { - return (int) Math.Round(physicalValue * _zoomLevelX, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue * _zoomLevelX, MidpointRounding.AwayFromZero); } private int ScaleY(int physicalValue) { - return (int) Math.Round(physicalValue * _zoomLevelY, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue * _zoomLevelY, MidpointRounding.AwayFromZero); } private int UnscaleX(int physicalValue) { - return (int) Math.Round(physicalValue / _zoomLevelX, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue / _zoomLevelX, MidpointRounding.AwayFromZero); } private int UnscaleY(int physicalValue) { - return (int) Math.Round(physicalValue / _zoomLevelY, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue / _zoomLevelY, MidpointRounding.AwayFromZero); } /// @@ -497,7 +487,7 @@ namespace Greenshot.Helpers.IEInterop /// public int GetAttributeAsInt(string attribute) { - int retVal = (int) GetAttribute(attribute); + int retVal = (int)GetAttribute(attribute); return retVal; } @@ -517,49 +507,41 @@ namespace Greenshot.Helpers.IEInterop public int ScrollHeight => ScaleY(GetAttributeAsInt("scrollHeight")); - public NativePoint SourceLocation - { - get { return _sourceLocation; } - set { _sourceLocation = value; } - } + public NativePoint SourceLocation { get; set; } - public NativeSize SourceSize => new NativeSize(ClientWidth, ClientHeight); + public NativeSize SourceSize => new(ClientWidth, ClientHeight); - public NativeRect SourceRectangle => new NativeRect(SourceLocation, SourceSize); + public NativeRect SourceRectangle => new(SourceLocation, SourceSize); - public int SourceLeft => _sourceLocation.X; + public int SourceLeft => SourceLocation.X; - public int SourceTop => _sourceLocation.Y; + public int SourceTop => SourceLocation.Y; - public int SourceRight => _sourceLocation.X + ClientWidth; + public int SourceRight => SourceLocation.X + ClientWidth; - public int SourceBottom => _sourceLocation.Y + ClientHeight; + public int SourceBottom => SourceLocation.Y + ClientHeight; - public NativePoint DestinationLocation - { - get { return _destinationLocation; } - set { _destinationLocation = value; } - } + public NativePoint DestinationLocation { get; set; } - public NativeSize DestinationSize => new NativeSize(ScrollWidth, ScrollHeight); + public NativeSize DestinationSize => new(ScrollWidth, ScrollHeight); - public NativeRect DestinationRectangle => new NativeRect(DestinationLocation, DestinationSize); + public NativeRect DestinationRectangle => new(DestinationLocation, DestinationSize); public int DestinationLeft { - get { return _destinationLocation.X; } - set { _destinationLocation = _destinationLocation.ChangeX(value); } + get { return DestinationLocation.X; } + set { DestinationLocation = DestinationLocation.ChangeX(value); } } public int DestinationTop { - get { return _destinationLocation.Y; } - set { _destinationLocation = _destinationLocation.ChangeY(value); } + get { return DestinationLocation.Y; } + set { DestinationLocation = DestinationLocation.ChangeY(value); } } - public int DestinationRight => _destinationLocation.X + ScrollWidth; + public int DestinationRight => DestinationLocation.X + ScrollWidth; - public int DestinationBottom => _destinationLocation.Y + ScrollHeight; + public int DestinationBottom => DestinationLocation.Y + ScrollHeight; public int ScrollLeft { @@ -573,6 +555,6 @@ namespace Greenshot.Helpers.IEInterop set { SetAttribute("scrollTop", UnscaleY(value)); } } - public IList Frames => _frames; + public IList Frames { get; } = new List(); } } \ No newline at end of file diff --git a/src/Greenshot/Helpers/MailHelper.cs b/src/Greenshot/Helpers/MailHelper.cs index 39aa3c150..5e5ea8912 100644 --- a/src/Greenshot/Helpers/MailHelper.cs +++ b/src/Greenshot/Helpers/MailHelper.cs @@ -54,7 +54,7 @@ namespace Greenshot.Helpers /// public static void SendImage(string fullPath, string title) { - using MapiMailMessage message = new MapiMailMessage(title, null); + using MapiMailMessage message = new(title, null); message.Files.Add(fullPath); if (!string.IsNullOrEmpty(CoreConfig.MailApiTo)) { @@ -74,7 +74,6 @@ namespace Greenshot.Helpers message.ShowDialog(); } - /// /// Helper Method for creating an Email with Image Attachment /// @@ -236,7 +235,7 @@ namespace Greenshot.Helpers DeallocFiles(message); } - MAPI_CODES errorCode = (MAPI_CODES) Enum.ToObject(typeof(MAPI_CODES), error); + MAPI_CODES errorCode = (MAPI_CODES)Enum.ToObject(typeof(MAPI_CODES), error); // Check for error if (errorCode == MAPI_CODES.SUCCESS || errorCode == MAPI_CODES.USER_ABORT) @@ -294,7 +293,7 @@ namespace Greenshot.Helpers return IntPtr.Zero; } - if ((Files.Count <= 0) || (Files.Count > 100)) + if ((Files.Count == 0) || (Files.Count > 100)) { return IntPtr.Zero; } @@ -303,7 +302,7 @@ namespace Greenshot.Helpers int asize = Marshal.SizeOf(atype); IntPtr ptra = Marshal.AllocHGlobal(Files.Count * asize); - MapiFileDescriptor mfd = new MapiFileDescriptor + MapiFileDescriptor mfd = new() { position = -1 }; @@ -404,7 +403,6 @@ namespace Greenshot.Helpers // Intenationally blank } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class MapiMessage { @@ -473,7 +471,7 @@ namespace Greenshot.Helpers /// internal MapiMailMessage.MapiHelperInterop.MapiRecipDesc GetInteropRepresentation() { - MapiMailMessage.MapiHelperInterop.MapiRecipDesc interop = new MapiMailMessage.MapiHelperInterop.MapiRecipDesc(); + MapiMailMessage.MapiHelperInterop.MapiRecipDesc interop = new(); if (DisplayName == null) { @@ -485,7 +483,7 @@ namespace Greenshot.Helpers interop.Address = Address; } - interop.RecipientClass = (int) RecipientType; + interop.RecipientClass = (int)RecipientType; return interop; } diff --git a/src/Greenshot/Helpers/NotifyIconNotificationService.cs b/src/Greenshot/Helpers/NotifyIconNotificationService.cs index 707ebb411..48709a1df 100644 --- a/src/Greenshot/Helpers/NotifyIconNotificationService.cs +++ b/src/Greenshot/Helpers/NotifyIconNotificationService.cs @@ -130,7 +130,7 @@ namespace Greenshot.Helpers } _notifyIcon.BalloonTipClosed += BalloonClosedHandler; - _notifyIcon.ShowBalloonTip(timeout.HasValue ? (int) timeout.Value.TotalMilliseconds : 5000, @"Greenshot", message, level); + _notifyIcon.ShowBalloonTip(timeout.HasValue ? (int)timeout.Value.TotalMilliseconds : 5000, "Greenshot", message, level); } } } \ No newline at end of file diff --git a/src/Greenshot/Helpers/PluginHelper.cs b/src/Greenshot/Helpers/PluginHelper.cs index 3ed3d97c3..008c22f2e 100644 --- a/src/Greenshot/Helpers/PluginHelper.cs +++ b/src/Greenshot/Helpers/PluginHelper.cs @@ -87,7 +87,7 @@ namespace Greenshot.Helpers return false; } - var greenshotPlugin = (IGreenshotPlugin) listView.SelectedItems[0].Tag; + var greenshotPlugin = (IGreenshotPlugin)listView.SelectedItems[0].Tag; return greenshotPlugin?.IsConfigurable == true; } @@ -98,7 +98,7 @@ namespace Greenshot.Helpers return; } - var greenshotPlugin = (IGreenshotPlugin) listView.SelectedItems[0].Tag; + var greenshotPlugin = (IGreenshotPlugin)listView.SelectedItems[0].Tag; if (greenshotPlugin == null) { return; @@ -153,7 +153,7 @@ namespace Greenshot.Helpers public void ImportCapture(ICapture captureToImport) { var mainForm = SimpleServiceProvider.Current.GetInstance(); - mainForm.BeginInvoke((MethodInvoker) delegate { CaptureHelper.ImportCapture(captureToImport); }); + mainForm.BeginInvoke((MethodInvoker)delegate { CaptureHelper.ImportCapture(captureToImport); }); } /// @@ -173,7 +173,6 @@ namespace Greenshot.Helpers return capture; } - /// /// Private helper to find the plugins in the path /// @@ -224,14 +223,14 @@ namespace Greenshot.Helpers var pluginEntryName = $"{assemblyName}.{assemblyName.Replace("Greenshot.Plugin.", string.Empty)}Plugin"; var pluginEntryType = assembly.GetType(pluginEntryName, false, true); - if (CoreConfig.ExcludePlugins != null && CoreConfig.ExcludePlugins.Contains(pluginEntryName)) + if (CoreConfig.ExcludePlugins?.Contains(pluginEntryName) == true) { Log.WarnFormat("Exclude list: {0}", string.Join(",", CoreConfig.ExcludePlugins)); Log.WarnFormat("Skipping the excluded plugin {0} with version {1} from {2}", pluginEntryName, assembly.GetName().Version, pluginFile); continue; } - var plugin = (IGreenshotPlugin) Activator.CreateInstance(pluginEntryType); + var plugin = (IGreenshotPlugin)Activator.CreateInstance(pluginEntryType); if (plugin != null) { if (plugin.Initialize()) diff --git a/src/Greenshot/Helpers/PrintHelper.cs b/src/Greenshot/Helpers/PrintHelper.cs index 36bf8257b..d6a200412 100644 --- a/src/Greenshot/Helpers/PrintHelper.cs +++ b/src/Greenshot/Helpers/PrintHelper.cs @@ -46,8 +46,8 @@ namespace Greenshot.Helpers private ISurface _surface; private readonly ICaptureDetails _captureDetails; - private PrintDocument _printDocument = new PrintDocument(); - private PrintDialog _printDialog = new PrintDialog(); + private PrintDocument _printDocument = new(); + private PrintDialog _printDialog = new(); public PrintHelper(ISurface surface, ICaptureDetails captureDetails) { @@ -173,7 +173,7 @@ namespace Greenshot.Helpers DialogResult? ret = null; if (CoreConfig.OutputPrintPromptOptions) { - using PrintOptionsDialog printOptionsDialog = new PrintOptionsDialog(); + using PrintOptionsDialog printOptionsDialog = new(); ret = printOptionsDialog.ShowDialog(); } @@ -183,7 +183,7 @@ namespace Greenshot.Helpers private void DrawImageForPrint(object sender, PrintPageEventArgs e) { // Create the output settings - SurfaceOutputSettings printOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false); + SurfaceOutputSettings printOutputSettings = new(OutputFormat.png, 100, false); ApplyEffects(printOutputSettings); @@ -199,7 +199,7 @@ namespace Greenshot.Helpers if (CoreConfig.OutputPrintFooter) { footerString = FilenameHelper.FillPattern(CoreConfig.OutputPrintFooterPattern, _captureDetails, false); - using Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular); + using Font f = new(FontFamily.GenericSansSerif, 10, FontStyle.Regular); footerStringWidth = e.Graphics.MeasureString(footerString, f).Width; footerStringHeight = e.Graphics.MeasureString(footerString, f).Height; } @@ -208,9 +208,7 @@ namespace Greenshot.Helpers RectangleF pageRect = e.PageSettings.PrintableArea; if (e.PageSettings.Landscape) { - float origWidth = pageRect.Width; - pageRect.Width = pageRect.Height; - pageRect.Height = origWidth; + (pageRect.Height, pageRect.Width) = (pageRect.Width, pageRect.Height); } // Subtract the dateString height from the available area, this way the area stays free @@ -221,7 +219,7 @@ namespace Greenshot.Helpers // rotate the image if it fits the page better if (CoreConfig.OutputPrintAllowRotate) { - if (pageRect.Width > pageRect.Height && imageRect.Width < imageRect.Height || pageRect.Width < pageRect.Height && imageRect.Width > imageRect.Height) + if ((pageRect.Width > pageRect.Height && imageRect.Width < imageRect.Height) || (pageRect.Width < pageRect.Height && imageRect.Width > imageRect.Height)) { image.RotateFlip(RotateFlipType.Rotate270FlipNone); imageRect = image.GetBounds(ref gu); @@ -232,12 +230,12 @@ namespace Greenshot.Helpers } } - RectangleF printRect = new RectangleF(0, 0, imageRect.Width, imageRect.Height); + RectangleF printRect = new(0, 0, imageRect.Width, imageRect.Height); // scale the image to fit the page better if (CoreConfig.OutputPrintAllowEnlarge || CoreConfig.OutputPrintAllowShrink) { SizeF resizedRect = ScaleHelper.GetScaledSize(imageRect.Size, pageRect.Size, false); - if (CoreConfig.OutputPrintAllowShrink && resizedRect.Width < printRect.Width || CoreConfig.OutputPrintAllowEnlarge && resizedRect.Width > printRect.Width) + if ((CoreConfig.OutputPrintAllowShrink && resizedRect.Width < printRect.Width) || (CoreConfig.OutputPrintAllowEnlarge && resizedRect.Width > printRect.Width)) { printRect.Size = resizedRect; } @@ -248,8 +246,8 @@ namespace Greenshot.Helpers if (CoreConfig.OutputPrintFooter) { //printRect = new RectangleF(0, 0, printRect.Width, printRect.Height - (dateStringHeight * 2)); - using Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular); - e.Graphics.DrawString(footerString, f, Brushes.Black, pageRect.Width / 2 - footerStringWidth / 2, pageRect.Height); + using Font f = new(FontFamily.GenericSansSerif, 10, FontStyle.Regular); + e.Graphics.DrawString(footerString, f, Brushes.Black, (pageRect.Width / 2) - (footerStringWidth / 2), pageRect.Height); } e.Graphics.DrawImage(image, printRect, imageRect, GraphicsUnit.Pixel); diff --git a/src/Greenshot/Helpers/SoundHelper.cs b/src/Greenshot/Helpers/SoundHelper.cs index 796aec077..2a0feaa28 100644 --- a/src/Greenshot/Helpers/SoundHelper.cs +++ b/src/Greenshot/Helpers/SoundHelper.cs @@ -49,10 +49,10 @@ namespace Greenshot.Helpers { try { - ResourceManager resources = new ResourceManager("Greenshot.Sounds", Assembly.GetExecutingAssembly()); - _soundBuffer = (byte[]) resources.GetObject("camera"); + ResourceManager resources = new("Greenshot.Sounds", Assembly.GetExecutingAssembly()); + _soundBuffer = (byte[])resources.GetObject("camera"); - if (CoreConfig.NotificationSound != null && CoreConfig.NotificationSound.EndsWith(".wav")) + if (CoreConfig.NotificationSound?.EndsWith(".wav") == true) { try { @@ -82,7 +82,7 @@ namespace Greenshot.Helpers if (_soundBuffer != null) { //Thread playSoundThread = new Thread(delegate() { - var flags = SoundSettings.Async | SoundSettings.Memory| SoundSettings.NoWait| SoundSettings.NoStop; + const SoundSettings flags = SoundSettings.Async | SoundSettings.Memory | SoundSettings.NoWait | SoundSettings.NoStop; try { if (_gcHandle != null) WinMm.Play(_gcHandle.Value.AddrOfPinnedObject(), flags); diff --git a/src/Greenshot/Helpers/UpdateService.cs b/src/Greenshot/Helpers/UpdateService.cs index 16a73db14..8cfd3c630 100644 --- a/src/Greenshot/Helpers/UpdateService.cs +++ b/src/Greenshot/Helpers/UpdateService.cs @@ -40,9 +40,9 @@ namespace Greenshot.Helpers { private static readonly ILog Log = LogManager.GetLogger(typeof(UpdateService)); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); - private static readonly Uri UpdateFeed = new Uri("https://getgreenshot.org/update-feed.json"); - private static readonly Uri Downloads = new Uri("https://getgreenshot.org/downloads"); - private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + private static readonly Uri UpdateFeed = new("https://getgreenshot.org/update-feed.json"); + private static readonly Uri Downloads = new("https://getgreenshot.org/downloads"); + private readonly CancellationTokenSource _cancellationTokenSource = new(); /// /// Provides the current version @@ -177,7 +177,6 @@ namespace Greenshot.Helpers } } - /// /// This takes care of creating the toast view model, publishing it, and disposing afterwards /// diff --git a/src/Greenshot/Processors/TitleFixProcessor.cs b/src/Greenshot/Processors/TitleFixProcessor.cs index 4167243d3..78e71ba09 100644 --- a/src/Greenshot/Processors/TitleFixProcessor.cs +++ b/src/Greenshot/Processors/TitleFixProcessor.cs @@ -38,7 +38,7 @@ namespace Greenshot.Processors public TitleFixProcessor() { - List corruptKeys = new List(); + List corruptKeys = new(); foreach (string key in config.ActiveTitleFixes) { if (config.TitleFixMatcher.ContainsKey(key)) continue; @@ -48,7 +48,7 @@ namespace Greenshot.Processors } // Fix configuration if needed - if (corruptKeys.Count <= 0) return; + if (corruptKeys.Count == 0) return; foreach (string corruptKey in corruptKeys) { From de6644b543821d7c77b1725884a511aa969634ba Mon Sep 17 00:00:00 2001 From: Michael Adams Date: Thu, 14 Jul 2022 14:31:31 -0700 Subject: [PATCH 4/5] Deal with warnings --- src/.editorconfig | 8 + src/Greenshot.Base/Controls/AnimatingForm.cs | 13 +- src/Greenshot.Base/Controls/BackgroundForm.cs | 19 +- .../Controls/ExtendedWebBrowser.cs | 19 +- .../Controls/FormWithoutActivation.cs | 5 +- .../Controls/GreenshotComboBox.cs | 10 +- .../Controls/GreenshotDoubleClickButton.cs | 5 +- src/Greenshot.Base/Controls/GreenshotForm.cs | 41 +- src/Greenshot.Base/Controls/HotkeyControl.cs | 37 +- src/Greenshot.Base/Controls/OAuthLoginForm.cs | 4 +- src/Greenshot.Base/Controls/QualityDialog.cs | 5 +- .../Controls/SaveImageFileDialog.cs | 15 +- src/Greenshot.Base/Controls/ThumbnailForm.cs | 22 +- .../Core/AbstractDestination.cs | 26 +- src/Greenshot.Base/Core/AccessibleHelper.cs | 29 +- src/Greenshot.Base/Core/AnimationHelpers.cs | 77 +-- src/Greenshot.Base/Core/Cache.cs | 32 +- src/Greenshot.Base/Core/Capture.cs | 15 +- src/Greenshot.Base/Core/CaptureDetails.cs | 25 +- src/Greenshot.Base/Core/ClipboardHelper.cs | 65 +- src/Greenshot.Base/Core/CoreConfiguration.cs | 50 +- src/Greenshot.Base/Core/CredentialsHelper.cs | 5 +- src/Greenshot.Base/Core/DestinationHelper.cs | 22 +- .../Core/DisplayKeyAttribute.cs | 5 +- src/Greenshot.Base/Core/EffectConverter.cs | 23 +- src/Greenshot.Base/Core/EnvironmentInfo.cs | 135 ++-- src/Greenshot.Base/Core/EventDelay.cs | 8 +- src/Greenshot.Base/Core/FastBitmap.cs | 86 +-- .../FileFormatHandlerExtensions.cs | 14 +- src/Greenshot.Base/Core/FilenameHelper.cs | 20 +- src/Greenshot.Base/Core/GreenshotResources.cs | 15 +- src/Greenshot.Base/Core/IEHelper.cs | 5 +- src/Greenshot.Base/Core/ImageHelper.cs | 60 +- src/Greenshot.Base/Core/JSONHelper.cs | 104 ++- src/Greenshot.Base/Core/Language.cs | 68 +- src/Greenshot.Base/Core/NetworkHelper.cs | 19 +- .../Core/OAuth/LocalServerCodeReceiver.cs | 8 +- src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs | 14 +- src/Greenshot.Base/Core/OAuth/OAuthSession.cs | 66 +- src/Greenshot.Base/Core/PluginUtils.cs | 5 +- src/Greenshot.Base/Core/QuantizerHelper.cs | 131 ++-- .../Core/SimpleServiceProvider.cs | 10 +- src/Greenshot.Base/Core/StringExtensions.cs | 7 +- src/Greenshot.Base/Core/WindowCapture.cs | 16 +- src/Greenshot.Base/Core/WindowDetails.cs | 187 ++---- src/Greenshot.Base/Core/WindowsVersion.cs | 5 +- .../Core/WmInputLangChangeRequestFilter.cs | 5 +- src/Greenshot.Base/Effects/AdjustEffect.cs | 10 +- src/Greenshot.Base/Effects/BorderEffect.cs | 10 +- .../Effects/DropShadowEffect.cs | 10 +- src/Greenshot.Base/Effects/GrayscaleEffect.cs | 5 +- src/Greenshot.Base/Effects/InvertEffect.cs | 5 +- .../Effects/MonochromeEffect.cs | 10 +- .../Effects/ReduceColorsEffect.cs | 10 +- .../Effects/ResizeCanvasEffect.cs | 5 +- src/Greenshot.Base/Effects/ResizeEffect.cs | 5 +- src/Greenshot.Base/Effects/RotateEffect.cs | 5 +- src/Greenshot.Base/Effects/TornEdgeEffect.cs | 5 +- src/Greenshot.Base/IniFile/IniAttributes.cs | 15 +- src/Greenshot.Base/IniFile/IniConfig.cs | 23 +- src/Greenshot.Base/IniFile/IniSection.cs | 71 +-- src/Greenshot.Base/IniFile/IniValue.cs | 24 +- .../Interfaces/Drawing/IField.cs | 5 +- src/Greenshot.Base/Interfaces/IDestination.cs | 5 +- src/Greenshot.Base/Interfaces/Ocr/Line.cs | 5 +- .../Plugin/SurfaceOutputSettings.cs | 17 +- src/Greenshot.Base/Interop/COMWrapper.cs | 44 +- .../Interop/ComProgIdAttribute.cs | 5 +- .../Controls/BindableToolStripButton.cs | 10 +- .../Controls/BindableToolStripComboBox.cs | 10 +- src/Greenshot.Editor/Controls/ColorButton.cs | 16 +- .../CustomToolStripProfessionalRenderer.cs | 35 +- .../Controls/NonJumpingPanel.cs | 6 +- src/Greenshot.Editor/Controls/Pipette.cs | 20 +- .../Controls/ToolStripColorButton.cs | 16 +- .../Controls/ToolStripNumericUpDown.cs | 5 +- .../Destinations/EditorDestination.cs | 13 +- .../Drawing/Adorners/AbstractAdorner.cs | 20 +- .../Drawing/Adorners/MoveAdorner.cs | 5 +- .../Drawing/Adorners/ResizeAdorner.cs | 5 +- .../Drawing/Adorners/TargetAdorner.cs | 5 +- src/Greenshot.Editor/Drawing/CropContainer.cs | 35 +- .../Drawing/CursorContainer.cs | 15 +- .../Drawing/DrawableContainer.cs | 50 +- .../Drawing/DrawableContainerList.cs | 28 +- .../Drawing/EllipseContainer.cs | 24 +- .../Drawing/Fields/AbstractFieldHolder.cs | 72 +-- .../Fields/AbstractFieldHolderWithChildren.cs | 28 +- .../Binding/AbstractBindingConverter.cs | 13 +- .../Fields/Binding/BidirectionalBinding.cs | 15 +- .../DecimalDoublePercentageConverter.cs | 15 +- .../Fields/Binding/DecimalFloatConverter.cs | 15 +- .../Fields/Binding/DecimalIntConverter.cs | 15 +- .../Fields/Binding/NotNullValidator.cs | 10 +- src/Greenshot.Editor/Drawing/Fields/Field.cs | 26 +- .../Drawing/Fields/FieldAggregator.cs | 31 +- .../Drawing/Fields/FieldType.cs | 20 +- .../Drawing/FilterContainer.cs | 10 +- .../Drawing/Filters/AbstractFilter.cs | 17 +- .../Drawing/Filters/BlurFilter.cs | 2 +- .../Drawing/Filters/BrightnessFilter.cs | 5 +- .../Drawing/Filters/HighlightFilter.cs | 5 +- .../Drawing/Filters/MagnifierFilter.cs | 5 +- .../Drawing/Filters/PixelizationFilter.cs | 5 +- .../Drawing/FreehandContainer.cs | 12 +- .../Drawing/HighlightContainer.cs | 10 +- src/Greenshot.Editor/Drawing/IconContainer.cs | 20 +- .../Drawing/ImageContainer.cs | 15 +- src/Greenshot.Editor/Drawing/LineContainer.cs | 15 +- .../Drawing/ObfuscateContainer.cs | 17 +- src/Greenshot.Editor/Drawing/Positions.cs | 2 +- .../Drawing/RectangleContainer.cs | 17 +- .../Drawing/SpeechbubbleContainer.cs | 5 +- .../Drawing/StepLabelContainer.cs | 10 +- src/Greenshot.Editor/Drawing/Surface.cs | 62 +- src/Greenshot.Editor/Drawing/TextContainer.cs | 19 +- .../Drawing/VectorGraphicsContainer.cs | 5 +- src/Greenshot.Editor/EditorInitialize.cs | 5 +- .../AbstractFileFormatHandler.cs | 5 +- .../MetaFileFormatHandler.cs | 5 +- .../SvgFileFormatHandler.cs | 6 +- .../WpfFileFormatHandler.cs | 13 +- src/Greenshot.Editor/Forms/ColorDialog.cs | 25 +- .../Forms/ColorPickerToolStripButton.cs | 5 +- src/Greenshot.Editor/Forms/ImageEditorForm.cs | 336 +++------- .../Forms/MovableShowColorForm.cs | 18 +- .../Forms/ResizeSettingsForm.cs | 27 +- src/Greenshot.Editor/Helpers/Colors.cs | 5 +- .../Helpers/GeometryHelper.cs | 5 +- .../Helpers/LineAngleRoundBehavior.cs | 5 +- src/Greenshot.Editor/Helpers/ScaleHelper.cs | 25 +- .../Helpers/ShapeAngleRoundBehavior.cs | 5 +- .../Helpers/ToolStripItemEndisabler.cs | 15 +- .../Memento/AddElementMemento.cs | 5 +- .../Memento/AddElementsMemento.cs | 10 +- .../Memento/ChangeFieldHolderMemento.cs | 5 +- .../Memento/DeleteElementMemento.cs | 5 +- .../Memento/DeleteElementsMemento.cs | 10 +- .../DrawableContainerBoundsChangeMemento.cs | 5 +- .../Memento/SurfaceBackgroundChangeMemento.cs | 10 +- .../Memento/TextChangeMemento.cs | 10 +- src/Greenshot.Plugin.Box/BoxDestination.cs | 5 +- src/Greenshot.Plugin.Box/BoxPlugin.cs | 15 +- src/Greenshot.Plugin.Confluence/Confluence.cs | 9 +- .../ConfluenceDestination.cs | 33 +- .../ConfluencePlugin.cs | 29 +- .../ConfluenceUtils.cs | 66 +- .../EnumDisplayer.cs | 10 +- .../Forms/ConfluenceConfigurationForm.xaml.cs | 5 +- .../Forms/ConfluencePagePicker.xaml.cs | 10 +- .../Forms/ConfluenceSearch.xaml.cs | 55 +- .../Forms/ConfluenceUpload.xaml.cs | 15 +- .../Support/LanguageChangedEventManager.cs | 15 +- .../Support/LanguageXMLTranslationProvider.cs | 5 +- .../Support/TranslateExtension.cs | 5 +- .../Support/TranslationData.cs | 5 +- .../Web References/confluence/Reference.cs | 593 ++++++------------ .../DropboxDestination.cs | 5 +- src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs | 15 +- .../ExternalCommandConfiguration.cs | 9 +- .../ExternalCommandDestination.cs | 12 +- .../ExternalCommandPlugin.cs | 10 +- .../IconCache.cs | 17 +- .../SettingsForm.cs | 15 +- .../SettingsFormDetail.cs | 15 +- .../FlickrDestination.cs | 5 +- src/Greenshot.Plugin.Flickr/FlickrPlugin.cs | 15 +- .../GooglePhotosDestination.cs | 5 +- .../GooglePhotosPlugin.cs | 10 +- .../Forms/ImgurHistory.cs | 10 +- .../Forms/SettingsForm.cs | 5 +- .../ImgurDestination.cs | 5 +- src/Greenshot.Plugin.Imgur/ImgurInfo.cs | 11 +- src/Greenshot.Plugin.Imgur/ImgurPlugin.cs | 23 +- src/Greenshot.Plugin.Imgur/ImgurUtils.cs | 19 +- src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs | 10 +- src/Greenshot.Plugin.Jira/Forms/JiraForm.cs | 10 +- .../IssueTypeBitmapCache.cs | 10 +- src/Greenshot.Plugin.Jira/JiraConnector.cs | 37 +- src/Greenshot.Plugin.Jira/JiraDestination.cs | 5 +- src/Greenshot.Plugin.Jira/JiraDetails.cs | 10 +- src/Greenshot.Plugin.Jira/JiraMonitor.cs | 18 +- src/Greenshot.Plugin.Jira/JiraPlugin.cs | 13 +- src/Greenshot.Plugin.Jira/Log4NetLogger.cs | 10 +- .../Com/DisposableCom.cs | 5 +- .../Com/DisposableComImplementation.cs | 5 +- src/Greenshot.Plugin.Office/Com/Ole32Api.cs | 5 +- .../Com/OleAut32Api.cs | 5 +- .../Destinations/ExcelDestination.cs | 5 +- .../Destinations/OneNoteDestination.cs | 38 +- .../Destinations/PowerpointDestination.cs | 21 +- .../Destinations/WordDestination.cs | 5 +- .../OfficeExport/OutlookEmailExporter.cs | 32 +- .../OfficeExport/PowerpointExporter.cs | 21 +- .../OfficeExport/WordExporter.cs | 12 +- src/Greenshot.Plugin.Office/OfficePlugin.cs | 10 +- .../PhotobucketDestination.cs | 8 +- .../PhotobucketPlugin.cs | 5 +- .../Internal/MemoryRandomAccessStream.cs | 5 +- .../ToastNotificationService.cs | 17 +- src/Greenshot.Plugin.Win10/Win10Plugin.cs | 5 +- ...ontextMenuToolStripProfessionalRenderer.cs | 5 +- .../Destinations/ClipboardDestination.cs | 20 +- .../Destinations/EmailDestination.cs | 11 +- .../Destinations/FileWithDialogDestination.cs | 10 +- .../Destinations/PrinterDestination.cs | 15 +- src/Greenshot/Forms/BugReportForm.cs | 10 +- src/Greenshot/Forms/CaptureForm.cs | 33 +- src/Greenshot/Forms/LanguageDialog.cs | 5 +- src/Greenshot/Forms/MainForm.cs | 137 ++-- src/Greenshot/Forms/SettingsForm.cs | 81 +-- .../Forms/ToolStripMenuSelectList.cs | 10 +- src/Greenshot/GreenshotMain.cs | 9 +- src/Greenshot/Helpers/CaptureHelper.cs | 44 +- src/Greenshot/Helpers/CopyData.cs | 82 +-- src/Greenshot/Helpers/IECaptureHelper.cs | 5 +- .../Helpers/IEInterop/IEContainer.cs | 25 +- src/Greenshot/Helpers/MailHelper.cs | 10 +- .../Helpers/NotifyIconNotificationService.cs | 20 +- src/Greenshot/Helpers/PluginHelper.cs | 20 +- src/Greenshot/Helpers/PrintHelper.cs | 18 +- src/Greenshot/Helpers/StartupHelper.cs | 5 +- src/Greenshot/Helpers/UpdateService.cs | 5 +- 223 files changed, 1431 insertions(+), 3817 deletions(-) diff --git a/src/.editorconfig b/src/.editorconfig index ecc46e465..383823176 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -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 #### diff --git a/src/Greenshot.Base/Controls/AnimatingForm.cs b/src/Greenshot.Base/Controls/AnimatingForm.cs index 44f2389d8..ac197d302 100644 --- a/src/Greenshot.Base/Controls/AnimatingForm.cs +++ b/src/Greenshot.Base/Controls/AnimatingForm.cs @@ -54,17 +54,15 @@ namespace Greenshot.Base.Controls /// /// /// Number of frames, 1 if in Terminal Server Session - protected int FramesForMillis(int milliseconds) - { + protected int FramesForMillis(int milliseconds) => // If we are in a Terminal Server Session we return 1 - return IsTerminalServerSession ? 1 : milliseconds / VRefresh; - } + IsTerminalServerSession ? 1 : milliseconds / VRefresh; /// /// Calculate the interval for the timer to animate the frames /// /// Milliseconds for the interval - protected int Interval() => (int)1000 / VRefresh; + protected int Interval() => 1000 / VRefresh; /// /// Initialize the animation @@ -114,9 +112,6 @@ namespace Greenshot.Base.Controls /// /// This method will be called every frame, so implement your animation/redraw logic here. /// - protected virtual void Animate() - { - throw new NotImplementedException(); - } + protected virtual void Animate() => throw new NotImplementedException(); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/BackgroundForm.cs b/src/Greenshot.Base/Controls/BackgroundForm.cs index fed465e5e..900c314d1 100644 --- a/src/Greenshot.Base/Controls/BackgroundForm.cs +++ b/src/Greenshot.Base/Controls/BackgroundForm.cs @@ -23,6 +23,7 @@ using System; using System.Drawing; using System.Windows.Forms; using Greenshot.Base.Core; +using System.Linq; namespace Greenshot.Base.Controls { @@ -52,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(); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs b/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs index 05cc4c88a..87555cf70 100644 --- a/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs +++ b/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs @@ -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); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/FormWithoutActivation.cs b/src/Greenshot.Base/Controls/FormWithoutActivation.cs index 0a69bc043..721fb97ce 100644 --- a/src/Greenshot.Base/Controls/FormWithoutActivation.cs +++ b/src/Greenshot.Base/Controls/FormWithoutActivation.cs @@ -28,9 +28,6 @@ namespace Greenshot.Base.Controls /// public class FormWithoutActivation : Form { - protected override bool ShowWithoutActivation - { - get { return true; } - } + protected override bool ShowWithoutActivation => true; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/GreenshotComboBox.cs b/src/Greenshot.Base/Controls/GreenshotComboBox.cs index c82da65f4..8dba6baee 100644 --- a/src/Greenshot.Base/Controls/GreenshotComboBox.cs +++ b/src/Greenshot.Base/Controls/GreenshotComboBox.cs @@ -37,10 +37,7 @@ namespace Greenshot.Base.Controls [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] public string PropertyName { get; set; } - public GreenshotComboBox() - { - SelectedIndexChanged += delegate { StoreSelectedEnum(); }; - } + public GreenshotComboBox() => SelectedIndexChanged += delegate { StoreSelectedEnum(); }; public void SetValue(Enum currentValue) { @@ -108,9 +105,6 @@ namespace Greenshot.Base.Controls /// Get the selected enum value from the combobox, uses generics /// /// The enum value of the combobox - public Enum GetSelectedEnum() - { - return _selectedEnum; - } + public Enum GetSelectedEnum() => _selectedEnum; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/GreenshotDoubleClickButton.cs b/src/Greenshot.Base/Controls/GreenshotDoubleClickButton.cs index a70fff93c..e6e79f005 100644 --- a/src/Greenshot.Base/Controls/GreenshotDoubleClickButton.cs +++ b/src/Greenshot.Base/Controls/GreenshotDoubleClickButton.cs @@ -4,9 +4,6 @@ namespace Greenshot.Base.Controls { public class GreenshotDoubleClickButton : Button { - public GreenshotDoubleClickButton() - { - SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true); - } + public GreenshotDoubleClickButton() => SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true); } } diff --git a/src/Greenshot.Base/Controls/GreenshotForm.cs b/src/Greenshot.Base/Controls/GreenshotForm.cs index f8de3d6cd..a207ca8e0 100644 --- a/src/Greenshot.Base/Controls/GreenshotForm.cs +++ b/src/Greenshot.Base/Controls/GreenshotForm.cs @@ -72,15 +72,9 @@ namespace Greenshot.Base.Controls /// Used to check the designmode during a constructor /// /// - protected static bool IsInDesignMode - { - get - { - return (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1) || + 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 /// protected bool ToFront { get; set; } - protected GreenshotForm() - { - DpiChanged += (sender, dpiChangedEventArgs) => DpiChangedHandler(dpiChangedEventArgs.DeviceDpiOld, dpiChangedEventArgs.DeviceDpiNew); - } + protected GreenshotForm() => DpiChanged += (sender, dpiChangedEventArgs) => DpiChangedHandler(dpiChangedEventArgs.DeviceDpiOld, dpiChangedEventArgs.DeviceDpiNew); /// /// This is the basic DpiChangedHandler responsible for all the DPI relative changes @@ -148,19 +139,16 @@ namespace Greenshot.Base.Controls /// protected override void OnPaint(PaintEventArgs e) { - if (DesignMode) + if (DesignMode && !_isDesignModeLanguageSet) { - if (!_isDesignModeLanguageSet) + _isDesignModeLanguageSet = true; + try { - _isDesignModeLanguageSet = true; - try - { - ApplyLanguage(); - } - catch (Exception) - { - // ignored - } + ApplyLanguage(); + } + catch (Exception) + { + // ignored } } @@ -215,13 +203,10 @@ namespace Greenshot.Base.Controls /// 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); diff --git a/src/Greenshot.Base/Controls/HotkeyControl.cs b/src/Greenshot.Base/Controls/HotkeyControl.cs index bb6fa857f..19b85d280 100644 --- a/src/Greenshot.Base/Controls/HotkeyControl.cs +++ b/src/Greenshot.Base/Controls/HotkeyControl.cs @@ -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" /// - private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e) - { - e.Handled = true; - } + private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e) => e.Handled = true; /// /// Handles some misc keys, such as Ctrl+Delete and Shift+Insert @@ -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+ 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; /// /// Register a hotkey diff --git a/src/Greenshot.Base/Controls/OAuthLoginForm.cs b/src/Greenshot.Base/Controls/OAuthLoginForm.cs index 9d0916762..0469a8870 100644 --- a/src/Greenshot.Base/Controls/OAuthLoginForm.cs +++ b/src/Greenshot.Base/Controls/OAuthLoginForm.cs @@ -112,10 +112,8 @@ namespace Greenshot.Base.Controls } } - private void AddressTextBox_KeyPress(object sender, KeyPressEventArgs e) - { + private void AddressTextBox_KeyPress(object sender, KeyPressEventArgs e) => //Cancel the key press so the user can't enter a new url e.Handled = true; - } } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/QualityDialog.cs b/src/Greenshot.Base/Controls/QualityDialog.cs index 2212ab35b..45a6c3eff 100644 --- a/src/Greenshot.Base/Controls/QualityDialog.cs +++ b/src/Greenshot.Base/Controls/QualityDialog.cs @@ -64,9 +64,6 @@ namespace Greenshot.Base.Controls } } - private void TrackBarJpegQualityScroll(object sender, EventArgs e) - { - textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(); - } + private void TrackBarJpegQualityScroll(object sender, EventArgs e) => textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/SaveImageFileDialog.cs b/src/Greenshot.Base/Controls/SaveImageFileDialog.cs index 0f3052bcf..9bf8e1758 100644 --- a/src/Greenshot.Base/Controls/SaveImageFileDialog.cs +++ b/src/Greenshot.Base/Controls/SaveImageFileDialog.cs @@ -51,13 +51,10 @@ namespace Greenshot.Base.Controls protected virtual void Dispose(bool disposing) { - if (disposing) + if (disposing && SaveFileDialog != null) { - if (SaveFileDialog != null) - { - SaveFileDialog.Dispose(); - SaveFileDialog = null; - } + SaveFileDialog.Dispose(); + SaveFileDialog = null; } } @@ -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 /// /// sets InitialDirectory and FileName property of a SaveFileDialog smartly, considering default pattern and last used path /// - private void ApplySuggestedValues() - { + private void ApplySuggestedValues() => // build the full path and set dialog properties FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, _captureDetails); - } private class FilterOption { diff --git a/src/Greenshot.Base/Controls/ThumbnailForm.cs b/src/Greenshot.Base/Controls/ThumbnailForm.cs index a79e5fb8b..b8d88745d 100644 --- a/src/Greenshot.Base/Controls/ThumbnailForm.cs +++ b/src/Greenshot.Base/Controls/ThumbnailForm.cs @@ -50,14 +50,9 @@ namespace Greenshot.Base.Controls FormBorderStyle = FormBorderStyle.None; TopMost = false; Enabled = false; - if (conf.WindowCaptureMode == WindowCaptureMode.Auto || conf.WindowCaptureMode == WindowCaptureMode.Aero) - { - BackColor = Color.FromArgb(255, conf.DWMBackgroundColor.R, conf.DWMBackgroundColor.G, conf.DWMBackgroundColor.B); - } - else - { - BackColor = Color.White; - } + BackColor = conf.WindowCaptureMode == WindowCaptureMode.Auto || conf.WindowCaptureMode == WindowCaptureMode.Aero + ? Color.FromArgb(255, conf.DWMBackgroundColor.R, conf.DWMBackgroundColor.G, conf.DWMBackgroundColor.B) + : Color.White; // cleanup at close FormClosing += delegate { UnregisterThumbnail(); }; @@ -147,14 +142,9 @@ namespace Greenshot.Base.Controls public void AlignToControl(Control alignTo) { var screenBounds = DisplayInfo.ScreenBounds; - if (screenBounds.Contains(alignTo.Left, alignTo.Top - Height)) - { - Location = new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Top - Height); - } - else - { - Location = new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Bottom); - } + Location = screenBounds.Contains(alignTo.Left, alignTo.Top - Height) + ? new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Top - Height) + : new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Bottom); } } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/AbstractDestination.cs b/src/Greenshot.Base/Core/AbstractDestination.cs index 803e6a783..ff416bd13 100644 --- a/src/Greenshot.Base/Core/AbstractDestination.cs +++ b/src/Greenshot.Base/Core/AbstractDestination.cs @@ -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; /// /// 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().ContextMenuStrip.Handle); diff --git a/src/Greenshot.Base/Core/AccessibleHelper.cs b/src/Greenshot.Base/Core/AccessibleHelper.cs index 1b26fffb1..ee45d7269 100644 --- a/src/Greenshot.Base/Core/AccessibleHelper.cs +++ b/src/Greenshot.Base/Core/AccessibleHelper.cs @@ -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) { diff --git a/src/Greenshot.Base/Core/AnimationHelpers.cs b/src/Greenshot.Base/Core/AnimationHelpers.cs index 0fbbe9469..b61f8e30a 100644 --- a/src/Greenshot.Base/Core/AnimationHelpers.cs +++ b/src/Greenshot.Base/Core/AnimationHelpers.cs @@ -110,22 +110,13 @@ namespace Greenshot.Base.Core /// /// Final animation value, this is including the legs /// - 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; /// /// This restarts the current animation and changes the last frame /// /// - public void ChangeDestination(T newDestination) - { - ChangeDestination(newDestination, Frames); - } + public void ChangeDestination(T newDestination) => ChangeDestination(newDestination, Frames); /// /// This restarts the current animation and changes the last frame @@ -146,20 +137,14 @@ namespace Greenshot.Base.Core /// All values will stay the same /// /// - public void QueueDestinationLeg(T queuedDestination) - { - QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode); - } + public void QueueDestinationLeg(T queuedDestination) => QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode); /// /// Queue the destination, it will be used to continue at the last frame /// /// /// - public void QueueDestinationLeg(T queuedDestination, int frames) - { - QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode); - } + public void QueueDestinationLeg(T queuedDestination, int frames) => QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode); /// /// Queue the destination, it will be used to continue at the last frame @@ -167,10 +152,7 @@ namespace Greenshot.Base.Core /// /// /// EasingType - public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType) - { - QueueDestinationLeg(queuedDestination, frames, easingType, EasingMode); - } + public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType) => QueueDestinationLeg(queuedDestination, frames, easingType, EasingMode); /// /// Queue the destination, it will be used to continue at the last frame @@ -204,17 +186,13 @@ namespace Greenshot.Base.Core /// /// Get the easing value, which is from 0-1 and depends on the frame /// - protected double EasingValue + protected double EasingValue => EasingMode switch { - get => - EasingMode switch - { - EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType), - EasingMode.EaseInOut => Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType), - EasingMode.EaseIn => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType), - _ => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType) - }; - } + EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType), + EasingMode.EaseInOut => Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType), + EasingMode.EaseIn => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType), + _ => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType) + }; /// /// Get the current (previous) frame object @@ -252,13 +230,7 @@ namespace Greenshot.Base.Core /// /// Are there more frames to animate? /// - public virtual bool HasNext - { - get - { - return CurrentFrameNr < Frames || _queue.Count > 0; - } - } + public virtual bool HasNext => CurrentFrameNr < Frames || _queue.Count > 0; /// /// 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) { diff --git a/src/Greenshot.Base/Core/Cache.cs b/src/Greenshot.Base/Core/Cache.cs index bf92bb557..8b7e33f5f 100644 --- a/src/Greenshot.Base/Core/Cache.cs +++ b/src/Greenshot.Base/Core/Cache.cs @@ -52,29 +52,20 @@ namespace Greenshot.Base.Core /// Initialize the cache /// /// - public Cache(CacheObjectExpired expiredCallback) : this() - { - _expiredCallback = expiredCallback; - } + public Cache(CacheObjectExpired expiredCallback) : this() => _expiredCallback = expiredCallback; /// /// Initialize the cache with a expire setting /// /// - public Cache(int secondsToExpire) : this() - { - _secondsToExpire = secondsToExpire; - } + public Cache(int secondsToExpire) : this() => _secondsToExpire = secondsToExpire; /// /// Initialize the cache with a expire setting /// /// /// - public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback) - { - _secondsToExpire = secondsToExpire; - } + public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback) => _secondsToExpire = secondsToExpire; /// /// Enumerable for the values in the cache @@ -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 /// /// /// - public void Add(TK key, TV value) - { - Add(key, value, null); - } + public void Add(TK key, TV value) => Add(key, value, null); /// /// Add a value to the cache @@ -156,7 +141,7 @@ namespace Greenshot.Base.Core lock (_lockObject) { var cachedItem = new CachedItem(key, value, secondsToExpire ?? _secondsToExpire); - cachedItem.Expired += delegate (TK cacheKey, TV cacheValue) + cachedItem.Expired += (TK cacheKey, TV cacheValue) => { if (_internalCache.ContainsKey(cacheKey)) { @@ -242,10 +227,7 @@ namespace Greenshot.Base.Core } } - private void timerEvent_Elapsed(object sender, ElapsedEventArgs e) - { - ExpireNow(); - } + private void timerEvent_Elapsed(object sender, ElapsedEventArgs e) => ExpireNow(); public TK Key { get; private set; } public TV Item { get; private set; } diff --git a/src/Greenshot.Base/Core/Capture.cs b/src/Greenshot.Base/Core/Capture.cs index 2a761dd29..c272dbdad 100644 --- a/src/Greenshot.Base/Core/Capture.cs +++ b/src/Greenshot.Base/Core/Capture.cs @@ -97,10 +97,7 @@ namespace Greenshot.Base.Core } } - public void NullImage() - { - _image = null; - } + public void NullImage() => _image = null; private Icon _cursor; @@ -162,10 +159,7 @@ namespace Greenshot.Base.Core /// Note: the supplied bitmap can be disposed immediately or when constructor is called. /// /// Image - public Capture(Image newImage) : this() - { - Image = newImage; - } + public Capture(Image newImage) : this() => Image = newImage; /// /// Destructor @@ -234,10 +228,7 @@ namespace Greenshot.Base.Core /// /// x coordinates to move the mouse /// y coordinates to move the mouse - public void MoveMouseLocation(int x, int y) - { - CursorLocation = CursorLocation.Offset(x, y); - } + public void MoveMouseLocation(int x, int y) => CursorLocation = CursorLocation.Offset(x, y); // TODO: Enable when the elements are usable again. ///// diff --git a/src/Greenshot.Base/Core/CaptureDetails.cs b/src/Greenshot.Base/Core/CaptureDetails.cs index 048fcf32c..b5c456e2b 100644 --- a/src/Greenshot.Base/Core/CaptureDetails.cs +++ b/src/Greenshot.Base/Core/CaptureDetails.cs @@ -23,6 +23,7 @@ using System; using System.Collections.Generic; using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces.Ocr; +using System.Linq; namespace Greenshot.Base.Core { @@ -54,10 +55,7 @@ namespace Greenshot.Base.Core public Dictionary MetaData { get; } = new Dictionary(); /// - public void AddMetaData(string key, string value) - { - MetaData[key] = value; - } + public void AddMetaData(string key, string value) => MetaData[key] = value; /// public CaptureMode CaptureMode { get; set; } @@ -66,10 +64,7 @@ namespace Greenshot.Base.Core public List CaptureDestinations { get; set; } = new List(); /// - public void ClearDestinations() - { - CaptureDestinations.Clear(); - } + public void ClearDestinations() => CaptureDestinations.Clear(); /// public void RemoveDestination(IDestination destination) @@ -92,20 +87,16 @@ namespace Greenshot.Base.Core /// public bool HasDestination(string designation) { - foreach (IDestination destination in CaptureDestinations) + foreach (var _ in from IDestination destination in CaptureDestinations + where designation.Equals(destination.Designation) + select new { }) { - if (designation.Equals(destination.Designation)) - { - return true; - } + return true; } return false; } - public CaptureDetails() - { - DateTime = DateTime.Now; - } + public CaptureDetails() => DateTime = DateTime.Now; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/ClipboardHelper.cs b/src/Greenshot.Base/Core/ClipboardHelper.cs index 770e293f6..de2b8293e 100644 --- a/src/Greenshot.Base/Core/ClipboardHelper.cs +++ b/src/Greenshot.Base/Core/ClipboardHelper.cs @@ -187,14 +187,9 @@ EndSelection:<<<<<<<4 { string messageText; string clipboardOwner = GetClipboardOwner(); - if (clipboardOwner != null) - { - messageText = Language.GetFormattedString("clipboard_inuse", clipboardOwner); - } - else - { - messageText = Language.GetString("clipboard_error"); - } + messageText = clipboardOwner != null + ? Language.GetFormattedString("clipboard_inuse", clipboardOwner) + : Language.GetString("clipboard_error"); Log.Error(messageText, clipboardSetException); } @@ -221,14 +216,9 @@ EndSelection:<<<<<<<4 { string messageText; string clipboardOwner = GetClipboardOwner(); - if (clipboardOwner != null) - { - messageText = Language.GetFormattedString("clipboard_inuse", clipboardOwner); - } - else - { - messageText = Language.GetString("clipboard_error"); - } + messageText = clipboardOwner != null + ? Language.GetFormattedString("clipboard_inuse", clipboardOwner) + : Language.GetString("clipboard_error"); Log.Error(messageText, ee); } @@ -254,12 +244,9 @@ EndSelection:<<<<<<<4 /// public static bool ContainsText(IDataObject dataObject) { - if (dataObject != null) + if (dataObject != null && (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText))) { - if (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText)) - { - return true; - } + return true; } return false; @@ -487,10 +474,7 @@ EndSelection:<<<<<<<4 /// /// /// true if there is a valid stream - private static bool IsValidStream(MemoryStream memoryStream) - { - return memoryStream?.Length > 0; - } + private static bool IsValidStream(MemoryStream memoryStream) => memoryStream?.Length > 0; /// /// Wrapper for Clipboard.GetImage, Created for Bug #3432313 @@ -885,10 +869,7 @@ EndSelection:<<<<<<<4 /// Get Text from the DataObject /// /// string if there is text on the clipboard - 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; /// /// Set text to the clipboard @@ -1177,23 +1158,17 @@ EndSelection:<<<<<<<4 /// IDataObject /// string with format /// true if one the format is found - public static bool ContainsFormat(IDataObject dataObject, string format) - { - return ContainsFormat(dataObject, new[] + public static bool ContainsFormat(IDataObject dataObject, string format) => ContainsFormat(dataObject, new[] { format }); - } /// /// Check if there is currently something on the clipboard which has one of the supplied formats /// /// string[] with formats /// true if one of the formats was found - public static bool ContainsFormat(string[] formats) - { - return ContainsFormat(GetDataObject(), formats); - } + public static bool ContainsFormat(string[] formats) => ContainsFormat(GetDataObject(), formats); /// /// Check if there is currently something on the clipboard which has one of the supplied formats @@ -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 /// IDataObject /// Type to get /// object from IDataObject - 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; /// /// Get ImageFilenames from the IDataObject diff --git a/src/Greenshot.Base/Core/CoreConfiguration.cs b/src/Greenshot.Base/Core/CoreConfiguration.cs index 7a1c7ef06..f38834ddf 100644 --- a/src/Greenshot.Base/Core/CoreConfiguration.cs +++ b/src/Greenshot.Base/Core/CoreConfiguration.cs @@ -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 /// /// /// - 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++) diff --git a/src/Greenshot.Base/Core/CredentialsHelper.cs b/src/Greenshot.Base/Core/CredentialsHelper.cs index a08e61d42..5ec1e6ec0 100644 --- a/src/Greenshot.Base/Core/CredentialsHelper.cs +++ b/src/Greenshot.Base/Core/CredentialsHelper.cs @@ -275,10 +275,7 @@ namespace Greenshot.Base.Core /// Shows the credentials dialog with the specified name. /// The name for the credentials. /// Returns a DialogResult indicating the user action. - public DialogResult Show(string name) - { - return Show(null, name, Password, SaveChecked); - } + public DialogResult Show(string name) => Show(null, name, Password, SaveChecked); /// Shows the credentials dialog with the specified owner, name, password and save checkbox status. /// The System.Windows.Forms.IWin32Window the dialog will display in front of. diff --git a/src/Greenshot.Base/Core/DestinationHelper.cs b/src/Greenshot.Base/Core/DestinationHelper.cs index d80bb694d..7f2fa803e 100644 --- a/src/Greenshot.Base/Core/DestinationHelper.cs +++ b/src/Greenshot.Base/Core/DestinationHelper.cs @@ -37,12 +37,8 @@ namespace Greenshot.Base.Core /// Method to get all the destinations from the plugins /// /// List of IDestination - public static IEnumerable GetAllDestinations() - { - return SimpleServiceProvider.Current.GetAllInstances() - .Where(destination => destination.IsActive) - .Where(destination => CoreConfig.ExcludeDestinations?.Contains(destination.Designation) != true).OrderBy(p => p.Priority).ThenBy(p => p.Description); - } + public static IEnumerable GetAllDestinations() => SimpleServiceProvider.Current.GetAllInstances() + .Where(destination => destination.IsActive && CoreConfig.ExcludeDestinations?.Contains(destination.Designation) != true).OrderBy(p => p.Priority).ThenBy(p => p.Description); /// /// Get a destination by a designation @@ -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 /// WellKnownDestinations /// ISurface /// ICaptureDetails - public static ExportInformation ExportCapture(bool manuallyInitiated, WellKnownDestinations designation, ISurface surface, ICaptureDetails captureDetails) - { - return ExportCapture(manuallyInitiated, designation.ToString(), surface, captureDetails); - } + public static ExportInformation ExportCapture(bool manuallyInitiated, WellKnownDestinations designation, ISurface surface, ICaptureDetails captureDetails) => ExportCapture(manuallyInitiated, designation.ToString(), surface, captureDetails); /// /// A simple helper method which will call ExportCapture for the destination with the specified designation diff --git a/src/Greenshot.Base/Core/DisplayKeyAttribute.cs b/src/Greenshot.Base/Core/DisplayKeyAttribute.cs index 9d80fa533..5b887a573 100644 --- a/src/Greenshot.Base/Core/DisplayKeyAttribute.cs +++ b/src/Greenshot.Base/Core/DisplayKeyAttribute.cs @@ -28,10 +28,7 @@ namespace Greenshot.Base.Core { public string Value { get; } - public DisplayKeyAttribute(string v) - { - Value = v; - } + public DisplayKeyAttribute(string v) => Value = v; public DisplayKeyAttribute() { diff --git a/src/Greenshot.Base/Core/EffectConverter.cs b/src/Greenshot.Base/Core/EffectConverter.cs index 6f333a683..de3124356 100644 --- a/src/Greenshot.Base/Core/EffectConverter.cs +++ b/src/Greenshot.Base/Core/EffectConverter.cs @@ -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]); - } } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/EnvironmentInfo.cs b/src/Greenshot.Base/Core/EnvironmentInfo.cs index c99f05e77..a2e2fc76c 100644 --- a/src/Greenshot.Base/Core/EnvironmentInfo.cs +++ b/src/Greenshot.Base/Core/EnvironmentInfo.cs @@ -54,11 +54,9 @@ namespace Greenshot.Base.Core } } - public static bool IsNet45OrNewer() - { + public static bool IsNet45OrNewer() => // Class "ReflectionContext" exists from .NET 4.5 onwards. - return Type.GetType("System.Reflection.ReflectionContext", false) != null; - } + Type.GetType("System.Reflection.ReflectionContext", false) != null; public static string GetGreenshotVersion(bool shortVersion = false) { @@ -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: diff --git a/src/Greenshot.Base/Core/EventDelay.cs b/src/Greenshot.Base/Core/EventDelay.cs index 0e0075e22..27cf9ecd8 100644 --- a/src/Greenshot.Base/Core/EventDelay.cs +++ b/src/Greenshot.Base/Core/EventDelay.cs @@ -28,14 +28,12 @@ namespace Greenshot.Base.Core private long lastCheck; private readonly long waitTime; - public EventDelay(long ticks) - { - waitTime = ticks; - } + public EventDelay(long ticks) => waitTime = ticks; + private readonly object _lockObject = new(); // Prevent RCS1059 public bool Check() { - lock (this) + lock (_lockObject) { long now = DateTime.Now.Ticks; bool isPassed = now - lastCheck > waitTime; diff --git a/src/Greenshot.Base/Core/FastBitmap.cs b/src/Greenshot.Base/Core/FastBitmap.cs index b5e0c058e..7a184082b 100644 --- a/src/Greenshot.Base/Core/FastBitmap.cs +++ b/src/Greenshot.Base/Core/FastBitmap.cs @@ -290,15 +290,9 @@ namespace Greenshot.Base.Core protected bool BitsLocked; protected byte* Pointer; - public static IFastBitmap Create(Bitmap source) - { - return Create(source, NativeRect.Empty); - } + public static IFastBitmap Create(Bitmap source) => Create(source, NativeRect.Empty); - public void SetResolution(float horizontal, float vertical) - { - Bitmap.SetResolution(horizontal, vertical); - } + public void SetResolution(float horizontal, float vertical) => Bitmap.SetResolution(horizontal, vertical); /// /// Factory for creating a FastBitmap depending on the pixelformat of the source @@ -324,10 +318,7 @@ namespace Greenshot.Base.Core /// Bitmap to clone /// new PixelFormat /// IFastBitmap - public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat) - { - return CreateCloneOf(source, pixelFormat, NativeRect.Empty); - } + public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat) => CreateCloneOf(source, pixelFormat, NativeRect.Empty); /// /// Factory for creating a FastBitmap as a destination for the source @@ -335,10 +326,7 @@ namespace Greenshot.Base.Core /// Bitmap to clone /// Area of the bitmap to access, can be NativeRect.Empty for the whole /// IFastBitmap - public static IFastBitmap CreateCloneOf(Image source, NativeRect area) - { - return CreateCloneOf(source, PixelFormat.DontCare, area); - } + public static IFastBitmap CreateCloneOf(Image source, NativeRect area) => CreateCloneOf(source, PixelFormat.DontCare, area); /// /// Factory for creating a FastBitmap as a destination for the source @@ -408,35 +396,17 @@ namespace Greenshot.Base.Core /// /// Return the size of the image /// - public NativeSize Size - { - get - { - return Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : Area.Size; - } - } + public NativeSize Size => Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : Area.Size; /// /// Return the width of the image /// - public int Width - { - get - { - return Area == NativeRect.Empty ? Bitmap.Width : Area.Width; - } - } + public int Width => Area == NativeRect.Empty ? Bitmap.Width : Area.Width; /// /// Return the height of the image /// - 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 /// /// /// - public void DrawTo(Graphics graphics, NativePoint destination) - { - DrawTo(graphics, new NativeRect(destination, Area.Size)); - } + public void DrawTo(Graphics graphics, NativePoint destination) => DrawTo(graphics, new NativeRect(destination, Area.Size)); /// /// Draw the stored Bitmap on the Destination bitmap with the specified rectangle @@ -609,10 +573,7 @@ namespace Greenshot.Base.Core /// /// /// true if x & y are inside the FastBitmap - public bool Contains(int x, int y) - { - return Area.Contains(x - Left, y - Top); - } + public bool Contains(int x, int y) => Area.Contains(x - Left, y - Top); public abstract Color GetColorAt(int x, int y); public abstract void SetColorAt(int x, int y, Color color); @@ -653,10 +614,7 @@ namespace Greenshot.Base.Core /// /// /// true if x & y are inside the FastBitmap - bool IFastBitmapWithOffset.Contains(int x, int y) - { - return Area.Contains(x - Left, y - Top); - } + bool IFastBitmapWithOffset.Contains(int x, int y) => Area.Contains(x - Left, y - Top); Color IFastBitmapWithOffset.GetColorAt(int x, int y) { @@ -696,10 +654,7 @@ namespace Greenshot.Base.Core private readonly Color[] _colorEntries; private readonly Dictionary _colorCache = new(); - public FastChunkyBitmap(Bitmap source, NativeRect area) : base(source, area) - { - _colorEntries = Bitmap.Palette.Entries; - } + public FastChunkyBitmap(Bitmap source, NativeRect area) : base(source, area) => _colorEntries = Bitmap.Palette.Entries; /// /// Get the color from the specified location @@ -720,10 +675,7 @@ namespace Greenshot.Base.Core /// /// /// byte[4] as reference - public override void GetColorAt(int x, int y, byte[] color) - { - throw new NotImplementedException("No performance gain!"); - } + public override void GetColorAt(int x, int y, byte[] color) => throw new NotImplementedException("No performance gain!"); /// /// Set the color at the specified location from the specified array @@ -731,10 +683,7 @@ namespace Greenshot.Base.Core /// /// /// byte[4] as reference - public override void SetColorAt(int x, int y, byte[] color) - { - throw new NotImplementedException("No performance gain!"); - } + public override void SetColorAt(int x, int y, byte[] color) => throw new NotImplementedException("No performance gain!"); /// /// Get the color-index from the specified location @@ -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; /// /// Retrieve the color at location x,y diff --git a/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs b/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs index 918bf1a64..618e20c17 100644 --- a/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs +++ b/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs @@ -56,10 +56,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers /// IEnumerable{IFileFormatHandler} /// /// - public static IEnumerable ExtensionsFor(this IEnumerable fileFormatHandlers, FileFormatHandlerActions fileFormatHandlerAction) - { - return fileFormatHandlers.Where(ffh => ffh.SupportedExtensions.ContainsKey(fileFormatHandlerAction)).SelectMany(ffh => ffh.SupportedExtensions[fileFormatHandlerAction]).Distinct().OrderBy(e => e); - } + public static IEnumerable ExtensionsFor(this IEnumerable fileFormatHandlers, FileFormatHandlerActions fileFormatHandlerAction) => fileFormatHandlers.Where(ffh => ffh.SupportedExtensions.ContainsKey(fileFormatHandlerAction)).SelectMany(ffh => ffh.SupportedExtensions[fileFormatHandlerAction]).Distinct().OrderBy(e => e); /// /// Extension method to check if a certain IFileFormatHandler supports a certain action with a specific extension @@ -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; diff --git a/src/Greenshot.Base/Core/FilenameHelper.cs b/src/Greenshot.Base/Core/FilenameHelper.cs index 83cb0d4ec..09ad85fc0 100644 --- a/src/Greenshot.Base/Core/FilenameHelper.cs +++ b/src/Greenshot.Base/Core/FilenameHelper.cs @@ -103,25 +103,13 @@ namespace Greenshot.Base.Core return path; } - public static string GetFilenameWithoutExtensionFromPattern(string pattern) - { - return GetFilenameWithoutExtensionFromPattern(pattern, null); - } + public static string GetFilenameWithoutExtensionFromPattern(string pattern) => GetFilenameWithoutExtensionFromPattern(pattern, null); - public static string GetFilenameWithoutExtensionFromPattern(string pattern, ICaptureDetails captureDetails) - { - return FillPattern(pattern, captureDetails, true); - } + public static string GetFilenameWithoutExtensionFromPattern(string pattern, ICaptureDetails captureDetails) => FillPattern(pattern, captureDetails, true); - public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat) - { - return GetFilenameFromPattern(pattern, imageFormat, null); - } + public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat) => GetFilenameFromPattern(pattern, imageFormat, null); - public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat, ICaptureDetails captureDetails) - { - return FillPattern(pattern, captureDetails, true) + "." + imageFormat.ToString().ToLower(); - } + public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat, ICaptureDetails captureDetails) => FillPattern(pattern, captureDetails, true) + "." + imageFormat.ToString().ToLower(); /// /// Return a filename for the current image format (png,jpg etc) with the default file pattern diff --git a/src/Greenshot.Base/Core/GreenshotResources.cs b/src/Greenshot.Base/Core/GreenshotResources.cs index 36f102f26..17dbcd23f 100644 --- a/src/Greenshot.Base/Core/GreenshotResources.cs +++ b/src/Greenshot.Base/Core/GreenshotResources.cs @@ -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"); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/IEHelper.cs b/src/Greenshot.Base/Core/IEHelper.cs index a03d09902..8de4f07a4 100644 --- a/src/Greenshot.Base/Core/IEHelper.cs +++ b/src/Greenshot.Base/Core/IEHelper.cs @@ -106,10 +106,7 @@ namespace Greenshot.Base.Core /// /// Name of the process /// true to ignore the doctype when loading a page - public static void FixBrowserVersion(string applicationName, bool ignoreDoctype = true) - { - FixBrowserVersion(applicationName, GetEmbVersion(ignoreDoctype)); - } + public static void FixBrowserVersion(string applicationName, bool ignoreDoctype = true) => FixBrowserVersion(applicationName, GetEmbVersion(ignoreDoctype)); /// /// Fix the browser version for the specified application diff --git a/src/Greenshot.Base/Core/ImageHelper.cs b/src/Greenshot.Base/Core/ImageHelper.cs index 458d5a4b4..6c49c119b 100644 --- a/src/Greenshot.Base/Core/ImageHelper.cs +++ b/src/Greenshot.Base/Core/ImageHelper.cs @@ -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 /// /// Image to apply matrix to /// ColorMatrix to apply - public static void ApplyColorMatrix(Bitmap source, ColorMatrix colorMatrix) - { - ApplyColorMatrix(source, NativeRect.Empty, source, NativeRect.Empty, colorMatrix); - } + public static void ApplyColorMatrix(Bitmap source, ColorMatrix colorMatrix) => ApplyColorMatrix(source, NativeRect.Empty, source, NativeRect.Empty, colorMatrix); /// /// Apply a color matrix by copying from the source to the destination @@ -1130,23 +1117,17 @@ namespace Greenshot.Base.Core /// /// PixelFormat to check /// bool if we support it - public static bool SupportsPixelFormat(PixelFormat pixelformat) - { - return pixelformat.Equals(PixelFormat.Format32bppArgb) || + public static bool SupportsPixelFormat(PixelFormat pixelformat) => pixelformat.Equals(PixelFormat.Format32bppArgb) || pixelformat.Equals(PixelFormat.Format32bppPArgb) || pixelformat.Equals(PixelFormat.Format32bppRgb) || pixelformat.Equals(PixelFormat.Format24bppRgb); - } /// /// Wrapper for just cloning which calls the CloneArea /// /// Image to clone /// Bitmap with clone image data - public static Image Clone(Image sourceImage) - { - 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); /// /// Wrapper for just cloning & TargetFormat which calls the CloneArea @@ -1154,10 +1135,7 @@ namespace Greenshot.Base.Core /// Image to clone /// Target Format, use PixelFormat.DontCare if you want the original (or a default if the source PixelFormat is not supported) /// Bitmap with clone image data - public static Bitmap Clone(Image sourceBitmap, PixelFormat targetFormat) - { - return CloneArea(sourceBitmap, NativeRect.Empty, targetFormat); - } + public static Bitmap Clone(Image sourceBitmap, PixelFormat targetFormat) => CloneArea(sourceBitmap, NativeRect.Empty, targetFormat); /// /// Clone an image, taking some rules into account: @@ -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 /// /// /// - public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, int newWidth, int newHeight, Matrix matrix) - { - return ResizeImage(sourceImage, maintainAspectRatio, false, Color.Empty, newWidth, newHeight, matrix); - } + public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, int newWidth, int newHeight, Matrix matrix) => ResizeImage(sourceImage, maintainAspectRatio, false, Color.Empty, newWidth, newHeight, matrix); /// /// Count how many times the supplied color exists diff --git a/src/Greenshot.Base/Core/JSONHelper.cs b/src/Greenshot.Base/Core/JSONHelper.cs index df08540c0..22d018305 100644 --- a/src/Greenshot.Base/Core/JSONHelper.cs +++ b/src/Greenshot.Base/Core/JSONHelper.cs @@ -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 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; diff --git a/src/Greenshot.Base/Core/Language.cs b/src/Greenshot.Base/Core/Language.cs index 5a413eb24..bd9fc3f62 100644 --- a/src/Greenshot.Base/Core/Language.cs +++ b/src/Greenshot.Base/Core/Language.cs @@ -328,13 +328,7 @@ namespace Greenshot.Base.Core /// /// Return the path to the help-file /// - public static string HelpFilePath - { - get - { - return HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage]; - } - } + public static string HelpFilePath => HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage]; /// /// Load the resources from the language file @@ -573,20 +567,14 @@ namespace Greenshot.Base.Core /// /// /// true if available - public static bool HasKey(string prefix, string key) - { - return HasKey(prefix + "." + key); - } + public static bool HasKey(string prefix, string key) => HasKey(prefix + "." + key); /// /// Check if a resource with key exists /// /// /// true if available - public static bool HasKey(string key) - { - return key != null && Resources.ContainsKey(key); - } + public static bool HasKey(string key) => key != null && Resources.ContainsKey(key); /// /// TryGet method which combines HasKey & GetString @@ -594,10 +582,7 @@ namespace Greenshot.Base.Core /// /// out string /// - public static bool TryGetString(string key, out string languageString) - { - return Resources.TryGetValue(key, out languageString); - } + public static bool TryGetString(string key, out string languageString) => Resources.TryGetValue(key, out languageString); /// /// TryGet method which combines HasKey & GetString @@ -606,10 +591,7 @@ namespace Greenshot.Base.Core /// string with key /// out string /// - public static bool TryGetString(string prefix, string key, out string languageString) - { - return Resources.TryGetValue(prefix + "." + key, out languageString); - } + public static bool TryGetString(string prefix, string key, out string languageString) => Resources.TryGetValue(prefix + "." + key, out languageString); /// /// TryGet method which combines HasKey & GetString @@ -618,10 +600,7 @@ namespace Greenshot.Base.Core /// Enum with key /// out string /// - public static bool TryGetString(string prefix, Enum key, out string languageString) - { - return Resources.TryGetValue(prefix + "." + key, out languageString); - } + public static bool TryGetString(string prefix, Enum key, out string languageString) => Resources.TryGetValue(prefix + "." + key, out languageString); /// /// Translate @@ -640,10 +619,7 @@ namespace Greenshot.Base.Core /// /// Enum /// resource or a "string ###key### not found" - 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()); /// /// Get the resource for prefix.key @@ -651,10 +627,7 @@ namespace Greenshot.Base.Core /// string /// Enum /// resource or a "string ###prefix.key### not found" - 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); /// /// Get the resource for prefix.key @@ -662,10 +635,7 @@ namespace Greenshot.Base.Core /// string /// string /// resource or a "string ###prefix.key### not found" - public static string GetString(string prefix, string key) - { - return GetString(prefix + "." + key); - } + public static string GetString(string prefix, string key) => GetString(prefix + "." + key); /// /// Get the resource for key @@ -688,10 +658,7 @@ namespace Greenshot.Base.Core /// Enum /// object /// formatted resource or a "string ###key### not found" - public static string GetFormattedString(Enum key, object param) - { - return GetFormattedString(key.ToString(), param); - } + public static string GetFormattedString(Enum key, object param) => GetFormattedString(key.ToString(), param); /// /// Get the resource for prefix.key, format with with string.format an supply the parameters @@ -700,10 +667,7 @@ namespace Greenshot.Base.Core /// Enum /// object /// formatted resource or a "string ###prefix.key### not found" - public static string GetFormattedString(string prefix, Enum key, object param) - { - return GetFormattedString(prefix, key.ToString(), param); - } + public static string GetFormattedString(string prefix, Enum key, object param) => GetFormattedString(prefix, key.ToString(), param); /// /// Get the resource for prefix.key, format with with string.format an supply the parameters @@ -712,10 +676,7 @@ namespace Greenshot.Base.Core /// string /// object /// formatted resource or a "string ###prefix.key### not found" - public static string GetFormattedString(string prefix, string key, object param) - { - return GetFormattedString(prefix + "." + key, param); - } + public static string GetFormattedString(string prefix, string key, object param) => GetFormattedString(prefix + "." + key, param); /// /// Get the resource for key, format with with string.format an supply the parameters @@ -723,9 +684,6 @@ namespace Greenshot.Base.Core /// string /// object /// formatted resource or a "string ###key### not found" - 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); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/NetworkHelper.cs b/src/Greenshot.Base/Core/NetworkHelper.cs index 01390f094..fbdb82de1 100644 --- a/src/Greenshot.Base/Core/NetworkHelper.cs +++ b/src/Greenshot.Base/Core/NetworkHelper.cs @@ -214,10 +214,7 @@ namespace Greenshot.Base.Core /// /// string with uri to connect to /// WebRequest - public static HttpWebRequest CreateWebRequest(string uri) - { - return CreateWebRequest(new Uri(uri)); - } + public static HttpWebRequest CreateWebRequest(string uri) => CreateWebRequest(new Uri(uri)); /// /// Helper method to create a web request with a lot of default settings @@ -225,10 +222,7 @@ namespace Greenshot.Base.Core /// string with uri to connect to /// /// Method to use /// WebRequest - public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method) - { - return CreateWebRequest(new Uri(uri), method); - } + public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method) => CreateWebRequest(new Uri(uri), method); /// /// Helper method to create a web request with a lot of default settings @@ -593,10 +587,7 @@ namespace Greenshot.Base.Core /// The request object. /// The response data. /// TODO: This method should handle the StatusCode better! - public static string GetResponseAsString(HttpWebRequest webRequest) - { - return GetResponseAsString(webRequest, false); - } + public static string GetResponseAsString(HttpWebRequest webRequest) => GetResponseAsString(webRequest, false); /// /// Read the response as string @@ -766,11 +757,9 @@ namespace Greenshot.Base.Core /// A plain "write data to stream" /// /// - public void WriteToStream(Stream dataStream) - { + public void WriteToStream(Stream dataStream) => // Write the file data directly to the Stream, rather than serializing it to a string. ImageIO.SaveToStream(_surface, dataStream, _outputSettings); - } /// /// Upload the Surface as image to the webrequest diff --git a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs index fe9ff0498..cfd240a98 100644 --- a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs +++ b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs @@ -71,13 +71,7 @@ Greenshot received information from CloudServiceName. You can close this browser /// /// The URL to redirect to /// - 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; diff --git a/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs b/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs index d18c2dcf6..137009a89 100644 --- a/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs +++ b/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs @@ -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) diff --git a/src/Greenshot.Base/Core/OAuth/OAuthSession.cs b/src/Greenshot.Base/Core/OAuth/OAuthSession.cs index 340c46297..c98d59527 100644 --- a/src/Greenshot.Base/Core/OAuth/OAuthSession.cs +++ b/src/Greenshot.Base/Core/OAuth/OAuthSession.cs @@ -29,6 +29,7 @@ using System.Text; using System.Threading; using Greenshot.Base.Controls; using log4net; +using System.Linq; namespace Greenshot.Base.Core.OAuth { @@ -219,11 +220,9 @@ namespace Greenshot.Base.Core.OAuth /// Generate a nonce /// /// - public static string GenerateNonce() - { + public static string GenerateNonce() => // Just a simple implementation of a random number between 123400 and 9999999 - return random.Next(123400, 9999999).ToString(); - } + random.Next(123400, 9999999).ToString(); /// /// Get the request token using the consumer key and secret. Also initializes tokensecret @@ -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 /// Data to post (MemoryStream) /// The web server response. public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary parametersToSign, IDictionary additionalParameters, - IBinaryContainer postData) - { - return MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData); - } + IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData); /// /// Submit a web request using oAuth. @@ -399,10 +392,7 @@ namespace Greenshot.Base.Core.OAuth /// Data to post (MemoryStream) /// The web server response. public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary headers, IDictionary parametersToSign, - IDictionary additionalParameters, IBinaryContainer postData) - { - return MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData); - } + IDictionary additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData); /// /// Submit a web request using oAuth. @@ -415,10 +405,7 @@ namespace Greenshot.Base.Core.OAuth /// Data to post (MemoryStream) /// The web server response. public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestUrl, IDictionary parametersToSign, - IDictionary additionalParameters, IBinaryContainer postData) - { - return MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData); - } + IDictionary additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData); /// /// Submit a web request using oAuth. @@ -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 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 diff --git a/src/Greenshot.Base/Core/PluginUtils.cs b/src/Greenshot.Base/Core/PluginUtils.cs index 9e51c122c..8aad3acb4 100644 --- a/src/Greenshot.Base/Core/PluginUtils.cs +++ b/src/Greenshot.Base/Core/PluginUtils.cs @@ -42,10 +42,7 @@ namespace Greenshot.Base.Core private const string PathKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"; private static readonly IDictionary ExeIconCache = new Dictionary(); - static PluginUtils() - { - CoreConfig.PropertyChanged += OnIconSizeChanged; - } + static PluginUtils() => CoreConfig.PropertyChanged += OnIconSizeChanged; /// /// Clear icon cache diff --git a/src/Greenshot.Base/Core/QuantizerHelper.cs b/src/Greenshot.Base/Core/QuantizerHelper.cs index efdb78d82..8577f7425 100644 --- a/src/Greenshot.Base/Core/QuantizerHelper.cs +++ b/src/Greenshot.Base/Core/QuantizerHelper.cs @@ -113,13 +113,10 @@ namespace Greenshot.Base.Core protected virtual void Dispose(bool disposing) { - if (disposing) + if (disposing && resultBitmap != null) { - if (resultBitmap != null) - { - resultBitmap.Dispose(); - resultBitmap = null; - } + resultBitmap.Dispose(); + resultBitmap = null; } } @@ -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 /// /// See for more details. /// - public int GetColorCount() - { - return colorCount; - } + public int GetColorCount() => colorCount; /// /// 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 /// /// Computes the volume of the cube in a specific moment. /// - private static long Volume(WuColorCube cube, long[,,] moment) - { - return moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - + private static long Volume(WuColorCube cube, long[,,] moment) => moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] - moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] - @@ -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]; - } /// /// Computes the volume of the cube in a specific moment. For the floating-point values. /// - private static float VolumeFloat(WuColorCube cube, float[,,] moment) - { - return moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - + private static float VolumeFloat(WuColorCube cube, float[,,] moment) => moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] - moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] - @@ -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]; - } /// /// Splits the cube in given position, and color direction. /// - private static long Top(WuColorCube cube, int direction, int position, long[,,] moment) + private static long Top(WuColorCube cube, int direction, int position, long[,,] moment) => direction switch { - return direction switch - { - RED => moment[position, cube.GreenMaximum, cube.BlueMaximum] - - moment[position, cube.GreenMaximum, cube.BlueMinimum] - - moment[position, cube.GreenMinimum, cube.BlueMaximum] + - moment[position, cube.GreenMinimum, cube.BlueMinimum], - GREEN => moment[cube.RedMaximum, position, cube.BlueMaximum] - - moment[cube.RedMaximum, position, cube.BlueMinimum] - - moment[cube.RedMinimum, position, cube.BlueMaximum] + - moment[cube.RedMinimum, position, cube.BlueMinimum], - BLUE => moment[cube.RedMaximum, cube.GreenMaximum, position] - - moment[cube.RedMaximum, cube.GreenMinimum, position] - - moment[cube.RedMinimum, cube.GreenMaximum, position] + - moment[cube.RedMinimum, cube.GreenMinimum, position], - _ => 0, - }; - } + RED => moment[position, cube.GreenMaximum, cube.BlueMaximum] - + moment[position, cube.GreenMaximum, cube.BlueMinimum] - + moment[position, cube.GreenMinimum, cube.BlueMaximum] + + moment[position, cube.GreenMinimum, cube.BlueMinimum], + GREEN => moment[cube.RedMaximum, position, cube.BlueMaximum] - + moment[cube.RedMaximum, position, cube.BlueMinimum] - + moment[cube.RedMinimum, position, cube.BlueMaximum] + + moment[cube.RedMinimum, position, cube.BlueMinimum], + BLUE => moment[cube.RedMaximum, cube.GreenMaximum, position] - + moment[cube.RedMaximum, cube.GreenMinimum, position] - + moment[cube.RedMinimum, cube.GreenMaximum, position] + + moment[cube.RedMinimum, cube.GreenMinimum, position], + _ => 0, + }; /// /// Splits the cube in a given color direction at its minimum. /// - private static long Bottom(WuColorCube cube, int direction, long[,,] moment) + private static long Bottom(WuColorCube cube, int direction, long[,,] moment) => direction switch { - return direction switch - { - RED => -moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] + - moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], - GREEN => -moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + - moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], - BLUE => -moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + - moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], - _ => 0 - }; - } + RED => -moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] + + moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], + GREEN => -moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], + BLUE => -moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + + moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], + _ => 0 + }; /// /// Calculates statistical variance for a given cube. @@ -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; diff --git a/src/Greenshot.Base/Core/SimpleServiceProvider.cs b/src/Greenshot.Base/Core/SimpleServiceProvider.cs index c72d5b9bd..fe9441e91 100644 --- a/src/Greenshot.Base/Core/SimpleServiceProvider.cs +++ b/src/Greenshot.Base/Core/SimpleServiceProvider.cs @@ -20,10 +20,7 @@ namespace Greenshot.Base.Core return !_services.TryGetValue(typeOfService, out var results) ? Array.Empty() : (IReadOnlyList)results.Cast().ToArray(); } - public TService GetInstance() - { - return GetAllInstances().SingleOrDefault(); - } + public TService GetInstance() => GetAllInstances().SingleOrDefault(); public void AddService(IEnumerable services) { @@ -45,9 +42,6 @@ namespace Greenshot.Base.Core } } - public void AddService(params TService[] services) - { - AddService(services.AsEnumerable()); - } + public void AddService(params TService[] services) => AddService(services.AsEnumerable()); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/StringExtensions.cs b/src/Greenshot.Base/Core/StringExtensions.cs index 4db75b166..2fc9d7903 100644 --- a/src/Greenshot.Base/Core/StringExtensions.cs +++ b/src/Greenshot.Base/Core/StringExtensions.cs @@ -41,10 +41,7 @@ namespace Greenshot.Base.Core /// String with formatting, like {name} /// Object used for the formatting /// Formatted string - public static string FormatWith(this string format, object source) - { - return FormatWith(format, null, source); - } + public static string FormatWith(this string format, object source) => FormatWith(format, null, source); /// /// Format the string "format" with the source @@ -85,7 +82,7 @@ namespace Greenshot.Base.Core RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); List 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"]; diff --git a/src/Greenshot.Base/Core/WindowCapture.cs b/src/Greenshot.Base/Core/WindowCapture.cs index 564ce9a65..1a2f07d5a 100644 --- a/src/Greenshot.Base/Core/WindowCapture.cs +++ b/src/Greenshot.Base/Core/WindowCapture.cs @@ -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 /// /// Point with cursor location, relative to the top left corner of the monitor setup (which itself might actually not be on any screen) /// - public static NativePoint GetCursorLocationRelativeToScreenBounds() - { - return GetLocationRelativeToScreenBounds(User32Api.GetCursorLocation()); - } + public static NativePoint GetCursorLocationRelativeToScreenBounds() => GetLocationRelativeToScreenBounds(User32Api.GetCursorLocation()); /// /// 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 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; diff --git a/src/Greenshot.Base/Core/WindowDetails.cs b/src/Greenshot.Base/Core/WindowDetails.cs index e614841d3..39566c8cc 100644 --- a/src/Greenshot.Base/Core/WindowDetails.cs +++ b/src/Greenshot.Base/Core/WindowDetails.cs @@ -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 _childWindows; private IntPtr _parentHandle = IntPtr.Zero; @@ -106,15 +103,9 @@ namespace Greenshot.Base.Core /// objects for the same Window will be equal. /// /// The Window Handle for this window - 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); /// /// Compare two windows details @@ -144,18 +135,12 @@ namespace Greenshot.Base.Core /// /// Freeze information updates /// - public void FreezeDetails() - { - _frozen = true; - } + public void FreezeDetails() => _frozen = true; /// /// Make the information update again. /// - public void UnfreezeDetails() - { - _frozen = false; - } + public void UnfreezeDetails() => _frozen = false; /// /// 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 /// /// - public static void RegisterIgnoreHandle(IntPtr ignoreHandle) - { - IgnoreHandles.Add(ignoreHandle); - } + public static void RegisterIgnoreHandle(IntPtr ignoreHandle) => IgnoreHandles.Add(ignoreHandle); /// /// Use this to remove the with RegisterIgnoreHandle registered handle /// /// - public static void UnregisterIgnoreHandle(IntPtr ignoreHandle) - { - IgnoreHandles.Remove(ignoreHandle); - } + public static void UnregisterIgnoreHandle(IntPtr ignoreHandle) => IgnoreHandles.Remove(ignoreHandle); public IList Children { @@ -302,12 +281,11 @@ namespace Greenshot.Base.Core /// 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" /// - public IList GetChildren() - { - return _childWindows ?? GetChildren(0); - } + public IList GetChildren() => _childWindows ?? GetChildren(0); /// /// 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 /// /// Returns if this window is cloaked /// - public bool IsCloaked - { - get => DwmApi.IsWindowCloaked(Handle); - } + public bool IsCloaked => DwmApi.IsWindowCloaked(Handle); /// /// Gets whether the window is visible. /// - 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 /// /// Gets the location of the window relative to the screen. /// - public NativePoint Location - { - get => WindowRectangle.Location; - } + public NativePoint Location => WindowRectangle.Location; /// /// Gets the size of the window. /// - public NativeSize Size - { - get => WindowRectangle.Size; - } + public NativeSize Size => WindowRectangle.Size; /// /// Get the client rectangle, this is the part of the window inside the borders (drawable area) @@ -623,10 +578,7 @@ namespace Greenshot.Base.Core /// /// Point with the coordinates to check /// true if the point lies within - public bool Contains(NativePoint p) - { - return WindowRectangle.Contains(p); - } + public bool Contains(NativePoint p) => WindowRectangle.Contains(p); /// /// 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 /// /// Set the window as foreground window /// - public void ToForeground() - { - ToForeground(Handle); - } + public void ToForeground() => ToForeground(Handle); /// /// 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. /// /// The Window Handle - public WindowDetails(IntPtr hWnd) - { - Handle = hWnd; - } + public WindowDetails(IntPtr hWnd) => Handle = hWnd; /// /// Gets an instance of the current active foreground window @@ -1370,28 +1300,19 @@ namespace Greenshot.Base.Core /// Gets the Desktop window /// /// WindowDetails for the desktop window - public static WindowDetails GetDesktopWindow() - { - return new WindowDetails(User32Api.GetDesktopWindow()); - } + public static WindowDetails GetDesktopWindow() => new(User32Api.GetDesktopWindow()); /// /// Get all the top level windows /// /// List of WindowDetails with all the top level windows - public static IList GetAllWindows() - { - return GetAllWindows(null); - } + public static IList GetAllWindows() => GetAllWindows(null); /// /// Get all the top level windows, with matching classname /// /// List WindowDetails with all the top level windows - public static IList GetAllWindows(string classname) - { - return new WindowsEnumerator().GetWindows(IntPtr.Zero, classname).Items; - } + public static IList GetAllWindows(string classname) => new WindowsEnumerator().GetWindows(IntPtr.Zero, classname).Items; /// /// Recursive "find children which" @@ -1618,13 +1539,7 @@ namespace Greenshot.Base.Core /// Return true if the metro-app-launcher is visible /// /// - public static bool IsAppLauncherVisible - { - get - { - return AppVisibility != null && AppVisibility.IsLauncherVisible; - } - } + public static bool IsAppLauncherVisible => AppVisibility?.IsLauncherVisible == true; /// /// Make a string representation of the window details diff --git a/src/Greenshot.Base/Core/WindowsVersion.cs b/src/Greenshot.Base/Core/WindowsVersion.cs index b7e883f72..a8531b564 100644 --- a/src/Greenshot.Base/Core/WindowsVersion.cs +++ b/src/Greenshot.Base/Core/WindowsVersion.cs @@ -62,9 +62,6 @@ namespace Greenshot.Base.Core /// /// int /// bool - public static bool IsWindows10BuildOrLater(int minimalBuildNumber) - { - return IsWindows10 && WinVersion.Build >= minimalBuildNumber; - } + public static bool IsWindows10BuildOrLater(int minimalBuildNumber) => IsWindows10 && WinVersion.Build >= minimalBuildNumber; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs b/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs index 26d36ff14..01a5c770d 100644 --- a/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs +++ b/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs @@ -38,10 +38,7 @@ namespace Greenshot.Base.Core /// /// Message /// true if the message should be filtered - public bool PreFilterMessage(ref Message m) - { - return PreFilterMessageExternal(ref m); - } + public bool PreFilterMessage(ref Message m) => PreFilterMessageExternal(ref m); /// /// Also used in the MainForm WndProc diff --git a/src/Greenshot.Base/Effects/AdjustEffect.cs b/src/Greenshot.Base/Effects/AdjustEffect.cs index d6448eec9..74bced2b7 100644 --- a/src/Greenshot.Base/Effects/AdjustEffect.cs +++ b/src/Greenshot.Base/Effects/AdjustEffect.cs @@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects /// 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); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/BorderEffect.cs b/src/Greenshot.Base/Effects/BorderEffect.cs index 9fd3b33b5..165111c45 100644 --- a/src/Greenshot.Base/Effects/BorderEffect.cs +++ b/src/Greenshot.Base/Effects/BorderEffect.cs @@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects /// 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); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/DropShadowEffect.cs b/src/Greenshot.Base/Effects/DropShadowEffect.cs index b597e4463..af1b4d4e8 100644 --- a/src/Greenshot.Base/Effects/DropShadowEffect.cs +++ b/src/Greenshot.Base/Effects/DropShadowEffect.cs @@ -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); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/GrayscaleEffect.cs b/src/Greenshot.Base/Effects/GrayscaleEffect.cs index 72535a12b..64db54e6b 100644 --- a/src/Greenshot.Base/Effects/GrayscaleEffect.cs +++ b/src/Greenshot.Base/Effects/GrayscaleEffect.cs @@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects /// 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() { diff --git a/src/Greenshot.Base/Effects/InvertEffect.cs b/src/Greenshot.Base/Effects/InvertEffect.cs index 939ad9d49..2372a545d 100644 --- a/src/Greenshot.Base/Effects/InvertEffect.cs +++ b/src/Greenshot.Base/Effects/InvertEffect.cs @@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects /// 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() { diff --git a/src/Greenshot.Base/Effects/MonochromeEffect.cs b/src/Greenshot.Base/Effects/MonochromeEffect.cs index 8928bf09c..78b74c4dc 100644 --- a/src/Greenshot.Base/Effects/MonochromeEffect.cs +++ b/src/Greenshot.Base/Effects/MonochromeEffect.cs @@ -33,19 +33,13 @@ namespace Greenshot.Base.Effects private readonly byte _threshold; /// Threshold for monochrome filter (0 - 255), lower value means less black - 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); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/ReduceColorsEffect.cs b/src/Greenshot.Base/Effects/ReduceColorsEffect.cs index bca3ae680..1d0136836 100644 --- a/src/Greenshot.Base/Effects/ReduceColorsEffect.cs +++ b/src/Greenshot.Base/Effects/ReduceColorsEffect.cs @@ -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) { diff --git a/src/Greenshot.Base/Effects/ResizeCanvasEffect.cs b/src/Greenshot.Base/Effects/ResizeCanvasEffect.cs index 87fca1aef..ce3590324 100644 --- a/src/Greenshot.Base/Effects/ResizeCanvasEffect.cs +++ b/src/Greenshot.Base/Effects/ResizeCanvasEffect.cs @@ -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); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/ResizeEffect.cs b/src/Greenshot.Base/Effects/ResizeEffect.cs index bf6298445..7abb61b6c 100644 --- a/src/Greenshot.Base/Effects/ResizeEffect.cs +++ b/src/Greenshot.Base/Effects/ResizeEffect.cs @@ -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); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/RotateEffect.cs b/src/Greenshot.Base/Effects/RotateEffect.cs index 86db7db21..8daf0a382 100644 --- a/src/Greenshot.Base/Effects/RotateEffect.cs +++ b/src/Greenshot.Base/Effects/RotateEffect.cs @@ -31,10 +31,7 @@ namespace Greenshot.Base.Effects /// public class RotateEffect : IEffect { - public RotateEffect(int angle) - { - Angle = angle; - } + public RotateEffect(int angle) => Angle = angle; public int Angle { get; set; } diff --git a/src/Greenshot.Base/Effects/TornEdgeEffect.cs b/src/Greenshot.Base/Effects/TornEdgeEffect.cs index 43dc75d39..edc9389cb 100644 --- a/src/Greenshot.Base/Effects/TornEdgeEffect.cs +++ b/src/Greenshot.Base/Effects/TornEdgeEffect.cs @@ -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; } diff --git a/src/Greenshot.Base/IniFile/IniAttributes.cs b/src/Greenshot.Base/IniFile/IniAttributes.cs index 72c16126c..4d8e45245 100644 --- a/src/Greenshot.Base/IniFile/IniAttributes.cs +++ b/src/Greenshot.Base/IniFile/IniAttributes.cs @@ -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; } diff --git a/src/Greenshot.Base/IniFile/IniConfig.cs b/src/Greenshot.Base/IniFile/IniConfig.cs index c6e638b3e..604974b7d 100644 --- a/src/Greenshot.Base/IniFile/IniConfig.cs +++ b/src/Greenshot.Base/IniFile/IniConfig.cs @@ -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 /// /// Get the location of the configuration /// - public static string ConfigLocation - { - get - { - return IsInitialized + public static string ConfigLocation => IsInitialized ? CreateIniLocation(_configName + IniExtension, false) : throw new InvalidOperationException("Ini configuration was not initialized!"); - } - } /// /// 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 /// /// IniSection Type to get the configuration for /// Filled instance of IniSection type which was supplied - public static T GetIniSection() where T : IniSection - { - return GetIniSection(true); - } + public static T GetIniSection() where T : IniSection => GetIniSection(true); /// /// diff --git a/src/Greenshot.Base/IniFile/IniSection.cs b/src/Greenshot.Base/IniFile/IniSection.cs index e88fa75a5..695020a04 100644 --- a/src/Greenshot.Base/IniFile/IniSection.cs +++ b/src/Greenshot.Base/IniFile/IniSection.cs @@ -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 values = new Dictionary(); [NonSerialized] private IniSectionAttribute iniSectionAttribute; - public IniSectionAttribute IniSectionAttribute - { - get - { - return iniSectionAttribute ??= GetIniSectionAttribute(GetType()); - } - } + public IniSectionAttribute IniSectionAttribute => iniSectionAttribute ??= GetIniSectionAttribute(GetType()); /// /// Get the dictionary with all the IniValues /// - public IDictionary Values - { - get { return values; } - } + public IDictionary Values => values; /// /// Flag to specify if values have been changed @@ -65,10 +57,7 @@ namespace Greenshot.Base.IniFile /// /// The property to return a default for /// object with the default value for the supplied property - public virtual object GetDefault(string property) - { - return null; - } + public virtual object GetDefault(string property) => null; /// /// 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 /// The name of the property /// The string value of the property /// string with the propertyValue, modified or not... - public virtual string PreCheckValue(string propertyName, string propertyValue) - { - return propertyValue; - } + public virtual string PreCheckValue(string propertyName, string propertyValue) => propertyValue; /// /// 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 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(); } } } diff --git a/src/Greenshot.Base/IniFile/IniValue.cs b/src/Greenshot.Base/IniFile/IniValue.cs index 2299e494a..34d776386 100644 --- a/src/Greenshot.Base/IniFile/IniValue.cs +++ b/src/Greenshot.Base/IniFile/IniValue.cs @@ -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 /// public bool IsVisible => !IsExpert; - public MemberInfo MemberInfo - { - get - { - return _propertyInfo == null ? _fieldInfo : _propertyInfo; - } - } + public MemberInfo MemberInfo => _propertyInfo == null ? _fieldInfo : _propertyInfo; /// /// 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 /// /// string representation of this - public override string ToString() - { - return ConvertValueToString(ValueType, Value, Attributes.Separator); - } + public override string ToString() => ConvertValueToString(ValueType, Value, Attributes.Separator); /// /// Convert the supplied value to a string diff --git a/src/Greenshot.Base/Interfaces/Drawing/IField.cs b/src/Greenshot.Base/Interfaces/Drawing/IField.cs index 8bbaaae66..b3dd16b42 100644 --- a/src/Greenshot.Base/Interfaces/Drawing/IField.cs +++ b/src/Greenshot.Base/Interfaces/Drawing/IField.cs @@ -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; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Interfaces/IDestination.cs b/src/Greenshot.Base/Interfaces/IDestination.cs index bfb520c1e..3e548e28f 100644 --- a/src/Greenshot.Base/Interfaces/IDestination.cs +++ b/src/Greenshot.Base/Interfaces/IDestination.cs @@ -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; } diff --git a/src/Greenshot.Base/Interfaces/Ocr/Line.cs b/src/Greenshot.Base/Interfaces/Ocr/Line.cs index ff5914a4e..43b11e14c 100644 --- a/src/Greenshot.Base/Interfaces/Ocr/Line.cs +++ b/src/Greenshot.Base/Interfaces/Ocr/Line.cs @@ -77,10 +77,7 @@ namespace Greenshot.Base.Interfaces.Ocr /// /// Return the calculated bounds for the whole line /// - public NativeRect CalculatedBounds - { - get { return _calculatedBounds ??= CalculateBounds(); } - } + public NativeRect CalculatedBounds => _calculatedBounds ??= CalculateBounds(); /// /// Offset the words with the specified x and y coordinates diff --git a/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs b/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs index 68be7ebb6..7d867b1d7 100644 --- a/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs +++ b/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs @@ -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; /// /// 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; } } diff --git a/src/Greenshot.Base/Interop/COMWrapper.cs b/src/Greenshot.Base/Interop/COMWrapper.cs index 3f75165a4..0ac8b10c2 100644 --- a/src/Greenshot.Base/Interop/COMWrapper.cs +++ b/src/Greenshot.Base/Interop/COMWrapper.cs @@ -232,10 +232,7 @@ namespace Greenshot.Base.Interop /// /// The full name of the intercepted type. /// - public override string ToString() - { - return _interceptType.FullName; - } + public override string ToString() => _interceptType.FullName; /// /// Returns the hash code of the wrapped object. @@ -243,10 +240,7 @@ namespace Greenshot.Base.Interop /// /// The hash code of the wrapped object. /// - public override int GetHashCode() - { - return _comObject.GetHashCode(); - } + public override int GetHashCode() => _comObject.GetHashCode(); /// /// Compares this object to another. @@ -259,12 +253,9 @@ namespace Greenshot.Base.Interop /// 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; diff --git a/src/Greenshot.Base/Interop/ComProgIdAttribute.cs b/src/Greenshot.Base/Interop/ComProgIdAttribute.cs index f4e6fcebc..5d54efed9 100644 --- a/src/Greenshot.Base/Interop/ComProgIdAttribute.cs +++ b/src/Greenshot.Base/Interop/ComProgIdAttribute.cs @@ -70,10 +70,7 @@ namespace Greenshot.Base.Interop /// Constructor /// The COM ProgID. - public ComProgIdAttribute(string value) - { - Value = value; - } + public ComProgIdAttribute(string value) => Value = value; /// /// Returns the COM ProgID diff --git a/src/Greenshot.Editor/Controls/BindableToolStripButton.cs b/src/Greenshot.Editor/Controls/BindableToolStripButton.cs index a79d6c801..1fb80fbdd 100644 --- a/src/Greenshot.Editor/Controls/BindableToolStripButton.cs +++ b/src/Greenshot.Editor/Controls/BindableToolStripButton.cs @@ -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")); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Controls/BindableToolStripComboBox.cs b/src/Greenshot.Editor/Controls/BindableToolStripComboBox.cs index ac56641f1..c8a0de905 100644 --- a/src/Greenshot.Editor/Controls/BindableToolStripComboBox.cs +++ b/src/Greenshot.Editor/Controls/BindableToolStripComboBox.cs @@ -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")); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Controls/ColorButton.cs b/src/Greenshot.Editor/Controls/ColorButton.cs index 9e968afbc..6a01aeb62 100644 --- a/src/Greenshot.Editor/Controls/ColorButton.cs +++ b/src/Greenshot.Editor/Controls/ColorButton.cs @@ -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); diff --git a/src/Greenshot.Editor/Controls/CustomToolStripProfessionalRenderer.cs b/src/Greenshot.Editor/Controls/CustomToolStripProfessionalRenderer.cs index 578aaf655..213ab8485 100644 --- a/src/Greenshot.Editor/Controls/CustomToolStripProfessionalRenderer.cs +++ b/src/Greenshot.Editor/Controls/CustomToolStripProfessionalRenderer.cs @@ -30,35 +30,17 @@ namespace Greenshot.Editor.Controls /// 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; } /// @@ -67,10 +49,7 @@ namespace Greenshot.Editor.Controls /// public class CustomToolStripProfessionalRenderer : ToolStripProfessionalRenderer { - public CustomToolStripProfessionalRenderer() : base(new CustomProfessionalColorTable()) - { - RoundedEdges = false; - } + public CustomToolStripProfessionalRenderer() : base(new CustomProfessionalColorTable()) => RoundedEdges = false; /// /// By overriding the OnRenderToolStripBorder we can make the ToolStrip without border diff --git a/src/Greenshot.Editor/Controls/NonJumpingPanel.cs b/src/Greenshot.Editor/Controls/NonJumpingPanel.cs index 3ce0fbdaf..fcdd40b96 100644 --- a/src/Greenshot.Editor/Controls/NonJumpingPanel.cs +++ b/src/Greenshot.Editor/Controls/NonJumpingPanel.cs @@ -29,12 +29,10 @@ namespace Greenshot.Editor.Controls /// 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; /// /// Add horizontal scrolling to the panel, when using the wheel and the shift key is pressed diff --git a/src/Greenshot.Editor/Controls/Pipette.cs b/src/Greenshot.Editor/Controls/Pipette.cs index 9a07f235a..830a7ab72 100644 --- a/src/Greenshot.Editor/Controls/Pipette.cs +++ b/src/Greenshot.Editor/Controls/Pipette.cs @@ -78,10 +78,7 @@ namespace Greenshot.Editor.Controls /// /// The bulk of the clean-up code is implemented in Dispose(bool) /// - public new void Dispose() - { - Dispose(true); - } + public new void Dispose() => Dispose(true); /// /// 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; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Controls/ToolStripColorButton.cs b/src/Greenshot.Editor/Controls/ToolStripColorButton.cs index eb05a0fcc..c0eae1707 100644 --- a/src/Greenshot.Editor/Controls/ToolStripColorButton.cs +++ b/src/Greenshot.Editor/Controls/ToolStripColorButton.cs @@ -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); diff --git a/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs b/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs index c8b41a4a5..7de612b60 100644 --- a/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs +++ b/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs @@ -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")); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Destinations/EditorDestination.cs b/src/Greenshot.Editor/Destinations/EditorDestination.cs index 95d6d42ba..b465c97c3 100644 --- a/src/Greenshot.Editor/Destinations/EditorDestination.cs +++ b/src/Greenshot.Editor/Destinations/EditorDestination.cs @@ -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; diff --git a/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs index c53f098c8..9b8efbe19 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs @@ -51,10 +51,7 @@ namespace Greenshot.Editor.Drawing.Adorners /// /// Returns the cursor for when the mouse is over the adorner /// - 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 /// /// /// - public virtual void MouseUp(object sender, MouseEventArgs mouseEventArgs) - { - EditStatus = EditStatus.IDLE; - } + public virtual void MouseUp(object sender, MouseEventArgs mouseEventArgs) => EditStatus = EditStatus.IDLE; /// /// Return the location of the adorner @@ -129,19 +123,13 @@ namespace Greenshot.Editor.Drawing.Adorners /// /// The adorner is active if the edit status is not idle or undrawn /// - public virtual bool IsActive - { - get { return EditStatus != EditStatus.IDLE && EditStatus != EditStatus.UNDRAWN; } - } + public virtual bool IsActive => EditStatus != EditStatus.IDLE && EditStatus != EditStatus.UNDRAWN; /// /// Adjust UI elements to the supplied DPI settings /// /// uint - 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; diff --git a/src/Greenshot.Editor/Drawing/Adorners/MoveAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/MoveAdorner.cs index 61fc8de11..a898d4729 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/MoveAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/MoveAdorner.cs @@ -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; /// /// Returns the cursor for when the mouse is over the adorner diff --git a/src/Greenshot.Editor/Drawing/Adorners/ResizeAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/ResizeAdorner.cs index 263d5a31e..4942c2780 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/ResizeAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/ResizeAdorner.cs @@ -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; /// /// Returns the cursor for when the mouse is over the adorner diff --git a/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs index 11028df1d..d1e883af7 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs @@ -45,10 +45,7 @@ namespace Greenshot.Editor.Drawing.Adorners /// /// object /// MouseEventArgs - public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) - { - EditStatus = EditStatus.MOVING; - } + public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) => EditStatus = EditStatus.MOVING; /// /// Handle the mouse move diff --git a/src/Greenshot.Editor/Drawing/CropContainer.cs b/src/Greenshot.Editor/Drawing/CropContainer.cs index 5960c63c3..ae3f3536d 100644 --- a/src/Greenshot.Editor/Drawing/CropContainer.cs +++ b/src/Greenshot.Editor/Drawing/CropContainer.cs @@ -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(); /// /// 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) /// - 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 /// 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) { diff --git a/src/Greenshot.Editor/Drawing/CursorContainer.cs b/src/Greenshot.Editor/Drawing/CursorContainer.cs index a3bc851d7..47076a3d4 100644 --- a/src/Greenshot.Editor/Drawing/CursorContainer.cs +++ b/src/Greenshot.Editor/Drawing/CursorContainer.cs @@ -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 { diff --git a/src/Greenshot.Editor/Drawing/DrawableContainer.cs b/src/Greenshot.Editor/Drawing/DrawableContainer.cs index f3236f25c..deedd7ee8 100644 --- a/src/Greenshot.Editor/Drawing/DrawableContainer.cs +++ b/src/Greenshot.Editor/Drawing/DrawableContainer.cs @@ -74,10 +74,7 @@ namespace Greenshot.Editor.Drawing protected EditStatus _defaultEditMode = EditStatus.DRAWING; - public EditStatus DefaultEditMode - { - get { return _defaultEditMode; } - } + public EditStatus DefaultEditMode => _defaultEditMode; /// /// 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 /// /// /// - public static float CalculateScaleY(Matrix matrix) - { - return matrix.Elements[M22]; - } + public static float CalculateScaleY(Matrix matrix) => matrix.Elements[M22]; /// /// Retrieve the X scale from the matrix /// /// /// - public static float CalculateScaleX(Matrix matrix) - { - return matrix.Elements[M11]; - } + public static float CalculateScaleX(Matrix matrix) => matrix.Elements[M11]; /// /// Retrieve the rotation angle from the matrix @@ -630,9 +606,8 @@ namespace Greenshot.Editor.Drawing /// 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; diff --git a/src/Greenshot.Editor/Drawing/DrawableContainerList.cs b/src/Greenshot.Editor/Drawing/DrawableContainerList.cs index c1a06a50a..f4804fa92 100644 --- a/src/Greenshot.Editor/Drawing/DrawableContainerList.cs +++ b/src/Greenshot.Editor/Drawing/DrawableContainerList.cs @@ -53,15 +53,9 @@ namespace Greenshot.Editor.Drawing { } - public DrawableContainerList(IEnumerable elements) - { - AddRange(elements); - } + public DrawableContainerList(IEnumerable 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 AsIDrawableContainerList() { List interfaceList = new(); - foreach (IDrawableContainer container in this) - { - interfaceList.Add(container); - } + interfaceList.AddRange(this); return interfaceList; } @@ -275,12 +266,11 @@ namespace Greenshot.Editor.Drawing /// 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); - } /// /// Adjust UI elements to the supplied DPI settings diff --git a/src/Greenshot.Editor/Drawing/EllipseContainer.cs b/src/Greenshot.Editor/Drawing/EllipseContainer.cs index 5b4816678..66263fa3a 100644 --- a/src/Greenshot.Editor/Drawing/EllipseContainer.cs +++ b/src/Greenshot.Editor/Drawing/EllipseContainer.cs @@ -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); /// /// 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 diff --git a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs index 1bcc6c68b..16b6ab273 100644 --- a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs +++ b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs @@ -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 GetFields() - { - return fields; - } + public IList 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); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs index 6116ad3cb..1eba099f1 100644 --- a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -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 Children = new List(); - 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; } } diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs index 3cd8b0f3b..464a0c283 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs @@ -28,15 +28,12 @@ namespace Greenshot.Editor.Drawing.Fields.Binding /// public abstract class AbstractBindingConverter : 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); diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs index ac14baede..212d4fb71 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs @@ -72,10 +72,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding /// Property of 2nd object to bind /// taking care of converting the synchronized value to the correct target format and back 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; /// /// Bind properties of two objects bidirectionally, converting the values using a converter. @@ -87,10 +84,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding /// Property of 2nd object to bind /// validator to intercept synchronization if the value does not match certain criteria 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; /// /// Bind properties of two objects bidirectionally, converting the values using a converter. @@ -103,10 +97,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding /// taking care of converting the synchronized value to the correct target format and back /// validator to intercept synchronization if the value does not match certain criteria 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) { diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalDoublePercentageConverter.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalDoublePercentageConverter.cs index 0e8a35ddf..9c9c0af0d 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalDoublePercentageConverter.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalDoublePercentageConverter.cs @@ -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(); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalFloatConverter.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalFloatConverter.cs index 1f8e7a182..25fd58b04 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalFloatConverter.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalFloatConverter.cs @@ -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(); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalIntConverter.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalIntConverter.cs index 882ceaac9..63110c45e 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalIntConverter.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalIntConverter.cs @@ -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(); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/NotNullValidator.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/NotNullValidator.cs index 426a560ee..d3e588f8e 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/NotNullValidator.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/NotNullValidator.cs @@ -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(); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/Field.cs b/src/Greenshot.Editor/Drawing/Fields/Field.cs index 2d31f47e8..951ed6c58 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Field.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Field.cs @@ -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; /// /// 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. /// /// - 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); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs b/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs index 045312a42..b109745e5 100644 --- a/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs +++ b/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs @@ -164,29 +164,26 @@ namespace Greenshot.Editor.Drawing.Fields private IList FindCommonFields() { IList 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 fieldsToRemove = new List(); + foreach (IField field in returnFields) { - if (_boundContainers[i] is not DrawableContainer dc) continue; - IList fieldsToRemove = new List(); - 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); } } } diff --git a/src/Greenshot.Editor/Drawing/Fields/FieldType.cs b/src/Greenshot.Editor/Drawing/Fields/FieldType.cs index 9983e2e4a..1a79fb6f9 100644 --- a/src/Greenshot.Editor/Drawing/Fields/FieldType.cs +++ b/src/Greenshot.Editor/Drawing/Fields/FieldType.cs @@ -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); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/FilterContainer.cs b/src/Greenshot.Editor/Drawing/FilterContainer.cs index 3a4a7395a..8d29275b3 100644 --- a/src/Greenshot.Editor/Drawing/FilterContainer.cs +++ b/src/Greenshot.Editor/Drawing/FilterContainer.cs @@ -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() { diff --git a/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs b/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs index 334a7c1af..e1b9ea13b 100644 --- a/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs @@ -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)); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs b/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs index 010cfd2cb..9a90a0235 100644 --- a/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs @@ -41,7 +41,7 @@ namespace Greenshot.Editor.Drawing.Filters set { previewQuality = value; - OnPropertyChanged("PreviewQuality"); + OnPropertyChanged(nameof(PreviewQuality)); } } diff --git a/src/Greenshot.Editor/Drawing/Filters/BrightnessFilter.cs b/src/Greenshot.Editor/Drawing/Filters/BrightnessFilter.cs index 639b0e5ac..5168a7916 100644 --- a/src/Greenshot.Editor/Drawing/Filters/BrightnessFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/BrightnessFilter.cs @@ -33,10 +33,7 @@ namespace Greenshot.Editor.Drawing.Filters [Serializable()] public class BrightnessFilter : AbstractFilter { - public BrightnessFilter(DrawableContainer parent) : base(parent) - { - AddField(GetType(), FieldType.BRIGHTNESS, 0.9d); - } + public BrightnessFilter(DrawableContainer parent) : base(parent) => AddField(GetType(), FieldType.BRIGHTNESS, 0.9d); /// /// Implements the Apply code for the Brightness Filet diff --git a/src/Greenshot.Editor/Drawing/Filters/HighlightFilter.cs b/src/Greenshot.Editor/Drawing/Filters/HighlightFilter.cs index 24624d193..8b807dc33 100644 --- a/src/Greenshot.Editor/Drawing/Filters/HighlightFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/HighlightFilter.cs @@ -35,10 +35,7 @@ namespace Greenshot.Editor.Drawing.Filters [Serializable()] public class HighlightFilter : AbstractFilter { - public HighlightFilter(DrawableContainer parent) : base(parent) - { - AddField(GetType(), FieldType.FILL_COLOR, Color.Yellow); - } + public HighlightFilter(DrawableContainer parent) : base(parent) => AddField(GetType(), FieldType.FILL_COLOR, Color.Yellow); /// /// Implements the Apply code for the Brightness Filet diff --git a/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs b/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs index 47a8e3a58..a1e366047 100644 --- a/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs @@ -35,10 +35,7 @@ namespace Greenshot.Editor.Drawing.Filters [Serializable] public class MagnifierFilter : AbstractFilter { - public MagnifierFilter(DrawableContainer parent) : base(parent) - { - AddField(GetType(), FieldType.MAGNIFICATION_FACTOR, 2); - } + public MagnifierFilter(DrawableContainer parent) : base(parent) => AddField(GetType(), FieldType.MAGNIFICATION_FACTOR, 2); public override void Apply(Graphics graphics, Bitmap applyBitmap, NativeRect rect, RenderMode renderMode) { diff --git a/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs b/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs index 97604e995..06cfb7942 100644 --- a/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs @@ -36,10 +36,7 @@ namespace Greenshot.Editor.Drawing.Filters [Serializable()] public class PixelizationFilter : AbstractFilter { - public PixelizationFilter(DrawableContainer parent) : base(parent) - { - AddField(GetType(), FieldType.PIXEL_SIZE, 5); - } + public PixelizationFilter(DrawableContainer parent) : base(parent) => AddField(GetType(), FieldType.PIXEL_SIZE, 5); public override void Apply(Graphics graphics, Bitmap applyBitmap, NativeRect rect, RenderMode renderMode) { diff --git a/src/Greenshot.Editor/Drawing/FreehandContainer.cs b/src/Greenshot.Editor/Drawing/FreehandContainer.cs index bae2025d5..0c604b49c 100644 --- a/src/Greenshot.Editor/Drawing/FreehandContainer.cs +++ b/src/Greenshot.Editor/Drawing/FreehandContainer.cs @@ -76,10 +76,7 @@ namespace Greenshot.Editor.Drawing RecalculatePath(); } - protected override void OnDeserialized(StreamingContext context) - { - RecalculatePath(); - } + protected override void OnDeserialized(StreamingContext context) => RecalculatePath(); /// /// This Dispose is called from the Dispose and the Destructor. @@ -204,7 +201,7 @@ namespace Greenshot.Editor.Drawing { Width = lineThickness }; - if (!(pen.Width > 0)) + if (pen.Width <= 0) { return; } @@ -294,10 +291,7 @@ namespace Greenshot.Editor.Drawing return ret; } - public override int GetHashCode() - { - return freehandPath?.GetHashCode() ?? 0; - } + public override int GetHashCode() => freehandPath?.GetHashCode() ?? 0; public override bool ClickableAt(int x, int y) { diff --git a/src/Greenshot.Editor/Drawing/HighlightContainer.cs b/src/Greenshot.Editor/Drawing/HighlightContainer.cs index 62994bd87..c84698921 100644 --- a/src/Greenshot.Editor/Drawing/HighlightContainer.cs +++ b/src/Greenshot.Editor/Drawing/HighlightContainer.cs @@ -34,10 +34,7 @@ namespace Greenshot.Editor.Drawing [Serializable] public class HighlightContainer : FilterContainer { - public HighlightContainer(ISurface parent) : base(parent) - { - Init(); - } + public HighlightContainer(ISurface parent) : base(parent) => Init(); /// /// Use settings from base, extend with our own field @@ -48,10 +45,7 @@ namespace Greenshot.Editor.Drawing AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT); } - protected override void OnDeserialized(StreamingContext context) - { - Init(); - } + protected override void OnDeserialized(StreamingContext context) => Init(); private void Init() { diff --git a/src/Greenshot.Editor/Drawing/IconContainer.cs b/src/Greenshot.Editor/Drawing/IconContainer.cs index 6ef6d49df..44441e533 100644 --- a/src/Greenshot.Editor/Drawing/IconContainer.cs +++ b/src/Greenshot.Editor/Drawing/IconContainer.cs @@ -41,10 +41,7 @@ namespace Greenshot.Editor.Drawing protected Icon icon; - public IconContainer(ISurface parent) : base(parent) - { - Init(); - } + public IconContainer(ISurface parent) : base(parent) => Init(); protected override void OnDeserialized(StreamingContext streamingContext) { @@ -52,20 +49,11 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); - public IconContainer(ISurface parent, string filename) : base(parent) - { - Load(filename); - } + public IconContainer(ISurface parent, string filename) : base(parent) => Load(filename); - public IconContainer(ISurface parent, Stream stream) : base(parent) - { - Load(stream); - } + public IconContainer(ISurface parent, Stream stream) : base(parent) => Load(stream); public Icon Icon { diff --git a/src/Greenshot.Editor/Drawing/ImageContainer.cs b/src/Greenshot.Editor/Drawing/ImageContainer.cs index 089c9a54e..e8f83c787 100644 --- a/src/Greenshot.Editor/Drawing/ImageContainer.cs +++ b/src/Greenshot.Editor/Drawing/ImageContainer.cs @@ -56,10 +56,7 @@ namespace Greenshot.Editor.Drawing /// [NonSerialized] private readonly NativePoint _shadowOffset = new(-1, -1); - public ImageContainer(ISurface parent, string filename) : this(parent) - { - Load(filename); - } + public ImageContainer(ISurface parent, string filename) : this(parent) => Load(filename); public ImageContainer(ISurface parent) : base(parent) { @@ -73,15 +70,9 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); - protected override void InitializeFields() - { - AddField(GetType(), FieldType.SHADOW, false); - } + protected override void InitializeFields() => AddField(GetType(), FieldType.SHADOW, false); protected void BitmapContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { diff --git a/src/Greenshot.Editor/Drawing/LineContainer.cs b/src/Greenshot.Editor/Drawing/LineContainer.cs index d9f03abbf..cb0c83eba 100644 --- a/src/Greenshot.Editor/Drawing/LineContainer.cs +++ b/src/Greenshot.Editor/Drawing/LineContainer.cs @@ -37,10 +37,7 @@ namespace Greenshot.Editor.Drawing [Serializable()] public class LineContainer : DrawableContainer { - public LineContainer(ISurface parent) : base(parent) - { - Init(); - } + public LineContainer(ISurface parent) : base(parent) => Init(); protected override void InitializeFields() { @@ -49,10 +46,7 @@ namespace Greenshot.Editor.Drawing AddField(GetType(), FieldType.SHADOW, true); } - protected override void OnDeserialized(StreamingContext context) - { - Init(); - } + protected override void OnDeserialized(StreamingContext context) => Init(); protected void Init() { @@ -114,9 +108,6 @@ namespace Greenshot.Editor.Drawing return false; } - protected override IDoubleProcessor GetAngleRoundProcessor() - { - return LineAngleRoundBehavior.INSTANCE; - } + protected override IDoubleProcessor GetAngleRoundProcessor() => LineAngleRoundBehavior.INSTANCE; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs b/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs index 453735457..62183518d 100644 --- a/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs +++ b/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs @@ -34,10 +34,7 @@ namespace Greenshot.Editor.Drawing [Serializable] public class ObfuscateContainer : FilterContainer { - public ObfuscateContainer(ISurface parent) : base(parent) - { - Init(); - } + public ObfuscateContainer(ISurface parent) : base(parent) => Init(); protected override void InitializeFields() { @@ -45,10 +42,7 @@ namespace Greenshot.Editor.Drawing AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE); } - protected override void OnDeserialized(StreamingContext context) - { - Init(); - } + protected override void OnDeserialized(StreamingContext context) => Init(); private void Init() { @@ -59,12 +53,9 @@ namespace Greenshot.Editor.Drawing protected void ObfuscateContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { - if (sender.Equals(this)) + if (sender.Equals(this) && Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_OBFUSCATE)) { - if (Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_OBFUSCATE)) - { - ConfigurePreparedFilters(); - } + ConfigurePreparedFilters(); } } diff --git a/src/Greenshot.Editor/Drawing/Positions.cs b/src/Greenshot.Editor/Drawing/Positions.cs index 815876255..fd19d1c2f 100644 --- a/src/Greenshot.Editor/Drawing/Positions.cs +++ b/src/Greenshot.Editor/Drawing/Positions.cs @@ -24,7 +24,7 @@ namespace Greenshot.Editor.Drawing /// /// Position /// - public enum Positions : int + public enum Positions { TopLeft = 0, TopCenter = 1, diff --git a/src/Greenshot.Editor/Drawing/RectangleContainer.cs b/src/Greenshot.Editor/Drawing/RectangleContainer.cs index 14faa69c2..316738104 100644 --- a/src/Greenshot.Editor/Drawing/RectangleContainer.cs +++ b/src/Greenshot.Editor/Drawing/RectangleContainer.cs @@ -38,10 +38,7 @@ namespace Greenshot.Editor.Drawing [Serializable] public class RectangleContainer : DrawableContainer { - public RectangleContainer(ISurface parent) : base(parent) - { - Init(); - } + public RectangleContainer(ISurface parent) : base(parent) => Init(); /// /// Do some logic to make sure all field are initiated correctly @@ -53,10 +50,7 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); protected override void InitializeFields() { @@ -145,12 +139,9 @@ namespace Greenshot.Editor.Drawing public static bool RectangleClickableAt(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 diff --git a/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs b/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs index 477985a0a..274a52bb3 100644 --- a/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs +++ b/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs @@ -380,10 +380,7 @@ namespace Greenshot.Editor.Drawing return false; } - public override bool ClickableAt(int x, int y) - { - return Contains(x, y); - } + public override bool ClickableAt(int x, int y) => Contains(x, y); /// /// Additional to the Transform of the TextContainer the bubble tail coordinates also need to be moved diff --git a/src/Greenshot.Editor/Drawing/StepLabelContainer.cs b/src/Greenshot.Editor/Drawing/StepLabelContainer.cs index 198a209db..1a07ea317 100644 --- a/src/Greenshot.Editor/Drawing/StepLabelContainer.cs +++ b/src/Greenshot.Editor/Drawing/StepLabelContainer.cs @@ -50,10 +50,7 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); // Used to store the counter start of the Surface, as the surface is NOT stored. private int _counterStart = 1; @@ -128,10 +125,7 @@ namespace Greenshot.Editor.Drawing /// /// This makes it possible for the label to be placed exactly in the middle of the pointer. /// - public override bool HandleMouseDown(int mouseX, int mouseY) - { - return base.HandleMouseDown(mouseX - (Width / 2), mouseY - (Height / 2)); - } + public override bool HandleMouseDown(int mouseX, int mouseY) => base.HandleMouseDown(mouseX - (Width / 2), mouseY - (Height / 2)); /// /// We set our own field values diff --git a/src/Greenshot.Editor/Drawing/Surface.cs b/src/Greenshot.Editor/Drawing/Surface.cs index 715f81742..409c3b655 100644 --- a/src/Greenshot.Editor/Drawing/Surface.cs +++ b/src/Greenshot.Editor/Drawing/Surface.cs @@ -242,10 +242,7 @@ namespace Greenshot.Editor.Drawing } } - public void RemoveStepLabel(StepLabelContainer stepLabel) - { - _stepLabels.Remove(stepLabel); - } + public void RemoveStepLabel(StepLabelContainer stepLabel) => _stepLabels.Remove(stepLabel); /// /// The start value of the counter objects @@ -878,14 +875,9 @@ namespace Greenshot.Editor.Drawing } else { - if (ClipboardHelper.ContainsImage(e.Data) || ClipboardHelper.ContainsFormat(e.Data, "DragImageBits")) - { - e.Effect = DragDropEffects.Copy; - } - else - { - e.Effect = DragDropEffects.None; - } + e.Effect = ClipboardHelper.ContainsImage(e.Data) || ClipboardHelper.ContainsFormat(e.Data, "DragImageBits") + ? DragDropEffects.Copy + : DragDropEffects.None; } } @@ -1426,7 +1418,7 @@ namespace Greenshot.Editor.Drawing _mouseDown = true; _isSurfaceMoveMadeUndoable = false; - if (_cropContainer != null && ((_undrawnElement == null) || (_undrawnElement != null && DrawingMode != DrawingModes.Crop))) + if (_cropContainer != null && ((_undrawnElement == null) || (DrawingMode != DrawingModes.Crop))) { RemoveElement(_cropContainer, false); _cropContainer = null; @@ -1675,10 +1667,7 @@ namespace Greenshot.Editor.Drawing /// This returns the image "result" of this surface, with all the elements rendered on it. /// /// - public Image GetImageForExport() - { - return GetImage(RenderMode.EXPORT); - } + public Image GetImageForExport() => GetImage(RenderMode.EXPORT); private static NativeRect ZoomClipRectangle(NativeRect rc, double scale, int inflateAmount = 0) { @@ -1735,13 +1724,10 @@ namespace Greenshot.Editor.Drawing if (Elements.HasIntersectingFilters(imageClipRectangle) || _zoomFactor > Fraction.Identity) { - if (_buffer != null) + if (_buffer != null && (_buffer.Width != Image.Width || _buffer.Height != Image.Height || _buffer.PixelFormat != Image.PixelFormat)) { - if (_buffer.Width != Image.Width || _buffer.Height != Image.Height || _buffer.PixelFormat != Image.PixelFormat) - { - _buffer.Dispose(); - _buffer = null; - } + _buffer.Dispose(); + _buffer = null; } if (_buffer == null) @@ -2373,10 +2359,7 @@ namespace Greenshot.Editor.Drawing /// /// Deselect all the selected elements /// - public void DeselectAllElements() - { - DeselectElements(selectedElements); - } + public void DeselectAllElements() => DeselectElements(selectedElements); /// /// Select the supplied element @@ -2409,10 +2392,7 @@ namespace Greenshot.Editor.Drawing /// /// Select all elements, this is called when Ctrl+A is pressed /// - public void SelectAllElements() - { - SelectElements(Elements); - } + public void SelectAllElements() => SelectElements(Elements); /// /// Select the supplied elements @@ -2630,29 +2610,17 @@ namespace Greenshot.Editor.Drawing /// indicates whether the selected elements could be pulled up in hierarchy /// /// true if selected elements could be pulled up, false otherwise - public bool CanPullSelectionUp() - { - return Elements.CanPullUp(selectedElements); - } + public bool CanPullSelectionUp() => Elements.CanPullUp(selectedElements); /// /// indicates whether the selected elements could be pushed down in hierarchy /// /// true if selected elements could be pushed down, false otherwise - public bool CanPushSelectionDown() - { - return Elements.CanPushDown(selectedElements); - } + public bool CanPushSelectionDown() => Elements.CanPushDown(selectedElements); - private void Element_FieldChanged(object sender, FieldChangedEventArgs e) - { - selectedElements.HandleFieldChangedEvent(sender, e); - } + private void Element_FieldChanged(object sender, FieldChangedEventArgs e) => selectedElements.HandleFieldChangedEvent(sender, e); - public bool IsOnSurface(IDrawableContainer container) - { - return Elements.Contains(container); - } + public bool IsOnSurface(IDrawableContainer container) => Elements.Contains(container); public NativePoint ToSurfaceCoordinates(NativePoint point) { diff --git a/src/Greenshot.Editor/Drawing/TextContainer.cs b/src/Greenshot.Editor/Drawing/TextContainer.cs index 170d91607..6db53e4e6 100644 --- a/src/Greenshot.Editor/Drawing/TextContainer.cs +++ b/src/Greenshot.Editor/Drawing/TextContainer.cs @@ -85,10 +85,7 @@ namespace Greenshot.Editor.Drawing OnPropertyChanged("Text"); } - public TextContainer(ISurface parent) : base(parent) - { - Init(); - } + public TextContainer(ISurface parent) : base(parent) => Init(); protected override void InitializeFields() { @@ -272,10 +269,7 @@ namespace Greenshot.Editor.Drawing } } - public override void OnDoubleClick() - { - ShowTextBox(); - } + public override void OnDoubleClick() => ShowTextBox(); private void CreateTextBox() { @@ -322,14 +316,7 @@ namespace Greenshot.Editor.Drawing } Color lc = GetFieldValueAsColor(FieldType.LINE_COLOR); - if (lc.R > 203 && lc.G > 203 && lc.B > 203) - { - _textBox.BackColor = Color.FromArgb(51, 51, 51); - } - else - { - _textBox.BackColor = Color.White; - } + _textBox.BackColor = lc.R > 203 && lc.G > 203 && lc.B > 203 ? Color.FromArgb(51, 51, 51) : Color.White; } private void HideTextBox() diff --git a/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs b/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs index 8d710dd65..ce43a679e 100644 --- a/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs +++ b/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs @@ -48,10 +48,7 @@ namespace Greenshot.Editor.Drawing /// Constructor takes care of calling Init /// /// ISurface - protected VectorGraphicsContainer(ISurface parent) : base(parent) - { - Init(); - } + protected VectorGraphicsContainer(ISurface parent) : base(parent) => Init(); /// /// Make sure Init is called after deserializing diff --git a/src/Greenshot.Editor/EditorInitialize.cs b/src/Greenshot.Editor/EditorInitialize.cs index c1ee27db8..337442023 100644 --- a/src/Greenshot.Editor/EditorInitialize.cs +++ b/src/Greenshot.Editor/EditorInitialize.cs @@ -27,9 +27,7 @@ namespace Greenshot.Editor { public static class EditorInitialize { - public static void Initialize() - { - SimpleServiceProvider.Current.AddService( + public static void Initialize() => SimpleServiceProvider.Current.AddService( // All generic things, like gif, png, jpg etc. new DefaultFileFormatHandler(), // Greenshot format @@ -45,6 +43,5 @@ namespace Greenshot.Editor // JPG XR new WpfFileFormatHandler() ); - } } } diff --git a/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs index 7c2621a0d..c3e3de27b 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs @@ -35,10 +35,7 @@ namespace Greenshot.Editor.FileFormatHandlers public IDictionary> SupportedExtensions { get; } = new Dictionary>(); /// - public virtual int PriorityFor(FileFormatHandlerActions fileFormatHandlerAction, string extension) - { - return 0; - } + public virtual int PriorityFor(FileFormatHandlerActions fileFormatHandlerAction, string extension) => 0; public abstract bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null); diff --git a/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs index 09b52b6b3..b82857e61 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs @@ -45,10 +45,7 @@ namespace Greenshot.Editor.FileFormatHandlers } /// - public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null) - { - return false; - } + public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null) => false; /// public override bool TryLoadFromStream(Stream stream, string extension, out Bitmap bitmap) diff --git a/src/Greenshot.Editor/FileFormatHandlers/SvgFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/SvgFileFormatHandler.cs index 14a33246e..43fa3f463 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/SvgFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/SvgFileFormatHandler.cs @@ -63,11 +63,9 @@ namespace Greenshot.Editor.FileFormatHandlers return false; } - public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null) - { + public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null) => // TODO: Implement this - return false; - } + false; public override IEnumerable LoadDrawablesFromStream(Stream stream, string extension, ISurface parent = null) { diff --git a/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs index 9d81d394b..aa1e5cf93 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs @@ -47,7 +47,7 @@ namespace Greenshot.Editor.FileFormatHandlers public WpfFileFormatHandler() { - LoadFromStreamExtensions = LoadFromStreamExtensions.ToList().Concat(RetrieveSupportedExtensions()).OrderBy(e => e).Distinct().ToArray(); + LoadFromStreamExtensions = LoadFromStreamExtensions.AsEnumerable().Concat(RetrieveSupportedExtensions()).OrderBy(e => e).Distinct().ToArray(); SupportedExtensions[FileFormatHandlerActions.LoadDrawableFromStream] = LoadFromStreamExtensions; SupportedExtensions[FileFormatHandlerActions.LoadFromStream] = LoadFromStreamExtensions; @@ -60,16 +60,7 @@ namespace Greenshot.Editor.FileFormatHandlers /// IEnumerable{string} private IEnumerable RetrieveSupportedExtensions() { - string baseKeyPath; - if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess) - { - baseKeyPath = "Wow6432Node\\CLSID"; - } - else - { - baseKeyPath = "CLSID"; - } - + string baseKeyPath = Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess ? "Wow6432Node\\CLSID" : "CLSID"; using RegistryKey baseKey = Registry.ClassesRoot.OpenSubKey(baseKeyPath, false); if (baseKey == null) yield break; diff --git a/src/Greenshot.Editor/Forms/ColorDialog.cs b/src/Greenshot.Editor/Forms/ColorDialog.cs index 5b30e64e2..7853788ca 100644 --- a/src/Greenshot.Editor/Forms/ColorDialog.cs +++ b/src/Greenshot.Editor/Forms/ColorDialog.cs @@ -108,10 +108,7 @@ namespace Greenshot.Editor.Forms } } - private Button CreateColorButton(int red, int green, int blue, int x, int y, int w, int h) - { - return CreateColorButton(Color.FromArgb(255, red, green, blue), x, y, w, h); - } + private Button CreateColorButton(int red, int green, int blue, int x, int y, int w, int h) => CreateColorButton(Color.FromArgb(255, red, green, blue), x, y, w, h); private Button CreateColorButton(Color color, int x, int y, int w, int h) { @@ -235,10 +232,7 @@ namespace Greenshot.Editor.Forms GetColorPartIntFromString(textBoxBlue.Text)), textBox); } - private void TextBoxGotFocus(object sender, EventArgs e) - { - textBoxHtmlColor.SelectAll(); - } + private void TextBoxGotFocus(object sender, EventArgs e) => textBoxHtmlColor.SelectAll(); private void TextBoxKeyDown(object sender, KeyEventArgs e) { @@ -254,15 +248,9 @@ namespace Greenshot.Editor.Forms PreviewColor(b.BackColor, b); } - private void SetButtonTooltip(Button colorButton, Color color) - { - _toolTip.SetToolTip(colorButton, ColorTranslator.ToHtml(color) + " | R:" + color.R + ", G:" + color.G + ", B:" + color.B); - } + private void SetButtonTooltip(Button colorButton, Color color) => _toolTip.SetToolTip(colorButton, ColorTranslator.ToHtml(color) + " | R:" + color.R + ", G:" + color.G + ", B:" + color.B); - private void BtnTransparentClick(object sender, EventArgs e) - { - ColorButtonClick(sender, e); - } + private void BtnTransparentClick(object sender, EventArgs e) => ColorButtonClick(sender, e); private void BtnApplyClick(object sender, EventArgs e) { @@ -286,9 +274,6 @@ namespace Greenshot.Editor.Forms return ret; } - private void PipetteUsed(object sender, PipetteUsedArgs e) - { - Color = e.Color; - } + private void PipetteUsed(object sender, PipetteUsedArgs e) => Color = e.Color; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs b/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs index 6e1fbb942..c1c7421ca 100644 --- a/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs +++ b/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs @@ -88,9 +88,6 @@ namespace Greenshot.Editor.Forms { public Color Color; - public ColorPickerEventArgs(Color color) - { - Color = color; - } + public ColorPickerEventArgs(Color color) => Color = color; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Forms/ImageEditorForm.cs b/src/Greenshot.Editor/Forms/ImageEditorForm.cs index 816f9234d..9afcca2cb 100644 --- a/src/Greenshot.Editor/Forms/ImageEditorForm.cs +++ b/src/Greenshot.Editor/Forms/ImageEditorForm.cs @@ -135,10 +135,7 @@ namespace Greenshot.Editor.Forms Initialize(surface, false); } - public ImageEditorForm(ISurface surface, bool outputMade) - { - Initialize(surface, outputMade); - } + public ImageEditorForm(ISurface surface, bool outputMade) => Initialize(surface, outputMade); private void Initialize(ISurface surface, bool outputMade) { @@ -331,40 +328,37 @@ namespace Greenshot.Editor.Forms /// /// Get all the destinations and display them in the file menu and the buttons /// - private void AddDestinations() - { - Invoke((MethodInvoker)delegate - { - // Create export buttons - foreach (IDestination destination in DestinationHelper.GetAllDestinations()) - { - if (destination.Priority <= 2) - { - continue; - } + private void AddDestinations() => Invoke((MethodInvoker)delegate + { + // Create export buttons + foreach (IDestination destination in DestinationHelper.GetAllDestinations()) + { + if (destination.Priority <= 2) + { + continue; + } - if (!destination.IsActive) - { - continue; - } + if (!destination.IsActive) + { + continue; + } - if (destination.DisplayIcon == null) - { - continue; - } + if (destination.DisplayIcon == null) + { + continue; + } - try - { - AddDestinationButton(destination); - } - catch (Exception addingException) - { - Log.WarnFormat("Problem adding destination {0}", destination.Designation); - Log.Warn("Exception: ", addingException); - } - } - }); - } + try + { + AddDestinationButton(destination); + } + catch (Exception addingException) + { + Log.WarnFormat("Problem adding destination {0}", destination.Designation); + Log.Warn("Exception: ", addingException); + } + } + }); private void AddDestinationButton(IDestination toolstripDestination) { @@ -515,40 +509,28 @@ namespace Greenshot.Editor.Forms /// /// object /// SurfaceForegroundColorEventArgs - private void ForegroundColorChanged(object sender, SurfaceForegroundColorEventArgs eventArgs) - { - _surface.FieldAggregator.GetField(FieldType.LINE_COLOR).Value = eventArgs.Color; - } + private void ForegroundColorChanged(object sender, SurfaceForegroundColorEventArgs eventArgs) => _surface.FieldAggregator.GetField(FieldType.LINE_COLOR).Value = eventArgs.Color; /// /// This is called when the background color of the select element chances, used for shortcuts /// /// object /// SurfaceBackgroundColorEventArgs - private void BackgroundColorChanged(object sender, SurfaceBackgroundColorEventArgs eventArgs) - { - _surface.FieldAggregator.GetField(FieldType.FILL_COLOR).Value = eventArgs.Color; - } + private void BackgroundColorChanged(object sender, SurfaceBackgroundColorEventArgs eventArgs) => _surface.FieldAggregator.GetField(FieldType.FILL_COLOR).Value = eventArgs.Color; /// /// This is called when the line thickness of the select element chances, used for shortcuts /// /// object /// SurfaceLineThicknessEventArgs - private void LineThicknessChanged(object sender, SurfaceLineThicknessEventArgs eventArgs) - { - _surface.FieldAggregator.GetField(FieldType.LINE_THICKNESS).Value = eventArgs.Thickness; - } + private void LineThicknessChanged(object sender, SurfaceLineThicknessEventArgs eventArgs) => _surface.FieldAggregator.GetField(FieldType.LINE_THICKNESS).Value = eventArgs.Thickness; /// /// This is called when the shadow of the select element chances, used for shortcuts /// /// object /// SurfaceShadowEventArgs - private void ShadowChanged(object sender, SurfaceShadowEventArgs eventArgs) - { - _surface.FieldAggregator.GetField(FieldType.SHADOW).Value = eventArgs.HasShadow; - } + private void ShadowChanged(object sender, SurfaceShadowEventArgs eventArgs) => _surface.FieldAggregator.GetField(FieldType.SHADOW).Value = eventArgs.HasShadow; /// /// This is called when the size of the surface chances, used for resizing and displaying the size information @@ -637,10 +619,7 @@ namespace Greenshot.Editor.Forms /** * Interfaces for plugins, see GreenshotInterface for more details! */ - public Image GetImageForExport() - { - return _surface.GetImageForExport(); - } + public Image GetImageForExport() => _surface.GetImageForExport(); public ICaptureDetails CaptureDetails => _surface.CaptureDetails; @@ -655,21 +634,13 @@ namespace Greenshot.Editor.Forms DestinationHelper.ExportCapture(true, destinationDesignation, _surface, _surface.CaptureDetails); } - private void BtnClipboardClick(object sender, EventArgs e) - { - DestinationHelper.ExportCapture(true, WellKnownDestinations.Clipboard, _surface, _surface.CaptureDetails); - } + private void BtnClipboardClick(object sender, EventArgs e) => DestinationHelper.ExportCapture(true, WellKnownDestinations.Clipboard, _surface, _surface.CaptureDetails); - private void BtnPrintClick(object sender, EventArgs e) - { + private void BtnPrintClick(object sender, EventArgs e) => // The BeginInvoke is a solution for the printdialog not having focus BeginInvoke((MethodInvoker)delegate { DestinationHelper.ExportCapture(true, WellKnownDestinations.Printer, _surface, _surface.CaptureDetails); }); - } - private void CloseToolStripMenuItemClick(object sender, EventArgs e) - { - Close(); - } + private void CloseToolStripMenuItemClick(object sender, EventArgs e) => Close(); private void BtnEllipseClick(object sender, EventArgs e) { @@ -763,55 +734,25 @@ namespace Greenshot.Editor.Forms } } - private void AddRectangleToolStripMenuItemClick(object sender, EventArgs e) - { - BtnRectClick(sender, e); - } + private void AddRectangleToolStripMenuItemClick(object sender, EventArgs e) => BtnRectClick(sender, e); - private void DrawFreehandToolStripMenuItemClick(object sender, EventArgs e) - { - BtnFreehandClick(sender, e); - } + private void DrawFreehandToolStripMenuItemClick(object sender, EventArgs e) => BtnFreehandClick(sender, e); - private void AddEllipseToolStripMenuItemClick(object sender, EventArgs e) - { - BtnEllipseClick(sender, e); - } + private void AddEllipseToolStripMenuItemClick(object sender, EventArgs e) => BtnEllipseClick(sender, e); - private void AddTextBoxToolStripMenuItemClick(object sender, EventArgs e) - { - BtnTextClick(sender, e); - } + private void AddTextBoxToolStripMenuItemClick(object sender, EventArgs e) => BtnTextClick(sender, e); - private void AddSpeechBubbleToolStripMenuItemClick(object sender, EventArgs e) - { - BtnSpeechBubbleClick(sender, e); - } + private void AddSpeechBubbleToolStripMenuItemClick(object sender, EventArgs e) => BtnSpeechBubbleClick(sender, e); - private void AddCounterToolStripMenuItemClick(object sender, EventArgs e) - { - BtnStepLabelClick(sender, e); - } + private void AddCounterToolStripMenuItemClick(object sender, EventArgs e) => BtnStepLabelClick(sender, e); - private void DrawLineToolStripMenuItemClick(object sender, EventArgs e) - { - BtnLineClick(sender, e); - } + private void DrawLineToolStripMenuItemClick(object sender, EventArgs e) => BtnLineClick(sender, e); - private void DrawArrowToolStripMenuItemClick(object sender, EventArgs e) - { - BtnArrowClick(sender, e); - } + private void DrawArrowToolStripMenuItemClick(object sender, EventArgs e) => BtnArrowClick(sender, e); - private void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.RemoveSelectedElements(); - } + private void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) => _surface.RemoveSelectedElements(); - private void BtnDeleteClick(object sender, EventArgs e) - { - RemoveObjectToolStripMenuItemClick(sender, e); - } + private void BtnDeleteClick(object sender, EventArgs e) => RemoveObjectToolStripMenuItemClick(sender, e); private void CutToolStripMenuItemClick(object sender, EventArgs e) { @@ -819,10 +760,7 @@ namespace Greenshot.Editor.Forms UpdateClipboardSurfaceDependencies(); } - private void BtnCutClick(object sender, EventArgs e) - { - CutToolStripMenuItemClick(sender, e); - } + private void BtnCutClick(object sender, EventArgs e) => CutToolStripMenuItemClick(sender, e); private void CopyToolStripMenuItemClick(object sender, EventArgs e) { @@ -830,10 +768,7 @@ namespace Greenshot.Editor.Forms UpdateClipboardSurfaceDependencies(); } - private void BtnCopyClick(object sender, EventArgs e) - { - CopyToolStripMenuItemClick(sender, e); - } + private void BtnCopyClick(object sender, EventArgs e) => CopyToolStripMenuItemClick(sender, e); private void PasteToolStripMenuItemClick(object sender, EventArgs e) { @@ -841,10 +776,7 @@ namespace Greenshot.Editor.Forms UpdateClipboardSurfaceDependencies(); } - private void BtnPasteClick(object sender, EventArgs e) - { - PasteToolStripMenuItemClick(sender, e); - } + private void BtnPasteClick(object sender, EventArgs e) => PasteToolStripMenuItemClick(sender, e); private void UndoToolStripMenuItemClick(object sender, EventArgs e) { @@ -852,10 +784,7 @@ namespace Greenshot.Editor.Forms UpdateUndoRedoSurfaceDependencies(); } - private void BtnUndoClick(object sender, EventArgs e) - { - UndoToolStripMenuItemClick(sender, e); - } + private void BtnUndoClick(object sender, EventArgs e) => UndoToolStripMenuItemClick(sender, e); private void RedoToolStripMenuItemClick(object sender, EventArgs e) { @@ -863,10 +792,7 @@ namespace Greenshot.Editor.Forms UpdateUndoRedoSurfaceDependencies(); } - private void BtnRedoClick(object sender, EventArgs e) - { - RedoToolStripMenuItemClick(sender, e); - } + private void BtnRedoClick(object sender, EventArgs e) => RedoToolStripMenuItemClick(sender, e); private void DuplicateToolStripMenuItemClick(object sender, EventArgs e) { @@ -874,30 +800,15 @@ namespace Greenshot.Editor.Forms UpdateClipboardSurfaceDependencies(); } - private void UpOneLevelToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.PullElementsUp(); - } + private void UpOneLevelToolStripMenuItemClick(object sender, EventArgs e) => _surface.PullElementsUp(); - private void DownOneLevelToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.PushElementsDown(); - } + private void DownOneLevelToolStripMenuItemClick(object sender, EventArgs e) => _surface.PushElementsDown(); - private void UpToTopToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.PullElementsToTop(); - } + private void UpToTopToolStripMenuItemClick(object sender, EventArgs e) => _surface.PullElementsToTop(); - private void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.PushElementsToBottom(); - } + private void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) => _surface.PushElementsToBottom(); - private void HelpToolStripMenuItem1Click(object sender, EventArgs e) - { - HelpFileLoader.LoadHelp(); - } + private void HelpToolStripMenuItem1Click(object sender, EventArgs e) => HelpFileLoader.LoadHelp(); private void AboutToolStripMenuItemClick(object sender, EventArgs e) { @@ -911,15 +822,9 @@ namespace Greenshot.Editor.Forms mainForm.ShowSetting(); } - private void BtnSettingsClick(object sender, EventArgs e) - { - PreferencesToolStripMenuItemClick(sender, e); - } + private void BtnSettingsClick(object sender, EventArgs e) => PreferencesToolStripMenuItemClick(sender, e); - private void BtnHelpClick(object sender, EventArgs e) - { - HelpToolStripMenuItem1Click(sender, e); - } + private void BtnHelpClick(object sender, EventArgs e) => HelpToolStripMenuItem1Click(sender, e); private void ImageEditorFormActivated(object sender, EventArgs e) { @@ -1099,30 +1004,27 @@ namespace Greenshot.Editor.Forms /// MouseEventArgs private void PanelMouseWheel(object sender, MouseEventArgs e) { - if (System.Windows.Forms.Control.ModifierKeys.Equals(Keys.Control)) + //waiting for next zoom step 100 ms + if (System.Windows.Forms.Control.ModifierKeys.Equals(Keys.Control) && _zoomStartTime.AddMilliseconds(100) < DateTime.Now) { - if (_zoomStartTime.AddMilliseconds(100) < DateTime.Now) //waiting for next zoom step 100 ms + _zoomStartTime = DateTime.Now; + switch (e.Delta) { - _zoomStartTime = DateTime.Now; - if (e.Delta > 0) - { + case > 0: ZoomInMenuItemClick(sender, e); - } - else if (e.Delta < 0) - { + break; + case < 0: ZoomOutMenuItemClick(sender, e); - } + break; } } panel1.Focus(); } - protected override bool ProcessKeyPreview(ref Message msg) - { + protected override bool ProcessKeyPreview(ref Message msg) => // disable default key handling if surface has requested a lock - return !_surface.KeysLocked && base.ProcessKeyPreview(ref msg); - } + !_surface.KeysLocked && base.ProcessKeyPreview(ref msg); protected override bool ProcessCmdKey(ref Message msg, Keys keys) { @@ -1171,12 +1073,9 @@ namespace Greenshot.Editor.Forms btnUndo.Enabled = canUndo; undoToolStripMenuItem.Enabled = canUndo; string undoAction = string.Empty; - if (canUndo) + if (canUndo && _surface.UndoActionLanguageKey != LangKey.none) { - if (_surface.UndoActionLanguageKey != LangKey.none) - { - undoAction = Language.GetString(_surface.UndoActionLanguageKey); - } + undoAction = Language.GetString(_surface.UndoActionLanguageKey); } string undoText = Language.GetFormattedString(LangKey.editor_undo, undoAction); @@ -1187,12 +1086,9 @@ namespace Greenshot.Editor.Forms btnRedo.Enabled = canRedo; redoToolStripMenuItem.Enabled = canRedo; string redoAction = string.Empty; - if (canRedo) + if (canRedo && _surface.RedoActionLanguageKey != LangKey.none) { - if (_surface.RedoActionLanguageKey != LangKey.none) - { - redoAction = Language.GetString(_surface.RedoActionLanguageKey); - } + redoAction = Language.GetString(_surface.RedoActionLanguageKey); } string redoText = Language.GetFormattedString(LangKey.editor_redo, redoAction); @@ -1240,15 +1136,9 @@ namespace Greenshot.Editor.Forms ss.ContextMenuStrip?.Show(ss, e.X, e.Y); } - private void CopyPathMenuItemClick(object sender, EventArgs e) - { - ClipboardHelper.SetClipboardData(_surface.LastSaveFullPath); - } + private void CopyPathMenuItemClick(object sender, EventArgs e) => ClipboardHelper.SetClipboardData(_surface.LastSaveFullPath); - private void OpenDirectoryMenuItemClick(object sender, EventArgs e) - { - ExplorerHelper.OpenInExplorer(_surface.LastSaveFullPath); - } + private void OpenDirectoryMenuItemClick(object sender, EventArgs e) => ExplorerHelper.OpenInExplorer(_surface.LastSaveFullPath); private void BindFieldControls() { @@ -1339,16 +1229,9 @@ namespace Greenshot.Editor.Forms private void RefreshEditorControls() { int stepLabels = _surface.CountStepLabels(null); - Image icon; - if (stepLabels <= 20) - { - icon = (Image)resources.GetObject($"btnStepLabel{stepLabels:00}.Image"); - } - else - { - icon = (Image)resources.GetObject("btnStepLabel20+.Image"); - } - + Image icon = stepLabels <= 20 + ? (Image)resources.GetObject($"btnStepLabel{stepLabels:00}.Image") + : (Image)resources.GetObject("btnStepLabel20+.Image"); btnStepLabel.Image = icon; addCounterToolStripMenuItem.Image = icon; @@ -1400,10 +1283,7 @@ namespace Greenshot.Editor.Forms RefreshFieldControls(); } - private void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; - } + private void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) => _surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; private void EditToolStripMenuItemClick(object sender, EventArgs e) { @@ -1449,8 +1329,7 @@ namespace Greenshot.Editor.Forms fontItalicButton.Enabled = italicAvailable; } - bool regularAvailable = fontFamily.IsStyleAvailable(FontStyle.Regular); - if (regularAvailable) + if (fontFamily.IsStyleAvailable(FontStyle.Regular)) { return; } @@ -1462,12 +1341,9 @@ namespace Greenshot.Editor.Forms fontBoldButton.Checked = true; } } - else if (italicAvailable) + else if (italicAvailable && fontItalicButton != null) { - if (fontItalicButton != null) - { - fontItalicButton.Checked = true; - } + fontItalicButton.Checked = true; } } @@ -1481,25 +1357,13 @@ namespace Greenshot.Editor.Forms } } - private void FontBoldButtonClick(object sender, EventArgs e) - { - _originalBoldCheckState = fontBoldButton.Checked; - } + private void FontBoldButtonClick(object sender, EventArgs e) => _originalBoldCheckState = fontBoldButton.Checked; - private void FontItalicButtonClick(object sender, EventArgs e) - { - _originalItalicCheckState = fontItalicButton.Checked; - } + private void FontItalicButtonClick(object sender, EventArgs e) => _originalItalicCheckState = fontItalicButton.Checked; - private void ToolBarFocusableElementGotFocus(object sender, EventArgs e) - { - _surface.KeysLocked = true; - } + private void ToolBarFocusableElementGotFocus(object sender, EventArgs e) => _surface.KeysLocked = true; - private void ToolBarFocusableElementLostFocus(object sender, EventArgs e) - { - _surface.KeysLocked = false; - } + private void ToolBarFocusableElementLostFocus(object sender, EventArgs e) => _surface.KeysLocked = false; private void SaveElementsToolStripMenuItemClick(object sender, EventArgs e) { @@ -1602,10 +1466,7 @@ namespace Greenshot.Editor.Forms RefreshEditorControls(); } - private void SelectAllToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.SelectAllElements(); - } + private void SelectAllToolStripMenuItemClick(object sender, EventArgs e) => _surface.SelectAllElements(); private void BtnConfirmClick(object sender, EventArgs e) { @@ -1803,10 +1664,7 @@ namespace Greenshot.Editor.Forms UpdateUndoRedoSurfaceDependencies(); } - private void ImageEditorFormResize(object sender, EventArgs e) - { - AlignCanvasPositionAfterResize(); - } + private void ImageEditorFormResize(object sender, EventArgs e) => AlignCanvasPositionAfterResize(); private void AlignCanvasPositionAfterResize() { @@ -1826,23 +1684,9 @@ namespace Greenshot.Editor.Forms int offsetX = -panel.HorizontalScroll.Value; int offsetY = -panel.VerticalScroll.Value; - if (currentClientSize.Width > canvasSize.Width) - { - canvas.Left = offsetX + ((currentClientSize.Width - canvasSize.Width) / 2); - } - else - { - canvas.Left = offsetX + 0; - } + canvas.Left = currentClientSize.Width > canvasSize.Width ? offsetX + ((currentClientSize.Width - canvasSize.Width) / 2) : offsetX + 0; - if (currentClientSize.Height > canvasSize.Height) - { - canvas.Top = offsetY + ((currentClientSize.Height - canvasSize.Height) / 2); - } - else - { - canvas.Top = offsetY + 0; - } + canvas.Top = currentClientSize.Height > canvasSize.Height ? offsetY + ((currentClientSize.Height - canvasSize.Height) / 2) : offsetY + 0; } /// diff --git a/src/Greenshot.Editor/Forms/MovableShowColorForm.cs b/src/Greenshot.Editor/Forms/MovableShowColorForm.cs index a07d283e6..7061bd1f7 100644 --- a/src/Greenshot.Editor/Forms/MovableShowColorForm.cs +++ b/src/Greenshot.Editor/Forms/MovableShowColorForm.cs @@ -27,6 +27,7 @@ using Dapplo.Windows.Common.Structs; using Dapplo.Windows.Gdi32; using Dapplo.Windows.Gdi32.SafeHandles; using Dapplo.Windows.User32; +using System.Linq; namespace Greenshot.Editor.Forms { @@ -36,15 +37,9 @@ namespace Greenshot.Editor.Forms /// public partial class MovableShowColorForm : Form { - public Color Color - { - get { return preview.BackColor; } - } + public Color Color => preview.BackColor; - public MovableShowColorForm() - { - InitializeComponent(); - } + public MovableShowColorForm() => InitializeComponent(); /// /// Move the MovableShowColorForm to the specified location and display the color under the (current mouse) coordinates @@ -65,12 +60,11 @@ namespace Greenshot.Editor.Forms var zoomerLocation = new NativePoint(screenCoordinates.X, screenCoordinates.Y) .Offset(cursorSize.Width + 5 - hotspot.X, cursorSize.Height + 5 - hotspot.Y); - - foreach (var displayInfo in DisplayInfo.AllDisplayInfos) + foreach (var (displayInfo, screenRectangle) in from displayInfo in DisplayInfo.AllDisplayInfos + let screenRectangle = displayInfo.Bounds + select (displayInfo, screenRectangle)) { - NativeRect screenRectangle = displayInfo.Bounds; if (!displayInfo.Bounds.Contains(screenCoordinates)) continue; - if (zoomerLocation.X < screenRectangle.X) { zoomerLocation = zoomerLocation.ChangeX(screenRectangle.X); diff --git a/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs b/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs index 5af9f6679..cc7eab831 100644 --- a/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs +++ b/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs @@ -90,31 +90,13 @@ namespace Greenshot.Editor.Forms private void DisplayWidth() { - double displayValue; - if (_valuePercent.Equals(combobox_width.SelectedItem)) - { - displayValue = _newWidth / _effect.Width * 100d; - } - else - { - displayValue = _newWidth; - } - + double displayValue = _valuePercent.Equals(combobox_width.SelectedItem) ? _newWidth / _effect.Width * 100d : _newWidth; textbox_width.Text = ((int)displayValue).ToString(); } private void DisplayHeight() { - double displayValue; - if (_valuePercent.Equals(combobox_height.SelectedItem)) - { - displayValue = _newHeight / _effect.Height * 100d; - } - else - { - displayValue = _newHeight; - } - + double displayValue = _valuePercent.Equals(combobox_height.SelectedItem) ? _newHeight / _effect.Height * 100d : _newHeight; textbox_height.Text = ((int)displayValue).ToString(); } @@ -188,10 +170,7 @@ namespace Greenshot.Editor.Forms } } - private void Textbox_Validating(object sender, System.ComponentModel.CancelEventArgs e) - { - Validate(sender); - } + private void Textbox_Validating(object sender, System.ComponentModel.CancelEventArgs e) => Validate(sender); /// /// diff --git a/src/Greenshot.Editor/Helpers/Colors.cs b/src/Greenshot.Editor/Helpers/Colors.cs index 74ffe9aad..5252abf1e 100644 --- a/src/Greenshot.Editor/Helpers/Colors.cs +++ b/src/Greenshot.Editor/Helpers/Colors.cs @@ -26,10 +26,7 @@ namespace Greenshot.Editor.Helpers { public static class Colors { - public static bool IsVisible(Color c) - { - return c != null && !c.Equals(Color.Empty) && !c.Equals(Color.Transparent) && c.A > 0; - } + public static bool IsVisible(Color c) => c != null && !c.Equals(Color.Empty) && !c.Equals(Color.Transparent) && c.A > 0; public static Color Mix(List colors) { diff --git a/src/Greenshot.Editor/Helpers/GeometryHelper.cs b/src/Greenshot.Editor/Helpers/GeometryHelper.cs index 2c104bfa2..b1e17e695 100644 --- a/src/Greenshot.Editor/Helpers/GeometryHelper.cs +++ b/src/Greenshot.Editor/Helpers/GeometryHelper.cs @@ -56,9 +56,6 @@ namespace Greenshot.Editor.Helpers /// The point on the y-axis of the first point /// The point on the y-axis of the second point /// - public static double Angle2D(int x1, int y1, int x2, int y2) - { - return Math.Atan2(y2 - y1, x2 - x1) * 180 / Math.PI; - } + public static double Angle2D(int x1, int y1, int x2, int y2) => Math.Atan2(y2 - y1, x2 - x1) * 180 / Math.PI; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Helpers/LineAngleRoundBehavior.cs b/src/Greenshot.Editor/Helpers/LineAngleRoundBehavior.cs index 6811f66cf..27b00d698 100644 --- a/src/Greenshot.Editor/Helpers/LineAngleRoundBehavior.cs +++ b/src/Greenshot.Editor/Helpers/LineAngleRoundBehavior.cs @@ -31,9 +31,6 @@ namespace Greenshot.Editor.Helpers { } - public double Process(double angle) - { - return Math.Round(angle / 15) * 15; - } + public double Process(double angle) => Math.Round(angle / 15) * 15; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Helpers/ScaleHelper.cs b/src/Greenshot.Editor/Helpers/ScaleHelper.cs index 567a8c4f1..11be13231 100644 --- a/src/Greenshot.Editor/Helpers/ScaleHelper.cs +++ b/src/Greenshot.Editor/Helpers/ScaleHelper.cs @@ -117,21 +117,18 @@ namespace Greenshot.Editor.Helpers /// Positions with the position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT /// NativePointFloat with coordinates of the used handle/gripper /// NativeRectFloat with the scaled originalRectangle - private static NativeRectFloat Scale(NativeRectFloat originalRectangle, Positions resizeHandlePosition, NativePointFloat resizeHandleCoords) + private static NativeRectFloat Scale(NativeRectFloat originalRectangle, Positions resizeHandlePosition, NativePointFloat resizeHandleCoords) => resizeHandlePosition switch { - return resizeHandlePosition switch - { - Positions.TopLeft => new NativeRectFloat(resizeHandleCoords.X, resizeHandleCoords.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), - Positions.TopCenter => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, originalRectangle.Width, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), - Positions.TopRight => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), - Positions.MiddleLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, originalRectangle.Height), - Positions.MiddleRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Height), - Positions.BottomLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, resizeHandleCoords.Y - originalRectangle.Top), - Positions.BottomCenter => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, originalRectangle.Width, resizeHandleCoords.Y - originalRectangle.Top), - Positions.BottomRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, resizeHandleCoords.Y - originalRectangle.Top), - _ => throw new ArgumentException("Position cannot be handled: " + resizeHandlePosition) - }; - } + Positions.TopLeft => new NativeRectFloat(resizeHandleCoords.X, resizeHandleCoords.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), + Positions.TopCenter => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, originalRectangle.Width, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), + Positions.TopRight => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), + Positions.MiddleLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, originalRectangle.Height), + Positions.MiddleRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Height), + Positions.BottomLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, resizeHandleCoords.Y - originalRectangle.Top), + Positions.BottomCenter => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, originalRectangle.Width, resizeHandleCoords.Y - originalRectangle.Top), + Positions.BottomRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, resizeHandleCoords.Y - originalRectangle.Top), + _ => throw new ArgumentException("Position cannot be handled: " + resizeHandlePosition) + }; /// /// Adjusts resizeHandleCoords so that aspect ratio is kept after resizing a given rectangle with provided arguments. diff --git a/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs b/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs index 7fcd1284d..951805592 100644 --- a/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs +++ b/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs @@ -31,9 +31,6 @@ namespace Greenshot.Editor.Helpers { } - public double Process(double angle) - { - return (Math.Round((angle + 45) / 90) * 90) - 45; - } + public double Process(double angle) => (Math.Round((angle + 45) / 90) * 90) - 45; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs b/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs index 257e362c2..674b1cb99 100644 --- a/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs +++ b/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs @@ -43,28 +43,19 @@ namespace Greenshot.Editor.Helpers /// Enables all of a ToolStrip's children (recursively), /// but not the ToolStrip itself /// - public static void Enable(ToolStrip ts) - { - Endisable(ts, true, PropagationMode.CHILDREN); - } + public static void Enable(ToolStrip ts) => Endisable(ts, true, PropagationMode.CHILDREN); /// /// Disables all of a ToolStrip's children (recursively), /// but not the ToolStrip itself /// - public static void Disable(ToolStrip ts) - { - Endisable(ts, false, PropagationMode.CHILDREN); - } + public static void Disable(ToolStrip ts) => Endisable(ts, false, PropagationMode.CHILDREN); /// /// Enables the ToolStripItem, including children (ToolStripDropDownItem) /// and ancestor (OwnerItem) /// - public static void Enable(ToolStripItem tsi) - { - Endisable(tsi, true, PropagationMode.CHILDREN | PropagationMode.ANCESTORS); - } + public static void Enable(ToolStripItem tsi) => Endisable(tsi, true, PropagationMode.CHILDREN | PropagationMode.ANCESTORS); private static void Endisable(ToolStrip ts, bool enable, PropagationMode mode) { diff --git a/src/Greenshot.Editor/Memento/AddElementMemento.cs b/src/Greenshot.Editor/Memento/AddElementMemento.cs index f9d60b7fb..c7900daea 100644 --- a/src/Greenshot.Editor/Memento/AddElementMemento.cs +++ b/src/Greenshot.Editor/Memento/AddElementMemento.cs @@ -51,10 +51,7 @@ namespace Greenshot.Editor.Memento _surface = null; } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/AddElementsMemento.cs b/src/Greenshot.Editor/Memento/AddElementsMemento.cs index 0b11fac15..4fd810f3c 100644 --- a/src/Greenshot.Editor/Memento/AddElementsMemento.cs +++ b/src/Greenshot.Editor/Memento/AddElementsMemento.cs @@ -38,10 +38,7 @@ namespace Greenshot.Editor.Memento _containerList = containerList; } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { @@ -54,10 +51,7 @@ namespace Greenshot.Editor.Memento _surface = null; } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs b/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs index bf5db52f3..4354a0a0d 100644 --- a/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs +++ b/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs @@ -39,10 +39,7 @@ namespace Greenshot.Editor.Memento _oldValue = fieldToBeChanged.Value; } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { diff --git a/src/Greenshot.Editor/Memento/DeleteElementMemento.cs b/src/Greenshot.Editor/Memento/DeleteElementMemento.cs index 1d744239d..73de769c8 100644 --- a/src/Greenshot.Editor/Memento/DeleteElementMemento.cs +++ b/src/Greenshot.Editor/Memento/DeleteElementMemento.cs @@ -56,10 +56,7 @@ namespace Greenshot.Editor.Memento } } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/DeleteElementsMemento.cs b/src/Greenshot.Editor/Memento/DeleteElementsMemento.cs index 509bbb016..dd242ce0a 100644 --- a/src/Greenshot.Editor/Memento/DeleteElementsMemento.cs +++ b/src/Greenshot.Editor/Memento/DeleteElementsMemento.cs @@ -38,10 +38,7 @@ namespace Greenshot.Editor.Memento _containerList = containerList; } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { @@ -54,10 +51,7 @@ namespace Greenshot.Editor.Memento _surface = null; } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/DrawableContainerBoundsChangeMemento.cs b/src/Greenshot.Editor/Memento/DrawableContainerBoundsChangeMemento.cs index b5b97e4cf..5d7cd2d0b 100644 --- a/src/Greenshot.Editor/Memento/DrawableContainerBoundsChangeMemento.cs +++ b/src/Greenshot.Editor/Memento/DrawableContainerBoundsChangeMemento.cs @@ -61,10 +61,7 @@ namespace Greenshot.Editor.Memento StoreBounds(); } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { diff --git a/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs b/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs index a55c140f4..250ab4dde 100644 --- a/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs +++ b/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs @@ -47,10 +47,7 @@ namespace Greenshot.Editor.Memento } } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { @@ -71,10 +68,7 @@ namespace Greenshot.Editor.Memento _surface = null; } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/TextChangeMemento.cs b/src/Greenshot.Editor/Memento/TextChangeMemento.cs index 71cc9ba99..9441b0a7c 100644 --- a/src/Greenshot.Editor/Memento/TextChangeMemento.cs +++ b/src/Greenshot.Editor/Memento/TextChangeMemento.cs @@ -38,10 +38,7 @@ namespace Greenshot.Editor.Memento _oldText = textContainer.Text; } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { @@ -51,10 +48,7 @@ namespace Greenshot.Editor.Memento } } - public bool Merge(IMemento otherMemento) - { - return otherMemento is TextChangeMemento other && other._textContainer.Equals(_textContainer); - } + public bool Merge(IMemento otherMemento) => otherMemento is TextChangeMemento other && other._textContainer.Equals(_textContainer); public IMemento Restore() { diff --git a/src/Greenshot.Plugin.Box/BoxDestination.cs b/src/Greenshot.Plugin.Box/BoxDestination.cs index 0126fa1e2..e77c52954 100644 --- a/src/Greenshot.Plugin.Box/BoxDestination.cs +++ b/src/Greenshot.Plugin.Box/BoxDestination.cs @@ -30,10 +30,7 @@ namespace Greenshot.Plugin.Box { private readonly BoxPlugin _plugin; - public BoxDestination(BoxPlugin plugin) - { - _plugin = plugin; - } + public BoxDestination(BoxPlugin plugin) => _plugin = plugin; public override string Designation => "Box"; diff --git a/src/Greenshot.Plugin.Box/BoxPlugin.cs b/src/Greenshot.Plugin.Box/BoxPlugin.cs index db8c66bd6..73a2a81b0 100644 --- a/src/Greenshot.Plugin.Box/BoxPlugin.cs +++ b/src/Greenshot.Plugin.Box/BoxPlugin.cs @@ -97,23 +97,14 @@ namespace Greenshot.Plugin.Box } } - public void Shutdown() - { - LOG.Debug("Box Plugin shutdown."); - } + public void Shutdown() => LOG.Debug("Box Plugin shutdown."); /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); - public void ConfigMenuClick(object sender, EventArgs eventArgs) - { - _config.ShowConfigDialog(); - } + public void ConfigMenuClick(object sender, EventArgs eventArgs) => _config.ShowConfigDialog(); /// /// This will be called when the menu item in the Editor is clicked diff --git a/src/Greenshot.Plugin.Confluence/Confluence.cs b/src/Greenshot.Plugin.Confluence/Confluence.cs index 963c3e746..877291724 100644 --- a/src/Greenshot.Plugin.Confluence/Confluence.cs +++ b/src/Greenshot.Plugin.Confluence/Confluence.cs @@ -60,13 +60,10 @@ namespace Greenshot.Plugin.Confluence Logout(); } - if (disposing) + if (disposing && _confluence != null) { - if (_confluence != null) - { - _confluence.Dispose(); - _confluence = null; - } + _confluence.Dispose(); + _confluence = null; } } diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs b/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs index b043b5264..874affa7e 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs @@ -72,40 +72,19 @@ namespace Greenshot.Plugin.Confluence { } - public ConfluenceDestination(Page page) - { - _page = page; - } + public ConfluenceDestination(Page page) => _page = page; - public override string Designation - { - get { return "Confluence"; } - } + public override string Designation => "Confluence"; - public override string Description - { - get - { - return _page == null + public override string Description => _page == null ? Language.GetString("confluence", LangKey.upload_menu_item) : Language.GetString("confluence", LangKey.upload_menu_item) + ": \"" + _page.Title + "\""; - } - } - public override bool IsDynamic - { - get { return true; } - } + public override bool IsDynamic => true; - public override bool IsActive - { - get { return base.IsActive && !string.IsNullOrEmpty(ConfluenceConfig.Url); } - } + public override bool IsActive => base.IsActive && !string.IsNullOrEmpty(ConfluenceConfig.Url); - public override Image DisplayIcon - { - get { return ConfluenceIcon; } - } + public override Image DisplayIcon => ConfluenceIcon; public override IEnumerable DynamicDestinations() { diff --git a/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs b/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs index e3c24ac0a..f62926ca1 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs @@ -64,21 +64,13 @@ namespace Greenshot.Plugin.Confluence { if (_confluenceConnector == null) { - if (_config.Url.Contains("soap-axis")) - { - _confluenceConnector = new ConfluenceConnector(_config.Url, _config.Timeout); - } - else - { - _confluenceConnector = new ConfluenceConnector(_config.Url + ConfluenceConfiguration.DEFAULT_POSTFIX2, _config.Timeout); - } + _confluenceConnector = _config.Url.Contains("soap-axis") + ? new ConfluenceConnector(_config.Url, _config.Timeout) + : new ConfluenceConnector(_config.Url + ConfluenceConfiguration.DEFAULT_POSTFIX2, _config.Timeout); } } - public static ConfluenceConnector ConfluenceConnectorNoLogin - { - get { return _confluenceConnector; } - } + public static ConfluenceConnector ConfluenceConnectorNoLogin => _confluenceConnector; public static ConfluenceConnector ConfluenceConnector { @@ -160,17 +152,14 @@ namespace Greenshot.Plugin.Confluence // copy the new object to the old... clonedConfig.CloneTo(_config); IniConfig.Save(); - if (_confluenceConnector != null) + if (_confluenceConnector != null && !url.Equals(_config.Url)) { - if (!url.Equals(_config.Url)) + if (_confluenceConnector.IsLoggedIn) { - if (_confluenceConnector.IsLoggedIn) - { - _confluenceConnector.Logout(); - } - - _confluenceConnector = null; + _confluenceConnector.Logout(); } + + _confluenceConnector = null; } } } diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs index a2cdd2806..e56140750 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs @@ -89,49 +89,45 @@ namespace Greenshot.Plugin.Confluence } MatchCollection spacePageMatch = spacePageRegex.Matches(url); - if (spacePageMatch?.Count > 0) + if (spacePageMatch?.Count > 0 && spacePageMatch[0].Groups.Count >= 2) { - if (spacePageMatch[0].Groups.Count >= 2) + string space = spacePageMatch[0].Groups[1].Value; + string title = spacePageMatch[0].Groups[2].Value; + if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(space)) { - string space = spacePageMatch[0].Groups[1].Value; - string title = spacePageMatch[0].Groups[2].Value; - if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(space)) + continue; + } + + if (title.EndsWith("#")) + { + title = title.Substring(0, title.Length - 1); + } + + try + { + bool pageDouble = false; + foreach (var _ in from Page page in pages + where page.Title.Equals(title) + select new { }) { - continue; + LOG.DebugFormat("Skipping double page with title {0}", title); + pageDouble = true; + break; } - if (title.EndsWith("#")) + if (!pageDouble) { - title = title.Substring(0, title.Length - 1); - } - - try - { - bool pageDouble = false; - foreach (Page page in pages) - { - if (page.Title.Equals(title)) - { - LOG.DebugFormat("Skipping double page with title {0}", title); - pageDouble = true; - break; - } - } - - if (!pageDouble) - { - Page page = ConfluencePlugin.ConfluenceConnector.GetPage(space, title); - LOG.DebugFormat("Adding page {0}", page.Title); - pages.Add(page); - } - } - catch (Exception ex) - { - // Preventing security problems - LOG.DebugFormat("Couldn't get page details for space {0} / title {1}", space, title); - LOG.Warn(ex); + Page page = ConfluencePlugin.ConfluenceConnector.GetPage(space, title); + LOG.DebugFormat("Adding page {0}", page.Title); + pages.Add(page); } } + catch (Exception ex) + { + // Preventing security problems + LOG.DebugFormat("Couldn't get page details for space {0} / title {1}", space, title); + LOG.Warn(ex); + } } } diff --git a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs index 2381c0d23..f29402c1d 100644 --- a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs +++ b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs @@ -101,14 +101,8 @@ namespace Greenshot.Plugin.Confluence return dka.Value; } - object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return _displayValues[value]; - } + object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) => _displayValues[value]; - object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - return _reverseValues[value]; - } + object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => _reverseValues[value]; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs index f8cfa6475..257816e64 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs @@ -37,9 +37,6 @@ namespace Greenshot.Plugin.Confluence.Forms InitializeComponent(); } - private void Button_OK_Click(object sender, RoutedEventArgs e) - { - DialogResult = true; - } + private void Button_OK_Click(object sender, RoutedEventArgs e) => DialogResult = true; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs index 0f48dbe5a..bdac51569 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs @@ -38,10 +38,7 @@ namespace Greenshot.Plugin.Confluence.Forms InitializeComponent(); } - private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) - { - SelectionChanged(); - } + private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) => SelectionChanged(); private void SelectionChanged() { @@ -57,9 +54,6 @@ namespace Greenshot.Plugin.Confluence.Forms } } - private void Page_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - SelectionChanged(); - } + private void Page_Loaded(object sender, System.Windows.RoutedEventArgs e) => SelectionChanged(); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs index e473fd8ef..64d2ff1be 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs @@ -42,43 +42,30 @@ namespace Greenshot.Plugin.Confluence.Forms _confluenceUpload = confluenceUpload; DataContext = this; InitializeComponent(); - if (ConfluenceConfig.SearchSpaceKey == null) + switch (ConfluenceConfig.SearchSpaceKey) { - SpaceComboBox.SelectedItem = Spaces.FirstOrDefault(); - } - else - { - foreach (var space in Spaces) - { - if (space.Key.Equals(ConfluenceConfig.SearchSpaceKey)) + case null: + SpaceComboBox.SelectedItem = Spaces.FirstOrDefault(); + break; + default: { - SpaceComboBox.SelectedItem = space; + foreach (var space in from space in Spaces + where space.Key.Equals(ConfluenceConfig.SearchSpaceKey) + select space) + { + SpaceComboBox.SelectedItem = space; + } + + break; } - } } } - private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) - { - SelectionChanged(); - } + private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) => SelectionChanged(); - private void SelectionChanged() - { - if (PageListView.HasItems && PageListView.SelectedItems.Count > 0) - { - _confluenceUpload.SelectedPage = (Page)PageListView.SelectedItem; - } - else - { - _confluenceUpload.SelectedPage = null; - } - } + private void SelectionChanged() => _confluenceUpload.SelectedPage = PageListView.HasItems && PageListView.SelectedItems.Count > 0 ? (Page)PageListView.SelectedItem : null; - private void Search_Click(object sender, RoutedEventArgs e) - { - DoSearch(); - } + private void Search_Click(object sender, RoutedEventArgs e) => DoSearch(); private void DoSearch() { @@ -100,14 +87,8 @@ namespace Greenshot.Plugin.Confluence.Forms } } - private void Page_Loaded(object sender, RoutedEventArgs e) - { - SelectionChanged(); - } + private void Page_Loaded(object sender, RoutedEventArgs e) => SelectionChanged(); - private void SearchText_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) - { - Search.IsEnabled = !string.IsNullOrEmpty(searchText.Text); - } + private void SearchText_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) => Search.IsEnabled = !string.IsNullOrEmpty(searchText.Text); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs index be002b301..2f2a9d21b 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs @@ -54,17 +54,11 @@ namespace Greenshot.Plugin.Confluence.Forms private System.Windows.Controls.Page _searchPage; - public System.Windows.Controls.Page SearchPage - { - get { return _searchPage ??= new ConfluenceSearch(this); } - } + public System.Windows.Controls.Page SearchPage => _searchPage ??= new ConfluenceSearch(this); private System.Windows.Controls.Page _browsePage; - public System.Windows.Controls.Page BrowsePage - { - get { return _browsePage ??= new ConfluenceTreePicker(this); } - } + public System.Windows.Controls.Page BrowsePage => _browsePage ??= new ConfluenceTreePicker(this); private Page _selectedPage; @@ -135,9 +129,6 @@ namespace Greenshot.Plugin.Confluence.Forms } } - private void Upload_Click(object sender, RoutedEventArgs e) - { - DialogResult = true; - } + private void Upload_Click(object sender, RoutedEventArgs e) => DialogResult = true; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs b/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs index 29568023f..e86216624 100644 --- a/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs +++ b/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs @@ -5,20 +5,11 @@ namespace Greenshot.Plugin.Confluence.Support { public class LanguageChangedEventManager : WeakEventManager { - public static void AddListener(TranslationManager source, IWeakEventListener listener) - { - CurrentManager.ProtectedAddListener(source, listener); - } + public static void AddListener(TranslationManager source, IWeakEventListener listener) => CurrentManager.ProtectedAddListener(source, listener); - public static void RemoveListener(TranslationManager source, IWeakEventListener listener) - { - CurrentManager.ProtectedRemoveListener(source, listener); - } + public static void RemoveListener(TranslationManager source, IWeakEventListener listener) => CurrentManager.ProtectedRemoveListener(source, listener); - private void OnLanguageChanged(object sender, EventArgs e) - { - DeliverEvent(sender, e); - } + private void OnLanguageChanged(object sender, EventArgs e) => DeliverEvent(sender, e); protected override void StartListening(object source) { diff --git a/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs b/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs index 330ae6b83..883624b6f 100644 --- a/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs +++ b/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs @@ -10,9 +10,6 @@ namespace Greenshot.Plugin.Confluence.Support /// /// See /// - public object Translate(string key) - { - return Language.HasKey("confluence", key) ? Language.GetString("confluence", key) : (object)key; - } + public object Translate(string key) => Language.HasKey("confluence", key) ? Language.GetString("confluence", key) : (object)key; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs b/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs index 6472e23a9..e0a4c4ec5 100644 --- a/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs +++ b/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs @@ -14,10 +14,7 @@ namespace Greenshot.Plugin.Confluence.Support /// Initializes a new instance of the class. /// /// The key. - public TranslateExtension(string key) - { - Key = key; - } + public TranslateExtension(string key) => Key = key; [ConstructorArgument("key")] public string Key { get; set; } diff --git a/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs b/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs index 0ebce8300..31e95cda8 100644 --- a/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs +++ b/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs @@ -40,10 +40,7 @@ namespace Greenshot.Plugin.Confluence.Support return false; } - private void OnLanguageChanged(object sender, EventArgs e) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); - } + private void OnLanguageChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); public event PropertyChangedEventHandler PropertyChanged; } diff --git a/src/Greenshot.Plugin.Confluence/Web References/confluence/Reference.cs b/src/Greenshot.Plugin.Confluence/Web References/confluence/Reference.cs index aba156d27..5127f796c 100644 --- a/src/Greenshot.Plugin.Confluence/Web References/confluence/Reference.cs +++ b/src/Greenshot.Plugin.Confluence/Web References/confluence/Reference.cs @@ -68,30 +68,31 @@ namespace GreenshotConfluencePlugin.confluence { } } - public new string Url { - get { - return base.Url; - } - set { - if ((((this.IsLocalFileSystemWebService(base.Url) == true) - && (this.useDefaultCredentialsSetExplicitly == false)) - && (this.IsLocalFileSystemWebService(value) == false))) { + public new string Url + { + get => base.Url; + set + { + if ((((this.IsLocalFileSystemWebService(base.Url) == true) + && (this.useDefaultCredentialsSetExplicitly == false)) + && (this.IsLocalFileSystemWebService(value) == false))) + { base.UseDefaultCredentials = false; } base.Url = value; } } - - public new bool UseDefaultCredentials { - get { - return base.UseDefaultCredentials; - } - set { + + public new bool UseDefaultCredentials + { + get => base.UseDefaultCredentials; + set + { base.UseDefaultCredentials = value; this.useDefaultCredentialsSetExplicitly = true; } } - + /// public event searchCompletedEventHandler searchCompleted; @@ -135,12 +136,10 @@ namespace GreenshotConfluencePlugin.confluence { in2}); return ((RemoteSearchResult[])(results[0])); } - + /// - public void searchAsync(string in0, string in1, int in2) { - this.searchAsync(in0, in1, in2, null); - } - + public void searchAsync(string in0, string in1, int in2) => this.searchAsync(in0, in1, in2, null); + /// public void searchAsync(string in0, string in1, int in2, object userState) { if ((this.searchOperationCompleted == null)) { @@ -168,12 +167,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((RemoteSpace)(results[0])); } - + /// - public void getSpaceAsync(string in0, string in1) { - this.getSpaceAsync(in0, in1, null); - } - + public void getSpaceAsync(string in0, string in1) => this.getSpaceAsync(in0, in1, null); + /// public void getSpaceAsync(string in0, string in1, object userState) { if ((this.getSpaceOperationCompleted == null)) { @@ -200,12 +197,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((RemotePageSummary[])(results[0])); } - + /// - public void getChildrenAsync(string in0, long in1) { - this.getChildrenAsync(in0, in1, null); - } - + public void getChildrenAsync(string in0, long in1) => this.getChildrenAsync(in0, in1, null); + /// public void getChildrenAsync(string in0, long in1, object userState) { if ((this.getChildrenOperationCompleted == null)) { @@ -232,12 +227,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((string)(results[0])); } - + /// - public void loginAsync(string in0, string in1) { - this.loginAsync(in0, in1, null); - } - + public void loginAsync(string in0, string in1) => this.loginAsync(in0, in1, null); + /// public void loginAsync(string in0, string in1, object userState) { if ((this.loginOperationCompleted == null)) { @@ -265,12 +258,10 @@ namespace GreenshotConfluencePlugin.confluence { in2}); return ((RemotePage)(results[0])); } - + /// - public void getPageAsync(string in0, string in1, string in2) { - this.getPageAsync(in0, in1, in2, null); - } - + public void getPageAsync(string in0, string in1, string in2) => this.getPageAsync(in0, in1, in2, null); + /// public void getPageAsync(string in0, string in1, string in2, object userState) { if ((this.getPageOperationCompleted == null)) { @@ -299,12 +290,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((RemotePage)(results[0])); } - + /// - public void getPage1Async(string in0, long in1) { - this.getPage1Async(in0, in1, null); - } - + public void getPage1Async(string in0, long in1) => this.getPage1Async(in0, in1, null); + /// public void getPage1Async(string in0, long in1, object userState) { if ((this.getPage1OperationCompleted == null)) { @@ -330,12 +319,10 @@ namespace GreenshotConfluencePlugin.confluence { in0}); return ((bool)(results[0])); } - + /// - public void logoutAsync(string in0) { - this.logoutAsync(in0, null); - } - + public void logoutAsync(string in0) => this.logoutAsync(in0, null); + /// public void logoutAsync(string in0, object userState) { if ((this.logoutOperationCompleted == null)) { @@ -363,12 +350,10 @@ namespace GreenshotConfluencePlugin.confluence { in3}); return ((RemoteAttachment)(results[0])); } - + /// - public void addAttachmentAsync(string in0, long in1, RemoteAttachment in2, byte[] in3) { - this.addAttachmentAsync(in0, in1, in2, in3, null); - } - + public void addAttachmentAsync(string in0, long in1, RemoteAttachment in2, byte[] in3) => this.addAttachmentAsync(in0, in1, in2, in3, null); + /// public void addAttachmentAsync(string in0, long in1, RemoteAttachment in2, byte[] in3, object userState) { if ((this.addAttachmentOperationCompleted == null)) { @@ -399,12 +384,10 @@ namespace GreenshotConfluencePlugin.confluence { in2}); return ((RemoteAttachment)(results[0])); } - + /// - public void addAttachment1Async(string in0, RemoteAttachment in1, byte[] in2) { - this.addAttachment1Async(in0, in1, in2, null); - } - + public void addAttachment1Async(string in0, RemoteAttachment in1, byte[] in2) => this.addAttachment1Async(in0, in1, in2, null); + /// public void addAttachment1Async(string in0, RemoteAttachment in1, byte[] in2, object userState) { if ((this.addAttachment1OperationCompleted == null)) { @@ -431,12 +414,10 @@ namespace GreenshotConfluencePlugin.confluence { in0}); return ((RemoteSpaceSummary[])(results[0])); } - + /// - public void getSpacesAsync(string in0) { - this.getSpacesAsync(in0, null); - } - + public void getSpacesAsync(string in0) => this.getSpacesAsync(in0, null); + /// public void getSpacesAsync(string in0, object userState) { if ((this.getSpacesOperationCompleted == null)) { @@ -462,12 +443,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((RemotePageSummary[])(results[0])); } - + /// - public void getPagesAsync(string in0, string in1) { - this.getPagesAsync(in0, in1, null); - } - + public void getPagesAsync(string in0, string in1) => this.getPagesAsync(in0, in1, null); + /// public void getPagesAsync(string in0, string in1, object userState) { if ((this.getPagesOperationCompleted == null)) { @@ -484,12 +463,10 @@ namespace GreenshotConfluencePlugin.confluence { this.getPagesCompleted(this, new getPagesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } - + /// - public new void CancelAsync(object userState) { - base.CancelAsync(userState); - } - + public new void CancelAsync(object userState) => base.CancelAsync(userState); + private bool IsLocalFileSystemWebService(string url) { if (((url == null) || (url == string.Empty))) { @@ -525,55 +502,35 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string excerpt { - get { - return this.excerptField; - } - set { - this.excerptField = value; - } + get => this.excerptField; + set => this.excerptField = value; } - + /// public long id { - get { - return this.idField; - } - set { - this.idField = value; - } + get => this.idField; + set => this.idField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string title { - get { - return this.titleField; - } - set { - this.titleField = value; - } + get => this.titleField; + set => this.titleField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string type { - get { - return this.typeField; - } - set { - this.typeField = value; - } + get => this.typeField; + set => this.typeField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string url { - get { - return this.urlField; - } - set { - this.urlField = value; - } + get => this.urlField; + set => this.urlField = value; } } @@ -608,108 +565,68 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string comment { - get { - return this.commentField; - } - set { - this.commentField = value; - } + get => this.commentField; + set => this.commentField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string contentType { - get { - return this.contentTypeField; - } - set { - this.contentTypeField = value; - } + get => this.contentTypeField; + set => this.contentTypeField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public System.Nullable created { - get { - return this.createdField; - } - set { - this.createdField = value; - } + get => this.createdField; + set => this.createdField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string creator { - get { - return this.creatorField; - } - set { - this.creatorField = value; - } + get => this.creatorField; + set => this.creatorField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string fileName { - get { - return this.fileNameField; - } - set { - this.fileNameField = value; - } + get => this.fileNameField; + set => this.fileNameField = value; } - + /// public long fileSize { - get { - return this.fileSizeField; - } - set { - this.fileSizeField = value; - } + get => this.fileSizeField; + set => this.fileSizeField = value; } - + /// public long id { - get { - return this.idField; - } - set { - this.idField = value; - } + get => this.idField; + set => this.idField = value; } - + /// public long pageId { - get { - return this.pageIdField; - } - set { - this.pageIdField = value; - } + get => this.pageIdField; + set => this.pageIdField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string title { - get { - return this.titleField; - } - set { - this.titleField = value; - } + get => this.titleField; + set => this.titleField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string url { - get { - return this.urlField; - } - set { - this.urlField = value; - } + get => this.urlField; + set => this.urlField = value; } } @@ -735,55 +652,35 @@ namespace GreenshotConfluencePlugin.confluence { /// public long id { - get { - return this.idField; - } - set { - this.idField = value; - } + get => this.idField; + set => this.idField = value; } - + /// public int permissions { - get { - return this.permissionsField; - } - set { - this.permissionsField = value; - } + get => this.permissionsField; + set => this.permissionsField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string space { - get { - return this.spaceField; - } - set { - this.spaceField = value; - } + get => this.spaceField; + set => this.spaceField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string title { - get { - return this.titleField; - } - set { - this.titleField = value; - } + get => this.titleField; + set => this.titleField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string url { - get { - return this.urlField; - } - set { - this.urlField = value; - } + get => this.urlField; + set => this.urlField = value; } } @@ -800,12 +697,8 @@ namespace GreenshotConfluencePlugin.confluence { /// public long parentId { - get { - return this.parentIdField; - } - set { - this.parentIdField = value; - } + get => this.parentIdField; + set => this.parentIdField = value; } } @@ -838,97 +731,61 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string content { - get { - return this.contentField; - } - set { - this.contentField = value; - } + get => this.contentField; + set => this.contentField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string contentStatus { - get { - return this.contentStatusField; - } - set { - this.contentStatusField = value; - } + get => this.contentStatusField; + set => this.contentStatusField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public System.Nullable created { - get { - return this.createdField; - } - set { - this.createdField = value; - } + get => this.createdField; + set => this.createdField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string creator { - get { - return this.creatorField; - } - set { - this.creatorField = value; - } + get => this.creatorField; + set => this.creatorField = value; } - + /// public bool current { - get { - return this.currentField; - } - set { - this.currentField = value; - } + get => this.currentField; + set => this.currentField = value; } - + /// public bool homePage { - get { - return this.homePageField; - } - set { - this.homePageField = value; - } + get => this.homePageField; + set => this.homePageField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public System.Nullable modified { - get { - return this.modifiedField; - } - set { - this.modifiedField = value; - } + get => this.modifiedField; + set => this.modifiedField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string modifier { - get { - return this.modifierField; - } - set { - this.modifierField = value; - } + get => this.modifierField; + set => this.modifierField = value; } - + /// public int version { - get { - return this.versionField; - } - set { - this.versionField = value; - } + get => this.versionField; + set => this.versionField = value; } } @@ -952,45 +809,29 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string key { - get { - return this.keyField; - } - set { - this.keyField = value; - } + get => this.keyField; + set => this.keyField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string name { - get { - return this.nameField; - } - set { - this.nameField = value; - } + get => this.nameField; + set => this.nameField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string type { - get { - return this.typeField; - } - set { - this.typeField = value; - } + get => this.typeField; + set => this.typeField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string url { - get { - return this.urlField; - } - set { - this.urlField = value; - } + get => this.urlField; + set => this.urlField = value; } } @@ -1011,33 +852,21 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string description { - get { - return this.descriptionField; - } - set { - this.descriptionField = value; - } + get => this.descriptionField; + set => this.descriptionField = value; } - + /// public long homePage { - get { - return this.homePageField; - } - set { - this.homePageField = value; - } + get => this.homePageField; + set => this.homePageField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string spaceGroup { - get { - return this.spaceGroupField; - } - set { - this.spaceGroupField = value; - } + get => this.spaceGroupField; + set => this.spaceGroupField = value; } } @@ -1052,12 +881,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class searchCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal searchCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal searchCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteSearchResult[] Result { get { @@ -1078,12 +905,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getSpaceCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getSpaceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getSpaceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteSpace Result { get { @@ -1104,12 +929,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getChildrenCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getChildrenCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getChildrenCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemotePageSummary[] Result { get { @@ -1130,12 +953,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class loginCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal loginCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal loginCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public string Result { get { @@ -1156,12 +977,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getPageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getPageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getPageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemotePage Result { get { @@ -1182,12 +1001,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getPage1CompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getPage1CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getPage1CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemotePage Result { get { @@ -1208,12 +1025,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class logoutCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal logoutCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal logoutCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public bool Result { get { @@ -1234,12 +1049,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class addAttachmentCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal addAttachmentCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal addAttachmentCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteAttachment Result { get { @@ -1260,12 +1073,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class addAttachment1CompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal addAttachment1CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal addAttachment1CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteAttachment Result { get { @@ -1286,12 +1097,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getSpacesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getSpacesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getSpacesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteSpaceSummary[] Result { get { @@ -1312,12 +1121,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getPagesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getPagesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getPagesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemotePageSummary[] Result { get { diff --git a/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs b/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs index 00f103cfe..3733c726e 100644 --- a/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs +++ b/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs @@ -33,10 +33,7 @@ namespace Greenshot.Plugin.Dropbox private readonly DropboxPlugin _plugin; - public DropboxDestination(DropboxPlugin plugin) - { - _plugin = plugin; - } + public DropboxDestination(DropboxPlugin plugin) => _plugin = plugin; public override string Designation => "Dropbox"; diff --git a/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs b/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs index ab32b5162..2e89183e0 100644 --- a/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs +++ b/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs @@ -94,23 +94,14 @@ namespace Greenshot.Plugin.Dropbox } } - public void Shutdown() - { - Log.Debug("Dropbox Plugin shutdown."); - } + public void Shutdown() => Log.Debug("Dropbox Plugin shutdown."); /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); - public void ConfigMenuClick(object sender, EventArgs eventArgs) - { - _config.ShowConfigDialog(); - } + public void ConfigMenuClick(object sender, EventArgs eventArgs) => _config.ShowConfigDialog(); /// /// This will be called when the menu item in the Editor is clicked diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs index b3d471a8f..17dca597c 100644 --- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs +++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs @@ -121,12 +121,9 @@ namespace Greenshot.Plugin.ExternalCommand Commandline.Remove(command); Argument.Remove(command); RunInbackground.Remove(command); - if (MsPaint.Equals(command) || PaintDotNet.Equals(command)) + if ((MsPaint.Equals(command) || PaintDotNet.Equals(command)) && !DeletedBuildInCommands.Contains(command)) { - if (!DeletedBuildInCommands.Contains(command)) - { - DeletedBuildInCommands.Add(command); - } + DeletedBuildInCommands.Add(command); } } @@ -161,7 +158,7 @@ namespace Greenshot.Plugin.ExternalCommand public override object GetDefault(string property) => property switch { - nameof(DeletedBuildInCommands) => (object)new List(), + nameof(DeletedBuildInCommands) => new List(), nameof(Commands) => new List(), nameof(Commandline) => new Dictionary(), nameof(Argument) => new Dictionary(), diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs index 9f57bca33..18170203d 100644 --- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs +++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs @@ -47,10 +47,7 @@ namespace Greenshot.Plugin.ExternalCommand private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection(); private readonly string _presetCommand; - public ExternalCommandDestination(string commando) - { - _presetCommand = commando; - } + public ExternalCommandDestination(string commando) => _presetCommand = commando; public override string Designation => "External " + _presetCommand.Replace(',', '_'); @@ -83,7 +80,7 @@ namespace Greenshot.Plugin.ExternalCommand string error; if (runInBackground) { - Thread commandThread = new(delegate () + Thread commandThread = new(() => { CallExternalCommand(exportInformation, fullPath, out output, out error); ProcessExport(exportInformation, surface); @@ -264,9 +261,6 @@ namespace Greenshot.Plugin.ExternalCommand return -1; } - public static string FormatArguments(string arguments, string fullpath) - { - return string.Format(arguments, fullpath); - } + public static string FormatArguments(string arguments, string fullpath) => string.Format(arguments, fullpath); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs index 7f576ccdd..236067a63 100644 --- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs +++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs @@ -181,15 +181,9 @@ namespace Greenshot.Plugin.ExternalCommand } } - public virtual void Shutdown() - { - Log.Debug("Shutdown"); - } + public virtual void Shutdown() => Log.Debug("Shutdown"); - private void ConfigMenuClick(object sender, EventArgs eventArgs) - { - Configure(); - } + private void ConfigMenuClick(object sender, EventArgs eventArgs) => Configure(); /// /// Implementation of the IPlugin.Configure diff --git a/src/Greenshot.Plugin.ExternalCommand/IconCache.cs b/src/Greenshot.Plugin.ExternalCommand/IconCache.cs index 0de573a43..39c38cd90 100644 --- a/src/Greenshot.Plugin.ExternalCommand/IconCache.cs +++ b/src/Greenshot.Plugin.ExternalCommand/IconCache.cs @@ -35,18 +35,15 @@ namespace Greenshot.Plugin.ExternalCommand public static Image IconForCommand(string commandName) { Image icon = null; - if (commandName != null) + if (commandName != null && config.Commandline.ContainsKey(commandName) && File.Exists(config.Commandline[commandName])) { - if (config.Commandline.ContainsKey(commandName) && File.Exists(config.Commandline[commandName])) + try { - try - { - icon = PluginUtils.GetCachedExeIcon(config.Commandline[commandName], 0); - } - catch (Exception ex) - { - LOG.Warn("Problem loading icon for " + config.Commandline[commandName], ex); - } + icon = PluginUtils.GetCachedExeIcon(config.Commandline[commandName], 0); + } + catch (Exception ex) + { + LOG.Warn("Problem loading icon for " + config.Commandline[commandName], ex); } } diff --git a/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs b/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs index 992fff3f5..0d680b572 100644 --- a/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs +++ b/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs @@ -44,10 +44,7 @@ namespace Greenshot.Plugin.ExternalCommand UpdateView(); } - private void ButtonOkClick(object sender, EventArgs e) - { - IniConfig.Save(); - } + private void ButtonOkClick(object sender, EventArgs e) => IniConfig.Save(); private void ButtonAddClick(object sender, EventArgs e) { @@ -101,15 +98,9 @@ namespace Greenshot.Plugin.ExternalCommand button_edit.Enabled = listView1.SelectedItems.Count > 0; } - private void ListView1ItemSelectionChanged(object sender, EventArgs e) - { - button_edit.Enabled = listView1.SelectedItems.Count > 0; - } + private void ListView1ItemSelectionChanged(object sender, EventArgs e) => button_edit.Enabled = listView1.SelectedItems.Count > 0; - private void ButtonEditClick(object sender, EventArgs e) - { - ListView1DoubleClick(sender, e); - } + private void ButtonEditClick(object sender, EventArgs e) => ListView1DoubleClick(sender, e); private void ListView1DoubleClick(object sender, EventArgs e) { diff --git a/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs b/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs index 95ebffb0d..769a55322 100644 --- a/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs +++ b/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs @@ -174,19 +174,10 @@ namespace Greenshot.Plugin.ExternalCommand } } - private void textBox_name_TextChanged(object sender, EventArgs e) - { - OkButtonState(); - } + private void textBox_name_TextChanged(object sender, EventArgs e) => OkButtonState(); - private void textBox_commandline_TextChanged(object sender, EventArgs e) - { - OkButtonState(); - } + private void textBox_commandline_TextChanged(object sender, EventArgs e) => OkButtonState(); - private void textBox_arguments_TextChanged(object sender, EventArgs e) - { - OkButtonState(); - } + private void textBox_arguments_TextChanged(object sender, EventArgs e) => OkButtonState(); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Flickr/FlickrDestination.cs b/src/Greenshot.Plugin.Flickr/FlickrDestination.cs index e1b2ed5e6..c40a8b203 100644 --- a/src/Greenshot.Plugin.Flickr/FlickrDestination.cs +++ b/src/Greenshot.Plugin.Flickr/FlickrDestination.cs @@ -30,10 +30,7 @@ namespace Greenshot.Plugin.Flickr { private readonly FlickrPlugin _plugin; - public FlickrDestination(FlickrPlugin plugin) - { - _plugin = plugin; - } + public FlickrDestination(FlickrPlugin plugin) => _plugin = plugin; public override string Designation => "Flickr"; diff --git a/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs b/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs index 597f00042..9ef671707 100644 --- a/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs +++ b/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs @@ -104,23 +104,14 @@ namespace Greenshot.Plugin.Flickr } } - public void Shutdown() - { - Log.Debug("Flickr Plugin shutdown."); - } + public void Shutdown() => Log.Debug("Flickr Plugin shutdown."); /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); - public void ConfigMenuClick(object sender, EventArgs eventArgs) - { - _config.ShowConfigDialog(); - } + public void ConfigMenuClick(object sender, EventArgs eventArgs) => _config.ShowConfigDialog(); public bool Upload(ICaptureDetails captureDetails, ISurface surface, out string uploadUrl) { diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs index 217e365d0..58de9ebd0 100644 --- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs +++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs @@ -29,10 +29,7 @@ namespace Greenshot.Plugin.GooglePhotos { private readonly GooglePhotosPlugin _plugin; - public GooglePhotosDestination(GooglePhotosPlugin plugin) - { - _plugin = plugin; - } + public GooglePhotosDestination(GooglePhotosPlugin plugin) => _plugin = plugin; public override string Designation => "GooglePhotos"; diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs index d0acc8c73..7121f51a8 100644 --- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs +++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs @@ -105,15 +105,9 @@ namespace Greenshot.Plugin.GooglePhotos /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); - public void ConfigMenuClick(object sender, EventArgs eventArgs) - { - Configure(); - } + public void ConfigMenuClick(object sender, EventArgs eventArgs) => Configure(); public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) { diff --git a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs index f0119183c..3a90b2a60 100644 --- a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs +++ b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs @@ -218,10 +218,7 @@ namespace Greenshot.Plugin.Imgur.Forms } } - private void FinishedButtonClick(object sender, EventArgs e) - { - Hide(); - } + private void FinishedButtonClick(object sender, EventArgs e) => Hide(); private void OpenButtonClick(object sender, EventArgs e) { @@ -254,9 +251,6 @@ namespace Greenshot.Plugin.Imgur.Forms listview_imgur_uploads.Sort(); } - private void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e) - { - _instance = null; - } + private void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e) => _instance = null; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs b/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs index 8bbf3bac5..aa48e49b9 100644 --- a/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs +++ b/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs @@ -40,9 +40,6 @@ namespace Greenshot.Plugin.Imgur.Forms historyButton.Enabled = ImgurUtils.IsHistoryLoadingNeeded(); } - private void ButtonHistoryClick(object sender, EventArgs e) - { - ImgurHistory.ShowHistory(); - } + private void ButtonHistoryClick(object sender, EventArgs e) => ImgurHistory.ShowHistory(); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Imgur/ImgurDestination.cs b/src/Greenshot.Plugin.Imgur/ImgurDestination.cs index c6be4d20e..21d3d97d7 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurDestination.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurDestination.cs @@ -33,10 +33,7 @@ namespace Greenshot.Plugin.Imgur { private readonly ImgurPlugin _plugin; - public ImgurDestination(ImgurPlugin plugin) - { - _plugin = plugin; - } + public ImgurDestination(ImgurPlugin plugin) => _plugin = plugin; public override string Designation => "Imgur"; diff --git a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs index 438ae8638..49eefced1 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs @@ -148,14 +148,11 @@ namespace Greenshot.Plugin.Imgur } nodes = doc.GetElementsByTagName("datetime"); - if (nodes.Count > 0) + // Version 3 has seconds since Epoch + if (nodes.Count > 0 && double.TryParse(nodes.Item(0)?.InnerText, out var secondsSince)) { - // Version 3 has seconds since Epoch - if (double.TryParse(nodes.Item(0)?.InnerText, out var secondsSince)) - { - var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); - imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime; - } + var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); + imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime; } nodes = doc.GetElementsByTagName("original"); diff --git a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs index 11befa5ef..1d9aa9995 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs @@ -146,14 +146,7 @@ namespace Greenshot.Plugin.Imgur return; } - if (_config?.ImgurUploadHistory != null && _config.ImgurUploadHistory.Count > 0) - { - historyMenuItem.Enabled = true; - } - else - { - historyMenuItem.Enabled = false; - } + historyMenuItem.Enabled = _config?.ImgurUploadHistory != null && _config.ImgurUploadHistory.Count > 0; }); } catch (Exception ex) @@ -171,10 +164,7 @@ namespace Greenshot.Plugin.Imgur /// /// Implementation of the IPlugin.Configure /// - public virtual void Configure() - { - _config.ShowConfigDialog(); - } + public virtual void Configure() => _config.ShowConfigDialog(); /// /// Upload the capture to imgur @@ -216,14 +206,7 @@ namespace Greenshot.Plugin.Imgur IniConfig.Save(); - if (_config.UsePageLink) - { - uploadUrl = imgurInfo.Page; - } - else - { - uploadUrl = imgurInfo.Original; - } + uploadUrl = _config.UsePageLink ? imgurInfo.Page : imgurInfo.Original; if (!string.IsNullOrEmpty(uploadUrl) && _config.CopyLinkToClipboard) { diff --git a/src/Greenshot.Plugin.Imgur/ImgurUtils.cs b/src/Greenshot.Plugin.Imgur/ImgurUtils.cs index 56da1c39e..2ba81ea53 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurUtils.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurUtils.cs @@ -135,10 +135,7 @@ namespace Greenshot.Plugin.Imgur /// Use this to make sure Imgur knows from where the upload comes. /// /// - private static void SetClientId(HttpWebRequest webRequest) - { - webRequest.Headers.Add("Authorization", "Client-ID " + ImgurCredentials.CONSUMER_KEY); - } + private static void SetClientId(HttpWebRequest webRequest) => webRequest.Headers.Add("Authorization", "Client-ID " + ImgurCredentials.CONSUMER_KEY); /// /// Do the actual upload to Imgur @@ -292,12 +289,9 @@ namespace Greenshot.Plugin.Imgur } catch (WebException wE) { - if (wE.Status == WebExceptionStatus.ProtocolError) + if (wE.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)wE.Response).StatusCode == HttpStatusCode.NotFound) { - if (((HttpWebResponse)wE.Response).StatusCode == HttpStatusCode.NotFound) - { - return null; - } + return null; } throw; @@ -345,12 +339,9 @@ namespace Greenshot.Plugin.Imgur catch (WebException wE) { // Allow "Bad request" this means we already deleted it - if (wE.Status == WebExceptionStatus.ProtocolError) + if (wE.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)wE.Response).StatusCode != HttpStatusCode.BadRequest) { - if (((HttpWebResponse)wE.Response).StatusCode != HttpStatusCode.BadRequest) - { - throw; - } + throw; } } diff --git a/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs b/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs index 3cb3f78d8..a7386f41d 100644 --- a/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs +++ b/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs @@ -74,10 +74,7 @@ namespace Greenshot.Plugin.Jira /// /// TKey /// string - protected virtual string CreateKey(TKey keyObject) - { - return keyObject.ToString(); - } + protected virtual string CreateKey(TKey keyObject) => keyObject.ToString(); /// /// Get a task element from the cache, if this is not available call the create function. @@ -183,9 +180,6 @@ namespace Greenshot.Plugin.Jira /// ActivateUpdateCallback / ActivateRemovedCallback /// /// CacheEntryUpdateArguments - protected void UpdateCallback(CacheEntryUpdateArguments cacheEntryUpdateArguments) - { - _log.Verbose().WriteLine("Update request for {0} due to {1}.", cacheEntryUpdateArguments.Key, cacheEntryUpdateArguments.RemovedReason); - } + protected void UpdateCallback(CacheEntryUpdateArguments cacheEntryUpdateArguments) => _log.Verbose().WriteLine("Update request for {0} due to {1}.", cacheEntryUpdateArguments.Key, cacheEntryUpdateArguments.RemovedReason); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs b/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs index a7c9b87c1..49e0216b8 100644 --- a/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs +++ b/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs @@ -113,15 +113,9 @@ namespace Greenshot.Plugin.Jira.Forms jiraCommentBox.Enabled = enabled; } - public void SetFilename(string filename) - { - jiraFilenameBox.Text = filename; - } + public void SetFilename(string filename) => jiraFilenameBox.Text = filename; - public Issue GetJiraIssue() - { - return _selectedIssue; - } + public Issue GetJiraIssue() => _selectedIssue; public async Task UploadAsync(IBinaryContainer attachment) { diff --git a/src/Greenshot.Plugin.Jira/IssueTypeBitmapCache.cs b/src/Greenshot.Plugin.Jira/IssueTypeBitmapCache.cs index 8b626d3a6..83d9f7d5a 100644 --- a/src/Greenshot.Plugin.Jira/IssueTypeBitmapCache.cs +++ b/src/Greenshot.Plugin.Jira/IssueTypeBitmapCache.cs @@ -42,14 +42,8 @@ namespace Greenshot.Plugin.Jira ExpireTimeSpan = TimeSpan.FromHours(4); } - protected override string CreateKey(IssueType keyObject) - { - return keyObject.Name; - } + protected override string CreateKey(IssueType keyObject) => keyObject.Name; - protected override async Task CreateAsync(IssueType issueType, CancellationToken cancellationToken = new CancellationToken()) - { - return await _jiraClient.Server.GetUriContentAsync(issueType.IconUri, cancellationToken).ConfigureAwait(false); - } + protected override async Task CreateAsync(IssueType issueType, CancellationToken cancellationToken = new CancellationToken()) => await _jiraClient.Server.GetUriContentAsync(issueType.IconUri, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Jira/JiraConnector.cs b/src/Greenshot.Plugin.Jira/JiraConnector.cs index fbfd42543..fe8cf8df9 100644 --- a/src/Greenshot.Plugin.Jira/JiraConnector.cs +++ b/src/Greenshot.Plugin.Jira/JiraConnector.cs @@ -54,21 +54,18 @@ namespace Greenshot.Plugin.Jira /// /// Initialize some basic stuff, in the case the SVG to bitmap converter /// - static JiraConnector() - { - CoreConfig.PropertyChanged += (sender, args) => - { - if (args.PropertyName == nameof(CoreConfig.IconSize)) - { - var jiraConnector = SimpleServiceProvider.Current.GetInstance(); - jiraConnector._jiraClient?.Behaviour.SetConfig(new SvgConfiguration - { - Width = CoreConfig.IconSize.Width, - Height = CoreConfig.IconSize.Height - }); - } - }; - } + static JiraConnector() => CoreConfig.PropertyChanged += (sender, args) => + { + if (args.PropertyName == nameof(CoreConfig.IconSize)) + { + var jiraConnector = SimpleServiceProvider.Current.GetInstance(); + jiraConnector._jiraClient?.Behaviour.SetConfig(new SvgConfiguration + { + Width = CoreConfig.IconSize.Width, + Height = CoreConfig.IconSize.Height + }); + } + }; /// /// Dispose, logout the users @@ -86,10 +83,7 @@ namespace Greenshot.Plugin.Jira /// /// Constructor /// - public JiraConnector() - { - JiraConfig.Url = JiraConfig.Url.Replace(DefaultPostfix, string.Empty); - } + public JiraConnector() => JiraConfig.Url = JiraConfig.Url.Replace(DefaultPostfix, string.Empty); /// /// Access the jira monitor @@ -299,10 +293,7 @@ namespace Greenshot.Plugin.Jira /// Issue /// CancellationToken /// Bitmap - public async Task GetIssueTypeBitmapAsync(Issue issue, CancellationToken cancellationToken = default) - { - return await _issueTypeBitmapCache.GetOrCreateAsync(issue.Fields.IssueType, cancellationToken).ConfigureAwait(false); - } + public async Task GetIssueTypeBitmapAsync(Issue issue, CancellationToken cancellationToken = default) => await _issueTypeBitmapCache.GetOrCreateAsync(issue.Fields.IssueType, cancellationToken).ConfigureAwait(false); /// /// Get the base uri diff --git a/src/Greenshot.Plugin.Jira/JiraDestination.cs b/src/Greenshot.Plugin.Jira/JiraDestination.cs index abfd4da7f..29be926c3 100644 --- a/src/Greenshot.Plugin.Jira/JiraDestination.cs +++ b/src/Greenshot.Plugin.Jira/JiraDestination.cs @@ -45,10 +45,7 @@ namespace Greenshot.Plugin.Jira private static readonly JiraConfiguration Config = IniConfig.GetIniSection(); private readonly Issue _jiraIssue; - public JiraDestination(Issue jiraIssue = null) - { - _jiraIssue = jiraIssue; - } + public JiraDestination(Issue jiraIssue = null) => _jiraIssue = jiraIssue; public override string Designation => "Jira"; diff --git a/src/Greenshot.Plugin.Jira/JiraDetails.cs b/src/Greenshot.Plugin.Jira/JiraDetails.cs index ff7ddd699..abce813bd 100644 --- a/src/Greenshot.Plugin.Jira/JiraDetails.cs +++ b/src/Greenshot.Plugin.Jira/JiraDetails.cs @@ -26,10 +26,7 @@ namespace Greenshot.Plugin.Jira { public class JiraDetails : IComparable { - public JiraDetails() - { - FirstSeenAt = SeenAt = DateTimeOffset.Now; - } + public JiraDetails() => FirstSeenAt = SeenAt = DateTimeOffset.Now; public string ProjectKey { get; set; } @@ -43,9 +40,6 @@ namespace Greenshot.Plugin.Jira public DateTimeOffset SeenAt { get; set; } - public int CompareTo(JiraDetails other) - { - return SeenAt.CompareTo(other.SeenAt); - } + public int CompareTo(JiraDetails other) => SeenAt.CompareTo(other.SeenAt); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Jira/JiraMonitor.cs b/src/Greenshot.Plugin.Jira/JiraMonitor.cs index 4bd06ac87..eac3be48f 100644 --- a/src/Greenshot.Plugin.Jira/JiraMonitor.cs +++ b/src/Greenshot.Plugin.Jira/JiraMonitor.cs @@ -92,18 +92,15 @@ namespace Greenshot.Plugin.Jira /// /// /// IJiraClient - public IJiraClient GetJiraClientForKey(JiraDetails jiraDetails) - { - return _projectJiraClientMap[jiraDetails.ProjectKey]; - } + public IJiraClient GetJiraClientForKey(JiraDetails jiraDetails) => _projectJiraClientMap[jiraDetails.ProjectKey]; /// /// Get the "list" of recently seen Jiras /// public IEnumerable RecentJiras => from jiraDetails in _recentJiras.Values - orderby jiraDetails.SeenAt descending - select jiraDetails; + orderby jiraDetails.SeenAt descending + select jiraDetails; /// /// Check if this monitor has active instances @@ -121,12 +118,11 @@ namespace Greenshot.Plugin.Jira var projects = await jiraInstance.Project.GetAllAsync(cancellationToken: token).ConfigureAwait(false); if (projects != null) { - foreach (var project in projects) + foreach (var project in from project in projects + where !_projectJiraClientMap.ContainsKey(project.Key) + select project) { - if (!_projectJiraClientMap.ContainsKey(project.Key)) - { - _projectJiraClientMap.Add(project.Key, jiraInstance); - } + _projectJiraClientMap.Add(project.Key, jiraInstance); } } } diff --git a/src/Greenshot.Plugin.Jira/JiraPlugin.cs b/src/Greenshot.Plugin.Jira/JiraPlugin.cs index 7b2483f21..25280717e 100644 --- a/src/Greenshot.Plugin.Jira/JiraPlugin.cs +++ b/src/Greenshot.Plugin.Jira/JiraPlugin.cs @@ -94,10 +94,6 @@ namespace Greenshot.Plugin.Jira { LogSettings.RegisterDefaultLogger(LogLevels.Error); } - else if (Log.IsErrorEnabled) - { - LogSettings.RegisterDefaultLogger(LogLevels.Error); - } else { LogSettings.RegisterDefaultLogger(LogLevels.Fatal); @@ -123,13 +119,10 @@ namespace Greenshot.Plugin.Jira { // check for re-login var jiraConnector = SimpleServiceProvider.Current.GetInstance(); - if (jiraConnector?.IsLoggedIn == true && !string.IsNullOrEmpty(url)) + if (jiraConnector?.IsLoggedIn == true && !string.IsNullOrEmpty(url) && !url.Equals(_config.Url)) { - if (!url.Equals(_config.Url)) - { - jiraConnector.Logout(); - Task.Run(async () => { await jiraConnector.LoginAsync(); }); - } + jiraConnector.Logout(); + Task.Run(async () => { await jiraConnector.LoginAsync(); }); } } } diff --git a/src/Greenshot.Plugin.Jira/Log4NetLogger.cs b/src/Greenshot.Plugin.Jira/Log4NetLogger.cs index 07b9ffb43..d63ef7af8 100644 --- a/src/Greenshot.Plugin.Jira/Log4NetLogger.cs +++ b/src/Greenshot.Plugin.Jira/Log4NetLogger.cs @@ -29,10 +29,7 @@ namespace Greenshot.Plugin.Jira /// public class Log4NetLogger : AbstractLogger { - private ILog GetLogger(LogSource logSource) - { - return logSource.SourceType != null ? LogManager.GetLogger(logSource.SourceType) : LogManager.GetLogger(logSource.Source); - } + private ILog GetLogger(LogSource logSource) => logSource.SourceType != null ? LogManager.GetLogger(logSource.SourceType) : LogManager.GetLogger(logSource.Source); /// /// Write the supplied information to a log4net.ILog @@ -86,10 +83,7 @@ namespace Greenshot.Plugin.Jira /// /// /// - public override void WriteLine(LogInfo logInfo, string messageTemplate, params object[] logParameters) - { - Write(logInfo, messageTemplate, logParameters); - } + public override void WriteLine(LogInfo logInfo, string messageTemplate, params object[] logParameters) => Write(logInfo, messageTemplate, logParameters); /// /// Test if a certain LogLevels enum is enabled diff --git a/src/Greenshot.Plugin.Office/Com/DisposableCom.cs b/src/Greenshot.Plugin.Office/Com/DisposableCom.cs index 5b24384e8..be25ae6bf 100644 --- a/src/Greenshot.Plugin.Office/Com/DisposableCom.cs +++ b/src/Greenshot.Plugin.Office/Com/DisposableCom.cs @@ -14,9 +14,6 @@ namespace Greenshot.Plugin.Office.Com /// Type for the com object /// the com object itself /// IDisposableCom of type T - public static IDisposableCom Create(T comObject) - { - return Equals(comObject, default(T)) ? null : (IDisposableCom)new DisposableComImplementation(comObject); - } + public static IDisposableCom Create(T comObject) => Equals(comObject, default(T)) ? null : (IDisposableCom)new DisposableComImplementation(comObject); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/Com/DisposableComImplementation.cs b/src/Greenshot.Plugin.Office/Com/DisposableComImplementation.cs index 572de52d8..501dcd7c5 100644 --- a/src/Greenshot.Plugin.Office/Com/DisposableComImplementation.cs +++ b/src/Greenshot.Plugin.Office/Com/DisposableComImplementation.cs @@ -12,10 +12,7 @@ namespace Greenshot.Plugin.Office.Com /// Type of the com object internal class DisposableComImplementation : IDisposableCom { - public DisposableComImplementation(T obj) - { - ComObject = obj; - } + public DisposableComImplementation(T obj) => ComObject = obj; public T ComObject { get; private set; } diff --git a/src/Greenshot.Plugin.Office/Com/Ole32Api.cs b/src/Greenshot.Plugin.Office/Com/Ole32Api.cs index 3f99df5bb..bc6efd9ac 100644 --- a/src/Greenshot.Plugin.Office/Com/Ole32Api.cs +++ b/src/Greenshot.Plugin.Office/Com/Ole32Api.cs @@ -18,10 +18,7 @@ namespace Greenshot.Plugin.Office.Com /// /// string with the program ID /// Guid with the clsId - public static Guid ClassIdFromProgId(string programId) - { - return CLSIDFromProgID(programId, out Guid clsId).Succeeded() ? clsId : clsId; - } + public static Guid ClassIdFromProgId(string programId) => CLSIDFromProgID(programId, out Guid clsId).Succeeded() ? clsId : clsId; /// /// See more here diff --git a/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs b/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs index 7993b7365..1c4767456 100644 --- a/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs +++ b/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs @@ -19,10 +19,7 @@ namespace Greenshot.Plugin.Office.Com /// Type for the instance /// Guid /// IDisposableCom of T - public static IDisposableCom GetActiveObject(ref Guid clsId) - { - return GetActiveObject(ref clsId, IntPtr.Zero, out object comObject).Succeeded() ? DisposableCom.Create((T)comObject) : null; - } + public static IDisposableCom GetActiveObject(ref Guid clsId) => GetActiveObject(ref clsId, IntPtr.Zero, out object comObject).Succeeded() ? DisposableCom.Create((T)comObject) : null; /// /// Get the active instance of the com object with the specified progId diff --git a/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs b/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs index b4109da28..38c670b7d 100644 --- a/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs @@ -57,10 +57,7 @@ namespace Greenshot.Plugin.Office.Destinations { } - public ExcelDestination(string workbookName) - { - _workbookName = workbookName; - } + public ExcelDestination(string workbookName) => _workbookName = workbookName; public override string Designation => "Excel"; diff --git a/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs b/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs index 8f51ff5df..15aea3005 100644 --- a/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs @@ -56,43 +56,19 @@ namespace Greenshot.Plugin.Office.Destinations { } - public OneNoteDestination(OneNotePage page) - { - this.page = page; - } + public OneNoteDestination(OneNotePage page) => this.page = page; - public override string Designation - { - get { return DESIGNATION; } - } + public override string Designation => DESIGNATION; - public override string Description - { - get - { - return page == null ? "Microsoft OneNote" : page.DisplayName; - } - } + public override string Description => page == null ? "Microsoft OneNote" : page.DisplayName; - public override int Priority - { - get { return 4; } - } + public override int Priority => 4; - public override bool IsDynamic - { - get { return true; } - } + public override bool IsDynamic => true; - public override bool IsActive - { - get { return base.IsActive && exePath != null; } - } + public override bool IsActive => base.IsActive && exePath != null; - public override Image DisplayIcon - { - get { return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION); } - } + public override Image DisplayIcon => PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION); public override IEnumerable DynamicDestinations() { diff --git a/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs b/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs index 8dcaadc0d..1d9a4220e 100644 --- a/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs @@ -60,20 +60,11 @@ namespace Greenshot.Plugin.Office.Destinations { } - public PowerpointDestination(string presentationName) - { - _presentationName = presentationName; - } + public PowerpointDestination(string presentationName) => _presentationName = presentationName; public override string Designation => "Powerpoint"; - public override string Description - { - get - { - return _presentationName ?? "Microsoft Powerpoint"; - } - } + public override string Description => _presentationName ?? "Microsoft Powerpoint"; public override int Priority => 4; @@ -81,15 +72,9 @@ namespace Greenshot.Plugin.Office.Destinations public override bool IsActive => base.IsActive && ExePath != null; - public override Image DisplayIcon - { - get - { - return !string.IsNullOrEmpty(_presentationName) + public override Image DisplayIcon => !string.IsNullOrEmpty(_presentationName) ? PluginUtils.GetCachedExeIcon(ExePath, IconPresentation) : PluginUtils.GetCachedExeIcon(ExePath, IconApplication); - } - } public override IEnumerable DynamicDestinations() { diff --git a/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs b/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs index 6bc4d0d6e..dd4ec0534 100644 --- a/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs @@ -57,10 +57,7 @@ namespace Greenshot.Plugin.Office.Destinations { } - public WordDestination(string wordCaption) - { - _documentCaption = wordCaption; - } + public WordDestination(string wordCaption) => _documentCaption = wordCaption; public override string Designation => "Word"; diff --git a/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs index 7bba19734..336d87b9d 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs @@ -95,12 +95,9 @@ namespace Greenshot.Plugin.Office.OfficeExport break; case AppointmentItem appointmentItem: - if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) + if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings && !string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) { - if (!string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) - { - return ExportToInspector(null, activeExplorer, appointmentItem.Class, null, tmpFile, attachmentName); - } + return ExportToInspector(null, activeExplorer, appointmentItem.Class, null, tmpFile, attachmentName); } break; @@ -224,13 +221,10 @@ namespace Greenshot.Plugin.Office.OfficeExport // TODO: Needs to have the Microsoft Outlook 15.0 Object Library installed wordDocument = DisposableCom.Create((_Document)explorer.ComObject.ActiveInlineResponseWordEditor); } - else if (inspector != null) + else if (inspector != null && inspector.ComObject.IsWordMail() && (inspector.ComObject.EditorType == OlEditorType.olEditorWord)) { - if (inspector.ComObject.IsWordMail() && (inspector.ComObject.EditorType == OlEditorType.olEditorWord)) - { - var tmpWordDocument = (_Document)inspector.ComObject.WordEditor; - wordDocument = DisposableCom.Create(tmpWordDocument); - } + var tmpWordDocument = (_Document)inspector.ComObject.WordEditor; + wordDocument = DisposableCom.Create(tmpWordDocument); } if (wordDocument != null) @@ -495,14 +489,7 @@ namespace Greenshot.Plugin.Office.OfficeExport if (bodyIndex >= 0) { bodyIndex = bodyString.IndexOf(">", bodyIndex, StringComparison.Ordinal) + 1; - if (bodyIndex >= 0) - { - bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded); - } - else - { - bodyString = fallbackBody; - } + bodyString = bodyIndex >= 0 ? bodyString.Insert(bodyIndex, htmlImgEmbedded) : fallbackBody; } else { @@ -744,12 +731,9 @@ namespace Greenshot.Plugin.Office.OfficeExport break; case AppointmentItem appointmentItem: - if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) + if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings && !string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) { - if (!string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) - { - inspectorCaptions.Add(caption, appointmentItem.Class); - } + inspectorCaptions.Add(caption, appointmentItem.Class); } break; diff --git a/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs index 01bdd99b6..2e63ccde9 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs @@ -113,14 +113,7 @@ namespace Greenshot.Plugin.Office.OfficeExport using (var shapes = DisposableCom.Create(slide.ComObject.Shapes)) { using var shape = DisposableCom.Create(shapes.ComObject.AddPicture(tmpFile, MsoTriState.msoFalse, MsoTriState.msoTrue, 0, 0, width, height)); - if (_officeConfiguration.PowerpointLockAspectRatio) - { - shape.ComObject.LockAspectRatio = MsoTriState.msoTrue; - } - else - { - shape.ComObject.LockAspectRatio = MsoTriState.msoFalse; - } + shape.ComObject.LockAspectRatio = _officeConfiguration.PowerpointLockAspectRatio ? MsoTriState.msoTrue : MsoTriState.msoFalse; shape.ComObject.ScaleHeight(1, MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle); shape.ComObject.ScaleWidth(1, MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle); @@ -292,12 +285,9 @@ namespace Greenshot.Plugin.Office.OfficeExport continue; } - if (IsAfter2003()) + if (IsAfter2003() && presentation.ComObject.Final) { - if (presentation.ComObject.Final) - { - continue; - } + continue; } yield return presentation.ComObject.Name; @@ -355,9 +345,6 @@ namespace Greenshot.Plugin.Office.OfficeExport return isPictureAdded; } - private bool IsAfter2003() - { - return _powerpointVersion.Major > (int)OfficeVersions.Office2003; - } + private bool IsAfter2003() => _powerpointVersion.Major > (int)OfficeVersions.Office2003; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs index 21e954ab8..095e37fe7 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs @@ -121,12 +121,9 @@ namespace Greenshot.Plugin.Office.OfficeExport continue; } - if (IsAfter2003()) + if (IsAfter2003() && document.ComObject.Final) { - if (document.ComObject.Final) - { - continue; - } + continue; } using var activeWindow = DisposableCom.Create(document.ComObject.ActiveWindow); @@ -356,9 +353,6 @@ namespace Greenshot.Plugin.Office.OfficeExport /// Check if the used version is higher than Office 2003 /// /// - private bool IsAfter2003() - { - return _wordVersion.Major > (int)OfficeVersions.Office2003; - } + private bool IsAfter2003() => _wordVersion.Major > (int)OfficeVersions.Office2003; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/OfficePlugin.cs b/src/Greenshot.Plugin.Office/OfficePlugin.cs index a9f85e45d..b29860890 100644 --- a/src/Greenshot.Plugin.Office/OfficePlugin.cs +++ b/src/Greenshot.Plugin.Office/OfficePlugin.cs @@ -140,17 +140,11 @@ namespace Greenshot.Plugin.Office return true; } - public void Shutdown() - { - LOG.Debug("Office Plugin shutdown."); - } + public void Shutdown() => LOG.Debug("Office Plugin shutdown."); /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - throw new NotImplementedException(); - } + public void Configure() => throw new NotImplementedException(); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs b/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs index 6809724dd..904f9ba3c 100644 --- a/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs +++ b/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs @@ -48,13 +48,7 @@ namespace Greenshot.Plugin.Photobucket public override string Designation => "Photobucket"; - public override string Description - { - get - { - return _albumPath ?? Language.GetString("photobucket", LangKey.upload_menu_item); - } - } + public override string Description => _albumPath ?? Language.GetString("photobucket", LangKey.upload_menu_item); public override Image DisplayIcon { diff --git a/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs b/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs index 0dc64760e..c65121f8c 100644 --- a/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs +++ b/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs @@ -106,10 +106,7 @@ namespace Greenshot.Plugin.Photobucket /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); /// /// Upload the capture to Photobucket diff --git a/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs b/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs index 9ef117638..52b407287 100644 --- a/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs +++ b/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs @@ -64,10 +64,7 @@ namespace Greenshot.Plugin.Win10.Internal } /// - public void Seek(ulong position) - { - Seek((long)position, SeekOrigin.Begin); - } + public void Seek(ulong position) => Seek((long)position, SeekOrigin.Begin); /// public Windows.Foundation.IAsyncOperationWithProgress ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) diff --git a/src/Greenshot.Plugin.Win10/ToastNotificationService.cs b/src/Greenshot.Plugin.Win10/ToastNotificationService.cs index 9af83c14d..e0bf69ff2 100644 --- a/src/Greenshot.Plugin.Win10/ToastNotificationService.cs +++ b/src/Greenshot.Plugin.Win10/ToastNotificationService.cs @@ -123,7 +123,7 @@ namespace Greenshot.Plugin.Win10 .Show(toast => { // Windows 10 first with 1903: ExpiresOnReboot = true - toast.ExpirationTime = timeout.HasValue ? DateTimeOffset.Now.Add(timeout.Value) : (DateTimeOffset?)null; + toast.ExpirationTime = timeout.HasValue ? DateTimeOffset.Now.Add(timeout.Value) : null; void ToastActivatedHandler(ToastNotification toastNotification, object sender) { @@ -183,20 +183,11 @@ namespace Greenshot.Plugin.Win10 Log.Debug(sender.Content.GetXml()); } - public void ShowWarningMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, onClickAction, onClosedAction); - } + public void ShowWarningMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, onClickAction, onClosedAction); - public void ShowErrorMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, onClickAction, onClosedAction); - } + public void ShowErrorMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, onClickAction, onClosedAction); - public void ShowInfoMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, onClickAction, onClosedAction); - } + public void ShowInfoMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, onClickAction, onClosedAction); /// /// Factory method, helping with checking if the notification service is even available diff --git a/src/Greenshot.Plugin.Win10/Win10Plugin.cs b/src/Greenshot.Plugin.Win10/Win10Plugin.cs index 6b15ff3c5..15c1c87da 100644 --- a/src/Greenshot.Plugin.Win10/Win10Plugin.cs +++ b/src/Greenshot.Plugin.Win10/Win10Plugin.cs @@ -41,10 +41,7 @@ namespace Greenshot.Plugin.Win10 // Nothing to dispose } - public void Configure() - { - throw new NotImplementedException(); - } + public void Configure() => throw new NotImplementedException(); /// /// Name of the plugin diff --git a/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs b/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs index 2addc0a8e..fee4abef0 100644 --- a/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs +++ b/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs @@ -38,10 +38,7 @@ namespace Greenshot.Controls private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); private static Image _scaledCheckbox; - public ContextMenuToolStripProfessionalRenderer(IProvideDeviceDpi provideDeviceDpi) - { - _provideDeviceDpi = provideDeviceDpi; - } + public ContextMenuToolStripProfessionalRenderer(IProvideDeviceDpi provideDeviceDpi) => _provideDeviceDpi = provideDeviceDpi; protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { var newSize = DpiCalculator.ScaleWithDpi(CoreConfig.IconSize, _provideDeviceDpi.DeviceDpi); diff --git a/src/Greenshot/Destinations/ClipboardDestination.cs b/src/Greenshot/Destinations/ClipboardDestination.cs index 7db8514ec..28661ee50 100644 --- a/src/Greenshot/Destinations/ClipboardDestination.cs +++ b/src/Greenshot/Destinations/ClipboardDestination.cs @@ -36,25 +36,13 @@ namespace Greenshot.Destinations { public override string Designation => nameof(WellKnownDestinations.Clipboard); - public override string Description - { - get { return Language.GetString(LangKey.settings_destination_clipboard); } - } + public override string Description => Language.GetString(LangKey.settings_destination_clipboard); - public override int Priority - { - get { return 2; } - } + public override int Priority => 2; - public override Keys EditorShortcutKeys - { - get { return Keys.Control | Keys.Shift | Keys.C; } - } + public override Keys EditorShortcutKeys => Keys.Control | Keys.Shift | Keys.C; - public override Image DisplayIcon - { - get { return GreenshotResources.GetImage("Clipboard.Image"); } - } + public override Image DisplayIcon => GreenshotResources.GetImage("Clipboard.Image"); public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { diff --git a/src/Greenshot/Destinations/EmailDestination.cs b/src/Greenshot/Destinations/EmailDestination.cs index 83369e10d..dbc323508 100644 --- a/src/Greenshot/Destinations/EmailDestination.cs +++ b/src/Greenshot/Destinations/EmailDestination.cs @@ -53,14 +53,9 @@ namespace Greenshot.Destinations public override string Designation => nameof(WellKnownDestinations.EMail); - public override string Description - { - get - { + public override string Description => // Make sure there is some kind of "mail" name - return _mapiClient ??= Language.GetString(LangKey.editor_email); - } - } + _mapiClient ??= Language.GetString(LangKey.editor_email); public override int Priority => 3; @@ -73,7 +68,7 @@ namespace Greenshot.Destinations // Disable if the office plugin is installed and the client is outlook // TODO: Change this! It always creates an exception, as the plugin has not been loaded the type is not there :( var outlookDestination = Type.GetType("GreenshotOfficePlugin.OutlookDestination,GreenshotOfficePlugin", false); - if (outlookDestination != null && _mapiClient.ToLower().Contains("microsoft outlook")) + if (outlookDestination != null && _mapiClient.IndexOf("microsoft outlook", StringComparison.CurrentCultureIgnoreCase) >= 0) { _isActiveFlag = false; } diff --git a/src/Greenshot/Destinations/FileWithDialogDestination.cs b/src/Greenshot/Destinations/FileWithDialogDestination.cs index 5c863e0c5..34305b06b 100644 --- a/src/Greenshot/Destinations/FileWithDialogDestination.cs +++ b/src/Greenshot/Destinations/FileWithDialogDestination.cs @@ -42,15 +42,9 @@ namespace Greenshot.Destinations public override int Priority => 0; - public override Keys EditorShortcutKeys - { - get { return Keys.Control | Keys.Shift | Keys.S; } - } + public override Keys EditorShortcutKeys => Keys.Control | Keys.Shift | Keys.S; - public override Image DisplayIcon - { - get { return GreenshotResources.GetImage("Save.Image"); } - } + public override Image DisplayIcon => GreenshotResources.GetImage("Save.Image"); public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { diff --git a/src/Greenshot/Destinations/PrinterDestination.cs b/src/Greenshot/Destinations/PrinterDestination.cs index 4086264ed..ba0fc2d32 100644 --- a/src/Greenshot/Destinations/PrinterDestination.cs +++ b/src/Greenshot/Destinations/PrinterDestination.cs @@ -43,22 +43,13 @@ namespace Greenshot.Destinations { } - public PrinterDestination(string printerName) - { - _printerName = printerName; - } + public PrinterDestination(string printerName) => _printerName = printerName; public override string Designation => nameof(WellKnownDestinations.Printer); - public override string Description - { - get - { - return _printerName != null + public override string Description => _printerName != null ? Language.GetString(LangKey.settings_destination_printer) + " - " + _printerName : Language.GetString(LangKey.settings_destination_printer); - } - } public override int Priority => 2; @@ -83,7 +74,7 @@ namespace Greenshot.Destinations printers.Add(printer); } - printers.Sort(delegate (string p1, string p2) + printers.Sort((string p1, string p2) => { if (defaultPrinter.Equals(p1)) { diff --git a/src/Greenshot/Forms/BugReportForm.cs b/src/Greenshot/Forms/BugReportForm.cs index ec3d70065..b857dc7f0 100644 --- a/src/Greenshot/Forms/BugReportForm.cs +++ b/src/Greenshot/Forms/BugReportForm.cs @@ -38,15 +38,9 @@ namespace Greenshot.Forms ToFront = true; } - public BugReportForm(string bugText) : this() - { - textBoxDescription.Text = bugText; - } + public BugReportForm(string bugText) : this() => textBoxDescription.Text = bugText; - private void LinkLblBugsLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - openLink((LinkLabel)sender); - } + private void LinkLblBugsLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => openLink((LinkLabel)sender); private void openLink(LinkLabel link) { diff --git a/src/Greenshot/Forms/CaptureForm.cs b/src/Greenshot/Forms/CaptureForm.cs index e5d206769..737c43fa8 100644 --- a/src/Greenshot/Forms/CaptureForm.cs +++ b/src/Greenshot/Forms/CaptureForm.cs @@ -39,6 +39,7 @@ using Greenshot.Base.Core; using Greenshot.Base.IniFile; using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces.Ocr; +using System.Linq; namespace Greenshot.Forms { @@ -463,12 +464,11 @@ namespace Greenshot.Forms if (lineBounds.IsEmpty) continue; // Highlight the text which is selected if (!lineBounds.Contains(location)) continue; - foreach (var word in line.Words) + foreach (var _ in from word in line.Words + where word.Bounds.Contains(location) + select new { }) { - if (word.Bounds.Contains(location)) - { - return true; - } + return true; } } @@ -536,10 +536,7 @@ namespace Greenshot.Forms /// /// /// - private bool IsAnimating(IAnimator animator) - { - return animator != null && animator.HasNext; - } + private bool IsAnimating(IAnimator animator) => animator?.HasNext == true; /// /// update the frame, this only invalidates @@ -732,14 +729,7 @@ namespace Greenshot.Forms { continue; } - if (invalidateRectangle.IsEmpty) - { - invalidateRectangle = word.Bounds; - } - else - { - invalidateRectangle = invalidateRectangle.Union(word.Bounds); - } + invalidateRectangle = invalidateRectangle.IsEmpty ? word.Bounds : invalidateRectangle.Union(word.Bounds); } } else if (lineBounds.Contains(_mouseMovePos)) @@ -747,14 +737,7 @@ namespace Greenshot.Forms foreach (var word in line.Words) { if (!word.Bounds.Contains(_mouseMovePos)) continue; - if (invalidateRectangle.IsEmpty) - { - invalidateRectangle = word.Bounds; - } - else - { - invalidateRectangle = invalidateRectangle.Union(word.Bounds); - } + invalidateRectangle = invalidateRectangle.IsEmpty ? word.Bounds : invalidateRectangle.Union(word.Bounds); break; } diff --git a/src/Greenshot/Forms/LanguageDialog.cs b/src/Greenshot/Forms/LanguageDialog.cs index 7e69bc24b..6bdaf4a0c 100644 --- a/src/Greenshot/Forms/LanguageDialog.cs +++ b/src/Greenshot/Forms/LanguageDialog.cs @@ -96,9 +96,6 @@ namespace Greenshot.Forms Close(); } - public static LanguageDialog GetInstance() - { - return _uniqueInstance ??= new LanguageDialog(); - } + public static LanguageDialog GetInstance() => _uniqueInstance ??= new LanguageDialog(); } } \ No newline at end of file diff --git a/src/Greenshot/Forms/MainForm.cs b/src/Greenshot/Forms/MainForm.cs index 04b6789cb..30e8a5ad5 100644 --- a/src/Greenshot/Forms/MainForm.cs +++ b/src/Greenshot/Forms/MainForm.cs @@ -117,7 +117,7 @@ namespace Greenshot.Forms { string argument = arguments[argumentNr]; // Help - if (argument.ToLower().Equals("/help") || argument.ToLower().Equals("/h") || argument.ToLower().Equals("/?")) + if (argument.Equals("/help", StringComparison.CurrentCultureIgnoreCase) || argument.Equals("/h", StringComparison.CurrentCultureIgnoreCase) || argument.Equals("/?", StringComparison.CurrentCultureIgnoreCase)) { // Try to attach to the console bool attachedToConsole = Kernel32Api.AttachConsole(); @@ -166,7 +166,7 @@ namespace Greenshot.Forms return; } - if (argument.ToLower().Equals("/exit")) + if (argument.Equals("/exit", StringComparison.CurrentCultureIgnoreCase)) { // un-register application on uninstall (allow uninstall) try @@ -185,7 +185,7 @@ namespace Greenshot.Forms } // Reload the configuration - if (argument.ToLower().Equals("/reload")) + if (argument.Equals("/reload", StringComparison.CurrentCultureIgnoreCase)) { // Modify configuration LOG.Info("Reloading configuration!"); @@ -196,7 +196,7 @@ namespace Greenshot.Forms } // Stop running - if (argument.ToLower().Equals("/norun")) + if (argument.Equals("/norun", StringComparison.CurrentCultureIgnoreCase)) { // Make an exit possible FreeMutex(); @@ -204,7 +204,7 @@ namespace Greenshot.Forms } // Language - if (argument.ToLower().Equals("/language")) + if (argument.Equals("/language", StringComparison.CurrentCultureIgnoreCase)) { _conf.Language = arguments[++argumentNr]; IniConfig.Save(); @@ -212,7 +212,7 @@ namespace Greenshot.Forms } // Setting the INI-directory - if (argument.ToLower().Equals("/inidirectory")) + if (argument.Equals("/inidirectory", StringComparison.CurrentCultureIgnoreCase)) { IniConfig.IniDirectory = arguments[++argumentNr]; continue; @@ -769,10 +769,7 @@ namespace Greenshot.Forms /// Registers all hotkeys as configured, displaying a dialog in case of hotkey conflicts with other tools. /// /// Whether the hotkeys could be registered to the users content. This also applies if conflicts arise and the user decides to ignore these (i.e. not to register the conflicting hotkey). - public static bool RegisterHotkeys() - { - return RegisterHotkeys(false); - } + public static bool RegisterHotkeys() => RegisterHotkeys(false); /// /// Registers all hotkeys as configured, displaying a dialog in case of hotkey conflicts with other tools. @@ -814,12 +811,9 @@ namespace Greenshot.Forms success = false; } - if (_conf.IECapture) + if (_conf.IECapture && !RegisterWrapper(failedKeys, "CaptureIE", "IEHotkey", _instance.CaptureIE, ignoreFailedRegistration)) { - if (!RegisterWrapper(failedKeys, "CaptureIE", "IEHotkey", _instance.CaptureIE, ignoreFailedRegistration)) - { - success = false; - } + success = false; } if (!success) @@ -936,10 +930,7 @@ namespace Greenshot.Forms //loProcess.MinWorkingSet = (IntPtr)300000; } - private void CaptureRegion() - { - CaptureHelper.CaptureRegion(true); - } + private void CaptureRegion() => CaptureHelper.CaptureRegion(true); private void CaptureFile(IDestination destination = null) { @@ -961,23 +952,14 @@ namespace Greenshot.Forms } } - private void CaptureFullScreen() - { - CaptureHelper.CaptureFullscreen(true, _conf.ScreenCaptureMode); - } + private void CaptureFullScreen() => CaptureHelper.CaptureFullscreen(true, _conf.ScreenCaptureMode); - private void CaptureLastRegion() - { - CaptureHelper.CaptureLastRegion(true); - } + private void CaptureLastRegion() => CaptureHelper.CaptureLastRegion(true); /// /// This is used by the hotkey trigger /// - private void CaptureClipboard() - { - CaptureHelper.CaptureClipboard(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); - } + private void CaptureClipboard() => CaptureHelper.CaptureClipboard(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); private void CaptureIE() { @@ -1191,10 +1173,7 @@ namespace Greenshot.Forms AddCaptureWindowMenuItems(captureWindowFromListMenuItem, Contextmenu_CaptureWindowFromList_Click); } - private void CaptureWindowFromListMenuDropDownClosed(object sender, EventArgs e) - { - CleanupThumbnail(); - } + private void CaptureWindowFromListMenuDropDownClosed(object sender, EventArgs e) => CleanupThumbnail(); private void ShowThumbnailOnEnter(object sender, EventArgs e) { @@ -1203,10 +1182,7 @@ namespace Greenshot.Forms (_thumbnailForm ??= new ThumbnailForm()).ShowThumbnail(window, captureWindowItem.GetCurrentParent().TopLevelControl); } - private void HideThumbnailOnLeave(object sender, EventArgs e) - { - _thumbnailForm?.Hide(); - } + private void HideThumbnailOnLeave(object sender, EventArgs e) => _thumbnailForm?.Hide(); private void CleanupThumbnail() { @@ -1261,35 +1237,17 @@ namespace Greenshot.Forms } } - private void CaptureAreaToolStripMenuItemClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureRegion(false); }); - } + private void CaptureAreaToolStripMenuItemClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureRegion(false); }); - private void CaptureClipboardToolStripMenuItemClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureClipboard(); }); - } + private void CaptureClipboardToolStripMenuItemClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureClipboard(); }); - private void OpenFileToolStripMenuItemClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureFile(); }); - } + private void OpenFileToolStripMenuItemClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureFile(); }); - private void CaptureFullScreenToolStripMenuItemClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureFullscreen(false, _conf.ScreenCaptureMode); }); - } + private void CaptureFullScreenToolStripMenuItemClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureFullscreen(false, _conf.ScreenCaptureMode); }); - private void Contextmenu_CaptureLastRegionClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureLastRegion(false); }); - } + private void Contextmenu_CaptureLastRegionClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureLastRegion(false); }); - private void Contextmenu_CaptureWindow_Click(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureWindowInteractive(false); }); - } + private void Contextmenu_CaptureWindow_Click(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureWindowInteractive(false); }); private void Contextmenu_CaptureWindowFromList_Click(object sender, EventArgs e) { @@ -1308,10 +1266,7 @@ namespace Greenshot.Forms }); } - private void Contextmenu_CaptureIe_Click(object sender, EventArgs e) - { - CaptureIE(); - } + private void Contextmenu_CaptureIe_Click(object sender, EventArgs e) => CaptureIE(); private void Contextmenu_CaptureIeFromList_Click(object sender, EventArgs e) { @@ -1356,20 +1311,14 @@ namespace Greenshot.Forms /// /// object /// EventArgs - private void Contextmenu_DonateClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { Process.Start("https://getgreenshot.org/support/?version=" + EnvironmentInfo.GetGreenshotVersion(true)); }); - } + private void Contextmenu_DonateClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { Process.Start("https://getgreenshot.org/support/?version=" + EnvironmentInfo.GetGreenshotVersion(true)); }); /// /// Context menu entry "Preferences" /// /// /// - private void Contextmenu_SettingsClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)ShowSetting); - } + private void Contextmenu_SettingsClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)ShowSetting); /// /// This is called indirectly from the context menu "Preferences" @@ -1404,10 +1353,7 @@ namespace Greenshot.Forms /// /// /// - private void Contextmenu_AboutClick(object sender, EventArgs e) - { - ShowAbout(); - } + private void Contextmenu_AboutClick(object sender, EventArgs e) => ShowAbout(); public void ShowAbout() { @@ -1436,20 +1382,14 @@ namespace Greenshot.Forms /// /// /// - private void Contextmenu_HelpClick(object sender, EventArgs e) - { - HelpFileLoader.LoadHelp(); - } + private void Contextmenu_HelpClick(object sender, EventArgs e) => HelpFileLoader.LoadHelp(); /// /// The "Exit" entry is clicked /// /// /// - private void Contextmenu_ExitClick(object sender, EventArgs e) - { - Exit(); - } + private void Contextmenu_ExitClick(object sender, EventArgs e) => Exit(); private void CheckStateChangedHandler(object sender, EventArgs e) { @@ -1528,15 +1468,14 @@ namespace Greenshot.Forms }; IniValue iniValue; - foreach (string propertyName in _conf.Values.Keys) + foreach (var propertyName in from string propertyName in _conf.Values.Keys + where propertyName.StartsWith("OutputPrint") + select propertyName) { - if (propertyName.StartsWith("OutputPrint")) + iniValue = _conf.Values[propertyName]; + if (iniValue.Attributes.LanguageKey != null && !iniValue.IsFixed) { - iniValue = _conf.Values[propertyName]; - if (iniValue.Attributes.LanguageKey != null && !iniValue.IsFixed) - { - selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); - } + selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); } } @@ -1931,10 +1870,7 @@ namespace Greenshot.Forms /// /// WindowDetails /// WindowDetails - public WindowDetails SelectCaptureWindow(WindowDetails windowToCapture) - { - return CaptureHelper.SelectCaptureWindow(windowToCapture); - } + public WindowDetails SelectCaptureWindow(WindowDetails windowToCapture) => CaptureHelper.SelectCaptureWindow(windowToCapture); /// /// TODO: Delete when the ICaptureHelper can be solve someway else @@ -1943,9 +1879,6 @@ namespace Greenshot.Forms /// ICapture /// WindowCaptureMode /// ICapture - public ICapture CaptureWindow(WindowDetails windowToCapture, ICapture capture, WindowCaptureMode coreConfigurationWindowCaptureMode) - { - return CaptureHelper.CaptureWindow(windowToCapture, capture, coreConfigurationWindowCaptureMode); - } + public ICapture CaptureWindow(WindowDetails windowToCapture, ICapture capture, WindowCaptureMode coreConfigurationWindowCaptureMode) => CaptureHelper.CaptureWindow(windowToCapture, capture, coreConfigurationWindowCaptureMode); } } \ No newline at end of file diff --git a/src/Greenshot/Forms/SettingsForm.cs b/src/Greenshot/Forms/SettingsForm.cs index a182cd13a..544b58dd6 100644 --- a/src/Greenshot/Forms/SettingsForm.cs +++ b/src/Greenshot/Forms/SettingsForm.cs @@ -68,10 +68,7 @@ namespace Greenshot.Forms /// /// /// DpiChangedEventArgs - private void AdjustToDpi(object sender, DpiChangedEventArgs dpiChangedEventArgs) - { - DisplaySettings(); - } + private void AdjustToDpi(object sender, DpiChangedEventArgs dpiChangedEventArgs) => DisplaySettings(); protected override void OnLoad(EventArgs e) { @@ -122,14 +119,7 @@ namespace Greenshot.Forms // Check if we can into the forbidden range if (currentValue > 0 && currentValue < 7) { - if (_daysBetweenCheckPreviousValue <= currentValue) - { - numericUpDown_daysbetweencheck.Value = 7; - } - else - { - numericUpDown_daysbetweencheck.Value = 0; - } + numericUpDown_daysbetweencheck.Value = _daysBetweenCheckPreviousValue <= currentValue ? 7 : 0; } if ((int)numericUpDown_daysbetweencheck.Value < 0) @@ -326,10 +316,7 @@ namespace Greenshot.Forms } // Check the settings and somehow visibly mark when something is incorrect - private bool CheckSettings() - { - return CheckFilenamePattern() && CheckStorageLocationPath(); - } + private bool CheckSettings() => CheckFilenamePattern() && CheckStorageLocationPath(); private bool CheckFilenamePattern() { @@ -370,15 +357,9 @@ namespace Greenshot.Forms } } - private void FilenamePatternChanged(object sender, EventArgs e) - { - CheckFilenamePattern(); - } + private void FilenamePatternChanged(object sender, EventArgs e) => CheckFilenamePattern(); - private void StorageLocationChanged(object sender, EventArgs e) - { - CheckStorageLocationPath(); - } + private void StorageLocationChanged(object sender, EventArgs e) => CheckStorageLocationPath(); /// /// Show all destination descriptions in the current language @@ -444,16 +425,9 @@ namespace Greenshot.Forms } else { - ListViewItem item; - if (destinationImage != null) - { - item = listview_destinations.Items.Add(currentDestination.Description, imageNr); - } - else - { - item = listview_destinations.Items.Add(currentDestination.Description); - } - + ListViewItem item = destinationImage != null + ? listview_destinations.Items.Add(currentDestination.Description, imageNr) + : listview_destinations.Items.Add(currentDestination.Description); item.Tag = currentDestination; item.Checked = coreConfiguration.OutputDestinations.Contains(currentDestination.Designation); } @@ -622,10 +596,7 @@ namespace Greenshot.Forms } } - private void Settings_cancelClick(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - } + private void Settings_cancelClick(object sender, EventArgs e) => DialogResult = DialogResult.Cancel; private void Settings_okayClick(object sender, EventArgs e) { @@ -651,20 +622,14 @@ namespace Greenshot.Forms { // Get the storage location and replace the environment variables folderBrowserDialog1.SelectedPath = FilenameHelper.FillVariables(textbox_storagelocation.Text, false); - if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) + // Only change if there is a change, otherwise we might overwrite the environment variables + if (folderBrowserDialog1.ShowDialog() == DialogResult.OK && folderBrowserDialog1.SelectedPath?.Equals(FilenameHelper.FillVariables(textbox_storagelocation.Text, false)) == false) { - // Only change if there is a change, otherwise we might overwrite the environment variables - if (folderBrowserDialog1.SelectedPath?.Equals(FilenameHelper.FillVariables(textbox_storagelocation.Text, false)) == false) - { - textbox_storagelocation.Text = folderBrowserDialog1.SelectedPath; - } + textbox_storagelocation.Text = folderBrowserDialog1.SelectedPath; } } - private void TrackBarJpegQualityScroll(object sender, EventArgs e) - { - textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(CultureInfo.InvariantCulture); - } + private void TrackBarJpegQualityScroll(object sender, EventArgs e) => textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(CultureInfo.InvariantCulture); private void BtnPatternHelpClick(object sender, EventArgs e) { @@ -674,15 +639,9 @@ namespace Greenshot.Forms MessageBox.Show(filenamepatternText, Language.GetString(LangKey.settings_filenamepattern)); } - private void Listview_pluginsSelectedIndexChanged(object sender, EventArgs e) - { - button_pluginconfigure.Enabled = PluginHelper.Instance.IsSelectedItemConfigurable(listview_plugins); - } + private void Listview_pluginsSelectedIndexChanged(object sender, EventArgs e) => button_pluginconfigure.Enabled = PluginHelper.Instance.IsSelectedItemConfigurable(listview_plugins); - private void Button_pluginconfigureClick(object sender, EventArgs e) - { - PluginHelper.Instance.ConfigureSelectedItem(listview_plugins); - } + private void Button_pluginconfigureClick(object sender, EventArgs e) => PluginHelper.Instance.ConfigureSelectedItem(listview_plugins); private void Combobox_languageSelectedIndexChanged(object sender, EventArgs e) { @@ -772,10 +731,7 @@ namespace Greenshot.Forms } } - private void DestinationsCheckStateChanged(object sender, EventArgs e) - { - CheckDestinationSettings(); - } + private void DestinationsCheckStateChanged(object sender, EventArgs e) => CheckDestinationSettings(); protected override void OnFieldsFilled() { @@ -817,10 +773,7 @@ namespace Greenshot.Forms } } - private void Radiobutton_CheckedChanged(object sender, EventArgs e) - { - combobox_window_capture_mode.Enabled = radiobuttonWindowCapture.Checked; - } + private void Radiobutton_CheckedChanged(object sender, EventArgs e) => combobox_window_capture_mode.Enabled = radiobuttonWindowCapture.Checked; } public class ListviewWithDestinationComparer : IComparer diff --git a/src/Greenshot/Forms/ToolStripMenuSelectList.cs b/src/Greenshot/Forms/ToolStripMenuSelectList.cs index 6e73874b1..daa1717c7 100644 --- a/src/Greenshot/Forms/ToolStripMenuSelectList.cs +++ b/src/Greenshot/Forms/ToolStripMenuSelectList.cs @@ -133,10 +133,7 @@ namespace Greenshot.Forms /// the label to be displayed /// the data to be returned when an item is queried /// whether the item is initially checked - public void AddItem(string label, object data, bool isChecked) - { - AddItem(label, null, data, isChecked); - } + public void AddItem(string label, object data, bool isChecked) => AddItem(label, null, data, isChecked); /// /// unchecks all items of the list @@ -162,10 +159,7 @@ namespace Greenshot.Forms { public ToolStripMenuSelectListItem Item { get; set; } - public ItemCheckedChangedEventArgs(ToolStripMenuSelectListItem item) - { - Item = item; - } + public ItemCheckedChangedEventArgs(ToolStripMenuSelectListItem item) => Item = item; } /// diff --git a/src/Greenshot/GreenshotMain.cs b/src/Greenshot/GreenshotMain.cs index 2d42d4b11..259811613 100644 --- a/src/Greenshot/GreenshotMain.cs +++ b/src/Greenshot/GreenshotMain.cs @@ -30,12 +30,9 @@ namespace Greenshot /// /// Description of Main. /// - public class GreenshotMain + public static class GreenshotMain { - static GreenshotMain() - { - AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; - } + static GreenshotMain() => AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { @@ -60,7 +57,7 @@ namespace Greenshot public static void Main(string[] args) { // Enable TLS 1.2 support - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; diff --git a/src/Greenshot/Helpers/CaptureHelper.cs b/src/Greenshot/Helpers/CaptureHelper.cs index 719e63cea..343995339 100644 --- a/src/Greenshot/Helpers/CaptureHelper.cs +++ b/src/Greenshot/Helpers/CaptureHelper.cs @@ -42,6 +42,7 @@ using Greenshot.Configuration; using Greenshot.Editor.Destinations; using Greenshot.Editor.Drawing; using Greenshot.Forms; +using System.Linq; namespace Greenshot.Helpers { @@ -203,10 +204,7 @@ namespace Greenshot.Helpers _capture = new Capture(); } - public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor) : this(captureMode) - { - _captureMouseCursor = captureMouseCursor; - } + public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor) : this(captureMode) => _captureMouseCursor = captureMouseCursor; public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor, ScreenCaptureMode screenCaptureMode) : this(captureMode) { @@ -214,10 +212,7 @@ namespace Greenshot.Helpers _screenCaptureMode = screenCaptureMode; } - public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor, IDestination destination) : this(captureMode, captureMouseCursor) - { - _capture.CaptureDetails.AddDestination(destination); - } + public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor, IDestination destination) : this(captureMode, captureMouseCursor) => _capture.CaptureDetails.AddDestination(destination); public WindowDetails SelectedCaptureWindow { get; set; } @@ -350,17 +345,16 @@ namespace Greenshot.Helpers { case ScreenCaptureMode.Auto: NativePoint mouseLocation = User32Api.GetCursorLocation(); - foreach (Screen screen in Screen.AllScreens) + foreach (var screen in from Screen screen in Screen.AllScreens + where screen.Bounds.Contains(mouseLocation) + select screen) { - if (screen.Bounds.Contains(mouseLocation)) - { - _capture = WindowCapture.CaptureRectangle(_capture, screen.Bounds); - captureTaken = true; - // As the screen shot might be on a different monitor we need to correct the mouse location - var correctedCursorLocation = _capture.CursorLocation.Offset(-screen.Bounds.Location.X, -screen.Bounds.Location.Y); - _capture.CursorLocation = correctedCursorLocation; - break; - } + _capture = WindowCapture.CaptureRectangle(_capture, screen.Bounds); + captureTaken = true; + // As the screen shot might be on a different monitor we need to correct the mouse location + var correctedCursorLocation = _capture.CursorLocation.Offset(-screen.Bounds.Location.X, -screen.Bounds.Location.Y); + _capture.CursorLocation = correctedCursorLocation; + break; } break; @@ -818,12 +812,9 @@ namespace Greenshot.Helpers else { SelectedCaptureWindow = WindowDetails.GetActiveWindow(); - if (SelectedCaptureWindow != null) + if (SelectedCaptureWindow != null && Log.IsDebugEnabled) { - if (Log.IsDebugEnabled) - { - Log.DebugFormat("Capturing window: {0} with {1}", SelectedCaptureWindow.Text, SelectedCaptureWindow.WindowRectangle); - } + Log.DebugFormat("Capturing window: {0} with {1}", SelectedCaptureWindow.Text, SelectedCaptureWindow.WindowRectangle); } } @@ -984,12 +975,9 @@ namespace Greenshot.Helpers } // Change to DWM, if enabled and allowed - if (dwmEnabled) + if (dwmEnabled && WindowCapture.IsDwmAllowed(process)) { - if (WindowCapture.IsDwmAllowed(process)) - { - windowCaptureMode = WindowCaptureMode.Aero; - } + windowCaptureMode = WindowCaptureMode.Aero; } } } diff --git a/src/Greenshot/Helpers/CopyData.cs b/src/Greenshot/Helpers/CopyData.cs index 88ca89cab..173b4ca50 100644 --- a/src/Greenshot/Helpers/CopyData.cs +++ b/src/Greenshot/Helpers/CopyData.cs @@ -47,30 +47,15 @@ namespace Greenshot.Helpers { public List> Commands { get; } - public CopyDataTransport() - { - Commands = new List>(); - } + public CopyDataTransport() => Commands = new List>(); - public CopyDataTransport(CommandEnum command) : this() - { - AddCommand(command, null); - } + public CopyDataTransport(CommandEnum command) : this() => AddCommand(command, null); - public CopyDataTransport(CommandEnum command, string commandData) : this() - { - AddCommand(command, commandData); - } + public CopyDataTransport(CommandEnum command, string commandData) : this() => AddCommand(command, commandData); - public void AddCommand(CommandEnum command) - { - Commands.Add(new KeyValuePair(command, null)); - } + public void AddCommand(CommandEnum command) => Commands.Add(new KeyValuePair(command, null)); - public void AddCommand(CommandEnum command, string commandData) - { - Commands.Add(new KeyValuePair(command, commandData)); - } + public void AddCommand(CommandEnum command, string commandData) => Commands.Add(new KeyValuePair(command, commandData)); } public delegate void CopyDataReceivedEventHandler(object sender, CopyDataReceivedEventArgs e); @@ -147,10 +132,7 @@ namespace Greenshot.Helpers /// Raises the DataReceived event from this class. /// /// The data which has been received. - protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) - { - CopyDataReceived?.Invoke(this, e); - } + protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) => CopyDataReceived?.Invoke(this, e); /// /// If the form's handle changes, the properties associated @@ -191,10 +173,7 @@ namespace Greenshot.Helpers /// /// Constructs a new instance of the CopyData class /// - public CopyData() - { - _channels = new CopyDataChannels(this); - } + public CopyData() => _channels = new CopyDataChannels(this); /// /// Finalises a CopyData class which has not been disposed. @@ -264,10 +243,7 @@ namespace Greenshot.Helpers /// /// An enumerator for each of the CopyDataChannel objects /// within this collection. - public new IEnumerator GetEnumerator() - { - return Dictionary.Values.GetEnumerator(); - } + public new IEnumerator GetEnumerator() => Dictionary.Values.GetEnumerator(); /// /// Returns the CopyDataChannel at the specified 0-based index. @@ -310,19 +286,13 @@ namespace Greenshot.Helpers /// Removes an existing channel. /// /// The channel to remove - public void Remove(string channelName) - { - Dictionary.Remove(channelName); - } + public void Remove(string channelName) => Dictionary.Remove(channelName); /// /// Gets/sets whether this channel contains a CopyDataChannel /// for the specified channelName. /// - public bool Contains(string channelName) - { - return Dictionary.Contains(channelName); - } + public bool Contains(string channelName) => Dictionary.Contains(channelName); /// /// Ensures the resources associated with a CopyDataChannel @@ -372,10 +342,7 @@ namespace Greenshot.Helpers /// /// The NativeWindow this collection /// will be associated with - internal CopyDataChannels(NativeWindow owner) - { - _owner = owner; - } + internal CopyDataChannels(NativeWindow owner) => _owner = owner; } /// @@ -461,19 +428,16 @@ namespace Greenshot.Helpers // the channel: foreach (WindowDetails window in WindowDetails.GetAllWindows()) { - if (!window.Handle.Equals(_owner.Handle)) + if (!window.Handle.Equals(_owner.Handle) && GetProp(window.Handle, ChannelName) != IntPtr.Zero) { - if (GetProp(window.Handle, ChannelName) != IntPtr.Zero) + COPYDATASTRUCT cds = new() { - COPYDATASTRUCT cds = new() - { - cbData = dataSize, - dwData = IntPtr.Zero, - lpData = ptrData - }; - SendMessage(window.Handle, WM_COPYDATA, _owner.Handle, ref cds); - recipients += Marshal.GetLastWin32Error() == 0 ? 1 : 0; - } + cbData = dataSize, + dwData = IntPtr.Zero, + lpData = ptrData + }; + SendMessage(window.Handle, WM_COPYDATA, _owner.Handle, ref cds); + recipients += Marshal.GetLastWin32Error() == 0 ? 1 : 0; } } @@ -486,17 +450,13 @@ namespace Greenshot.Helpers return recipients; } - private void AddChannel() - { + private void AddChannel() => // Tag this window with property "channelName" SetProp(_owner.Handle, ChannelName, _owner.Handle); - } - private void RemoveChannel() - { + private void RemoveChannel() => // Remove the "channelName" property from this window RemoveProp(_owner.Handle, ChannelName); - } /// /// If the form's handle changes, the properties associated diff --git a/src/Greenshot/Helpers/IECaptureHelper.cs b/src/Greenshot/Helpers/IECaptureHelper.cs index facfc841b..51e15a6df 100644 --- a/src/Greenshot/Helpers/IECaptureHelper.cs +++ b/src/Greenshot/Helpers/IECaptureHelper.cs @@ -112,10 +112,7 @@ namespace Greenshot.Helpers /// Simple check if IE is running /// /// bool - public static bool IsIeRunning() - { - return GetIeWindows().Any(); - } + public static bool IsIeRunning() => GetIeWindows().Any(); /// /// Gets a list of all IE Windows & tabs with the captions of the instances diff --git a/src/Greenshot/Helpers/IEInterop/IEContainer.cs b/src/Greenshot/Helpers/IEInterop/IEContainer.cs index 01cbaa703..56bb535b4 100644 --- a/src/Greenshot/Helpers/IEInterop/IEContainer.cs +++ b/src/Greenshot/Helpers/IEInterop/IEContainer.cs @@ -427,33 +427,18 @@ namespace Greenshot.Helpers.IEInterop public DocumentContainer Parent { get; set; } - private int ScaleX(int physicalValue) - { - return (int)Math.Round(physicalValue * _zoomLevelX, MidpointRounding.AwayFromZero); - } + private int ScaleX(int physicalValue) => (int)Math.Round(physicalValue * _zoomLevelX, MidpointRounding.AwayFromZero); - private int ScaleY(int physicalValue) - { - return (int)Math.Round(physicalValue * _zoomLevelY, MidpointRounding.AwayFromZero); - } + private int ScaleY(int physicalValue) => (int)Math.Round(physicalValue * _zoomLevelY, MidpointRounding.AwayFromZero); - private int UnscaleX(int physicalValue) - { - return (int)Math.Round(physicalValue / _zoomLevelX, MidpointRounding.AwayFromZero); - } + private int UnscaleX(int physicalValue) => (int)Math.Round(physicalValue / _zoomLevelX, MidpointRounding.AwayFromZero); - private int UnscaleY(int physicalValue) - { - return (int)Math.Round(physicalValue / _zoomLevelY, MidpointRounding.AwayFromZero); - } + private int UnscaleY(int physicalValue) => (int)Math.Round(physicalValue / _zoomLevelY, MidpointRounding.AwayFromZero); /// /// Set/change an int attribute on a document /// - public void SetAttribute(string attribute, int value) - { - SetAttribute(attribute, value.ToString()); - } + public void SetAttribute(string attribute, int value) => SetAttribute(attribute, value.ToString()); /// /// Set/change an attribute on a document diff --git a/src/Greenshot/Helpers/MailHelper.cs b/src/Greenshot/Helpers/MailHelper.cs index 5e5ea8912..a0285885b 100644 --- a/src/Greenshot/Helpers/MailHelper.cs +++ b/src/Greenshot/Helpers/MailHelper.cs @@ -497,15 +497,9 @@ namespace Greenshot.Helpers /// /// Adds the specified recipient to this collection. /// - public void Add(Recipient value) - { - List.Add(value); - } + public void Add(Recipient value) => List.Add(value); - internal InteropRecipientCollection GetInteropRepresentation() - { - return new InteropRecipientCollection(this); - } + internal InteropRecipientCollection GetInteropRepresentation() => new(this); /// /// Struct which contains an interop representation of a colleciton of recipients. diff --git a/src/Greenshot/Helpers/NotifyIconNotificationService.cs b/src/Greenshot/Helpers/NotifyIconNotificationService.cs index 48709a1df..e1a52b534 100644 --- a/src/Greenshot/Helpers/NotifyIconNotificationService.cs +++ b/src/Greenshot/Helpers/NotifyIconNotificationService.cs @@ -37,10 +37,7 @@ namespace Greenshot.Helpers private static readonly CoreConfiguration CoreConfiguration = IniConfig.GetIniSection(); private readonly NotifyIcon _notifyIcon; - public NotifyIconNotificationService() - { - _notifyIcon = SimpleServiceProvider.Current.GetInstance(); - } + public NotifyIconNotificationService() => _notifyIcon = SimpleServiceProvider.Current.GetInstance(); /// /// This will show a warning message to the user @@ -49,10 +46,7 @@ namespace Greenshot.Helpers /// TimeSpan /// Action called if the user clicks the notification /// Action - public void ShowWarningMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, ToolTipIcon.Warning, onClickAction, onClosedAction); - } + public void ShowWarningMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, ToolTipIcon.Warning, onClickAction, onClosedAction); /// /// This will show an error message to the user @@ -61,10 +55,7 @@ namespace Greenshot.Helpers /// TimeSpan /// Action called if the user clicks the notification /// Action - public void ShowErrorMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, ToolTipIcon.Error, onClickAction, onClosedAction); - } + public void ShowErrorMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, ToolTipIcon.Error, onClickAction, onClosedAction); /// /// This will show an info message to the user @@ -73,10 +64,7 @@ namespace Greenshot.Helpers /// TimeSpan /// Action called if the user clicks the notification /// Action - public void ShowInfoMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, ToolTipIcon.Info, onClickAction, onClosedAction); - } + public void ShowInfoMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, ToolTipIcon.Info, onClickAction, onClosedAction); /// /// This will show a message to the user diff --git a/src/Greenshot/Helpers/PluginHelper.cs b/src/Greenshot/Helpers/PluginHelper.cs index 008c22f2e..dda42661d 100644 --- a/src/Greenshot/Helpers/PluginHelper.cs +++ b/src/Greenshot/Helpers/PluginHelper.cs @@ -117,34 +117,22 @@ namespace Greenshot.Helpers /// Thumbnail width /// Thumbnail height /// Image with Thumbnail - public Image GetThumbnail(Image image, int width, int height) - { - return image.GetThumbnailImage(width, height, ThumbnailCallback, IntPtr.Zero); - } + public Image GetThumbnail(Image image, int width, int height) => image.GetThumbnailImage(width, height, ThumbnailCallback, IntPtr.Zero); /// /// Required for GetThumbnail, but not used /// /// true - private bool ThumbnailCallback() - { - return true; - } + private bool ThumbnailCallback() => true; - public ExportInformation ExportCapture(bool manuallyInitiated, string designation, ISurface surface, ICaptureDetails captureDetails) - { - return DestinationHelper.ExportCapture(manuallyInitiated, designation, surface, captureDetails); - } + public ExportInformation ExportCapture(bool manuallyInitiated, string designation, ISurface surface, ICaptureDetails captureDetails) => DestinationHelper.ExportCapture(manuallyInitiated, designation, surface, captureDetails); /// /// Make Capture with specified Handler /// /// bool false if the mouse should not be captured, true if the configuration should be checked /// IDestination - public void CaptureRegion(bool captureMouseCursor, IDestination destination) - { - CaptureHelper.CaptureRegion(captureMouseCursor, destination); - } + public void CaptureRegion(bool captureMouseCursor, IDestination destination) => CaptureHelper.CaptureRegion(captureMouseCursor, destination); /// /// Use the supplied image, and handle it as if it's captured. diff --git a/src/Greenshot/Helpers/PrintHelper.cs b/src/Greenshot/Helpers/PrintHelper.cs index d6a200412..03c41d66d 100644 --- a/src/Greenshot/Helpers/PrintHelper.cs +++ b/src/Greenshot/Helpers/PrintHelper.cs @@ -159,10 +159,7 @@ namespace Greenshot.Helpers return returnPrinterSettings; } - private bool IsColorPrint() - { - return !CoreConfig.OutputPrintGrayscale && !CoreConfig.OutputPrintMonochrome; - } + private bool IsColorPrint() => !CoreConfig.OutputPrintGrayscale && !CoreConfig.OutputPrintMonochrome; /// /// display print options dialog (if the user has not configured Greenshot not to) @@ -217,16 +214,13 @@ namespace Greenshot.Helpers GraphicsUnit gu = GraphicsUnit.Pixel; RectangleF imageRect = image.GetBounds(ref gu); // rotate the image if it fits the page better - if (CoreConfig.OutputPrintAllowRotate) + if (CoreConfig.OutputPrintAllowRotate && ((pageRect.Width > pageRect.Height && imageRect.Width < imageRect.Height) || (pageRect.Width < pageRect.Height && imageRect.Width > imageRect.Height))) { - if ((pageRect.Width > pageRect.Height && imageRect.Width < imageRect.Height) || (pageRect.Width < pageRect.Height && imageRect.Width > imageRect.Height)) + image.RotateFlip(RotateFlipType.Rotate270FlipNone); + imageRect = image.GetBounds(ref gu); + if (alignment.Equals(ContentAlignment.TopLeft)) { - image.RotateFlip(RotateFlipType.Rotate270FlipNone); - imageRect = image.GetBounds(ref gu); - if (alignment.Equals(ContentAlignment.TopLeft)) - { - alignment = ContentAlignment.TopRight; - } + alignment = ContentAlignment.TopRight; } } diff --git a/src/Greenshot/Helpers/StartupHelper.cs b/src/Greenshot/Helpers/StartupHelper.cs index 1047ad5de..fd5d8b8ad 100644 --- a/src/Greenshot/Helpers/StartupHelper.cs +++ b/src/Greenshot/Helpers/StartupHelper.cs @@ -39,10 +39,7 @@ namespace Greenshot.Helpers private const string ApplicationName = "Greenshot"; - private static string GetExecutablePath() - { - return "\"" + Application.ExecutablePath + "\""; - } + private static string GetExecutablePath() => "\"" + Application.ExecutablePath + "\""; /// /// Return true if the current user can write the RUN key of the local machine. diff --git a/src/Greenshot/Helpers/UpdateService.cs b/src/Greenshot/Helpers/UpdateService.cs index 8cfd3c630..11d803062 100644 --- a/src/Greenshot/Helpers/UpdateService.cs +++ b/src/Greenshot/Helpers/UpdateService.cs @@ -88,10 +88,7 @@ namespace Greenshot.Helpers /// /// Start the background task which checks for updates /// - public void Startup() - { - _ = BackgroundTask(() => TimeSpan.FromDays(CoreConfig.UpdateCheckInterval), UpdateCheck, _cancellationTokenSource.Token); - } + public void Startup() => _ = BackgroundTask(() => TimeSpan.FromDays(CoreConfig.UpdateCheckInterval), UpdateCheck, _cancellationTokenSource.Token); /// /// This runs a periodic task in the background From 43ac3d6024e5b14872f4f95d4f07e452dfbfc2b7 Mon Sep 17 00:00:00 2001 From: Michael Adams Date: Thu, 14 Jul 2022 15:10:07 -0700 Subject: [PATCH 5/5] Additional work on warnings --- src/Greenshot.Base/Controls/GreenshotForm.cs | 2 +- src/Greenshot.Base/Controls/HotkeyControl.cs | 14 +++-- .../Controls/SaveImageFileDialog.cs | 10 ++-- src/Greenshot.Base/Core/AccessibleHelper.cs | 24 ++++----- src/Greenshot.Base/Core/CoreConfiguration.cs | 2 +- src/Greenshot.Base/Core/CredentialsHelper.cs | 12 ++--- src/Greenshot.Base/Core/FastBitmap.cs | 16 +++--- src/Greenshot.Base/Core/Language.cs | 10 ++-- .../Core/OAuth/LocalServerCodeReceiver.cs | 2 +- .../Core/OAuth/OAuth2Settings.cs | 2 +- src/Greenshot.Base/Core/WindowDetails.cs | 52 +++++++------------ src/Greenshot.Base/IniFile/IniAttributes.cs | 3 +- src/Greenshot.Base/IniFile/IniValue.cs | 15 ++---- .../Plugin/SurfaceOutputSettings.cs | 10 ++-- src/Greenshot.Base/Interop/COMWrapper.cs | 4 +- .../BindableToolStripDropDownButton.cs | 2 +- src/Greenshot.Editor/Controls/ColorButton.cs | 2 +- .../Controls/FontFamilyComboBox.cs | 2 +- src/Greenshot.Editor/Controls/Pipette.cs | 3 +- .../Controls/ToolStripColorButton.cs | 2 +- .../Controls/ToolStripNumericUpDown.cs | 20 +++---- .../Drawing/CursorContainer.cs | 2 +- .../Drawing/DrawableContainerList.cs | 7 +-- .../Drawing/Fields/AbstractFieldHolder.cs | 4 +- .../Fields/AbstractFieldHolderWithChildren.cs | 6 +-- src/Greenshot.Editor/Drawing/Fields/Field.cs | 2 +- .../Drawing/Fields/FieldType.cs | 5 +- .../Drawing/Filters/AbstractFilter.cs | 10 ++-- .../Drawing/Filters/BlurFilter.cs | 2 +- .../Drawing/ImageContainer.cs | 2 +- src/Greenshot.Editor/Forms/ColorDialog.cs | 4 +- .../Forms/ColorPickerToolStripButton.cs | 5 +- src/Greenshot.Editor/Forms/ImageEditorForm.cs | 4 +- src/Greenshot.Editor/Helpers/ScaleHelper.cs | 4 +- .../ConfluenceUtils.cs | 2 +- .../EnumDisplayer.cs | 2 +- .../Forms/ImgurHistory.cs | 4 +- .../ImgurConfiguration.cs | 4 +- src/Greenshot.Plugin.Imgur/ImgurInfo.cs | 4 +- src/Greenshot.Plugin.Imgur/ImgurPlugin.cs | 2 +- src/Greenshot.Plugin.Imgur/ImgurUtils.cs | 14 ++--- .../Destinations/OneNoteDestination.cs | 7 ++- .../Internal/MemoryRandomAccessStream.cs | 4 +- src/Greenshot/Forms/CaptureForm.cs | 15 +++--- src/Greenshot/Forms/MainForm.cs | 3 +- .../Helpers/IEInterop/IEContainer.cs | 16 +++--- src/Greenshot/Helpers/MailHelper.cs | 16 ++---- src/Greenshot/Helpers/UpdateService.cs | 5 +- 48 files changed, 159 insertions(+), 205 deletions(-) diff --git a/src/Greenshot.Base/Controls/GreenshotForm.cs b/src/Greenshot.Base/Controls/GreenshotForm.cs index a207ca8e0..f246e5d95 100644 --- a/src/Greenshot.Base/Controls/GreenshotForm.cs +++ b/src/Greenshot.Base/Controls/GreenshotForm.cs @@ -219,7 +219,7 @@ namespace Greenshot.Base.Controls /// public override ISite Site { - get { return base.Site; } + get => base.Site; set { // Clear any component change event handlers. diff --git a/src/Greenshot.Base/Controls/HotkeyControl.cs b/src/Greenshot.Base/Controls/HotkeyControl.cs index 19b85d280..21fc25de8 100644 --- a/src/Greenshot.Base/Controls/HotkeyControl.cs +++ b/src/Greenshot.Base/Controls/HotkeyControl.cs @@ -109,8 +109,8 @@ namespace Greenshot.Base.Controls /// public override ContextMenuStrip ContextMenuStrip { - get { return _dummy; } - set { base.ContextMenuStrip = _dummy; } + get => _dummy; + set => base.ContextMenuStrip = _dummy; } /// @@ -118,12 +118,10 @@ namespace Greenshot.Base.Controls /// public override bool Multiline { - get { return base.Multiline; } - set - { + get => base.Multiline; + set => // Ignore what the user wants; force Multiline to false base.Multiline = false; - } } /// @@ -281,7 +279,7 @@ namespace Greenshot.Base.Controls /// public Keys Hotkey { - get { return _hotkey; } + get => _hotkey; set { _hotkey = value; @@ -304,7 +302,7 @@ namespace Greenshot.Base.Controls /// public Keys HotkeyModifiers { - get { return _modifiers; } + get => _modifiers; set { _modifiers = value; diff --git a/src/Greenshot.Base/Controls/SaveImageFileDialog.cs b/src/Greenshot.Base/Controls/SaveImageFileDialog.cs index 9bf8e1758..f115428df 100644 --- a/src/Greenshot.Base/Controls/SaveImageFileDialog.cs +++ b/src/Greenshot.Base/Controls/SaveImageFileDialog.cs @@ -138,8 +138,8 @@ namespace Greenshot.Base.Controls /// public string FileName { - get { return SaveFileDialog.FileName; } - set { SaveFileDialog.FileName = value; } + get => SaveFileDialog.FileName; + set => SaveFileDialog.FileName = value; } /// @@ -147,8 +147,8 @@ namespace Greenshot.Base.Controls /// public string InitialDirectory { - get { return SaveFileDialog.InitialDirectory; } - set { SaveFileDialog.InitialDirectory = value; } + get => SaveFileDialog.InitialDirectory; + set => SaveFileDialog.InitialDirectory = value; } /// @@ -178,7 +178,7 @@ namespace Greenshot.Base.Controls /// public string Extension { - get { return _filterOptions[SaveFileDialog.FilterIndex - 1].Extension; } + get => _filterOptions[SaveFileDialog.FilterIndex - 1].Extension; set { for (int i = 0; i < _filterOptions.Length; i++) diff --git a/src/Greenshot.Base/Core/AccessibleHelper.cs b/src/Greenshot.Base/Core/AccessibleHelper.cs index ee45d7269..9eb0dcedf 100644 --- a/src/Greenshot.Base/Core/AccessibleHelper.cs +++ b/src/Greenshot.Base/Core/AccessibleHelper.cs @@ -23,6 +23,7 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Accessibility; +using System.Linq; namespace Greenshot.Base.Core { @@ -180,20 +181,19 @@ namespace Greenshot.Base.Core { get { - foreach (Accessible accessor in Children) + foreach (var tab in from Accessible accessor in Children + from tab in + from child in accessor.Children + from tab in child.Children + select tab + select tab) { - foreach (var child in accessor.Children) + _ = tab.accessible.get_accState(CHILDID_SELF); + var description = tab.accessible.get_accDescription(CHILDID_SELF); + if (!string.IsNullOrEmpty(description) && description.Contains(Environment.NewLine)) { - foreach (var tab in child.Children) - { - _ = tab.accessible.get_accState(CHILDID_SELF); - var description = tab.accessible.get_accDescription(CHILDID_SELF); - if (!string.IsNullOrEmpty(description) && 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; } } } diff --git a/src/Greenshot.Base/Core/CoreConfiguration.cs b/src/Greenshot.Base/Core/CoreConfiguration.cs index f38834ddf..be9dc5c45 100644 --- a/src/Greenshot.Base/Core/CoreConfiguration.cs +++ b/src/Greenshot.Base/Core/CoreConfiguration.cs @@ -334,7 +334,7 @@ namespace Greenshot.Base.Core DefaultValue = "16,16")] public NativeSize IconSize { - get { return _iconSize; } + get => _iconSize; set { Size newSize = value; diff --git a/src/Greenshot.Base/Core/CredentialsHelper.cs b/src/Greenshot.Base/Core/CredentialsHelper.cs index 5ec1e6ec0..20c9e3cd2 100644 --- a/src/Greenshot.Base/Core/CredentialsHelper.cs +++ b/src/Greenshot.Base/Core/CredentialsHelper.cs @@ -132,7 +132,7 @@ namespace Greenshot.Base.Core /// Gets or sets the name for the credentials. public string Name { - get { return _name; } + get => _name; set { if (value?.Length > CredUi.MAX_USERNAME_LENGTH) @@ -153,7 +153,7 @@ namespace Greenshot.Base.Core /// Gets or sets the password for the credentials. public string Password { - get { return _password; } + get => _password; set { if (value?.Length > CredUi.MAX_PASSWORD_LENGTH) @@ -181,7 +181,7 @@ namespace Greenshot.Base.Core /// Gets or sets the name of the target for the credentials, typically a server name. public string Target { - get { return _target; } + get => _target; set { if (value == null) @@ -208,7 +208,7 @@ namespace Greenshot.Base.Core /// A null value will cause a system default caption to be used. public string Caption { - get { return _caption; } + get => _caption; set { if (value?.Length > CredUi.MAX_CAPTION_LENGTH) @@ -230,7 +230,7 @@ namespace Greenshot.Base.Core /// A null value will cause a system default message to be used. public string Message { - get { return _message; } + get => _message; set { if (value?.Length > CredUi.MAX_MESSAGE_LENGTH) @@ -252,7 +252,7 @@ namespace Greenshot.Base.Core /// A null value will cause a system default image to be used. public Image Banner { - get { return _banner; } + get => _banner; set { if (value != null) diff --git a/src/Greenshot.Base/Core/FastBitmap.cs b/src/Greenshot.Base/Core/FastBitmap.cs index 7a184082b..f44408369 100644 --- a/src/Greenshot.Base/Core/FastBitmap.cs +++ b/src/Greenshot.Base/Core/FastBitmap.cs @@ -415,8 +415,8 @@ namespace Greenshot.Base.Core /// public int Left { - get { return 0; } - set { _left = value; } + get => 0; + set => _left = value; } /// @@ -424,8 +424,8 @@ namespace Greenshot.Base.Core /// int IFastBitmapWithOffset.Left { - get { return _left; } - set { _left = value; } + get => _left; + set => _left = value; } private int _top; @@ -435,8 +435,8 @@ namespace Greenshot.Base.Core /// public int Top { - get { return 0; } - set { _top = value; } + get => 0; + set => _top = value; } /// @@ -444,8 +444,8 @@ namespace Greenshot.Base.Core /// int IFastBitmapWithOffset.Top { - get { return _top; } - set { _top = value; } + get => _top; + set => _top = value; } /// diff --git a/src/Greenshot.Base/Core/Language.cs b/src/Greenshot.Base/Core/Language.cs index bd9fc3f62..c27da3950 100644 --- a/src/Greenshot.Base/Core/Language.cs +++ b/src/Greenshot.Base/Core/Language.cs @@ -36,7 +36,7 @@ namespace Greenshot.Base.Core /// This class supplies the GUI with translations, based upon keys. /// The language resources are loaded from the language files found on fixed or supplied paths /// - public class Language + public static class Language { private static readonly ILog Log = LogManager.GetLogger(typeof(Language)); private static readonly List LanguagePaths = new(); @@ -653,7 +653,7 @@ namespace Greenshot.Base.Core } /// - /// Get the resource for key, format with with string.format an supply the parameters + /// Get the resource for key, format with string.format an supply the parameters /// /// Enum /// object @@ -661,7 +661,7 @@ namespace Greenshot.Base.Core public static string GetFormattedString(Enum key, object param) => GetFormattedString(key.ToString(), param); /// - /// Get the resource for prefix.key, format with with string.format an supply the parameters + /// Get the resource for prefix.key, format with string.format an supply the parameters /// /// string /// Enum @@ -670,7 +670,7 @@ namespace Greenshot.Base.Core public static string GetFormattedString(string prefix, Enum key, object param) => GetFormattedString(prefix, key.ToString(), param); /// - /// Get the resource for prefix.key, format with with string.format an supply the parameters + /// Get the resource for prefix.key, format with string.format an supply the parameters /// /// string /// string @@ -679,7 +679,7 @@ namespace Greenshot.Base.Core public static string GetFormattedString(string prefix, string key, object param) => GetFormattedString(prefix + "." + key, param); /// - /// Get the resource for key, format with with string.format an supply the parameters + /// Get the resource for key, format with string.format an supply the parameters /// /// string /// object diff --git a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs index cfd240a98..2f855f2d3 100644 --- a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs +++ b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs @@ -47,7 +47,7 @@ namespace Greenshot.Base.Core.OAuth public string LoopbackCallbackUrl { get; set; } = "http://localhost:{0}/authorize/"; /// - /// HTML code to to return the _browser, default it will try to close the _browser / tab, this won't always work. + /// HTML code to return the _browser, default it will try to close the _browser / tab, this won't always work. /// You can use CloudServiceName where you want to show the CloudServiceName from your OAuth2 settings /// public string ClosePageResponse { get; set; } = @" diff --git a/src/Greenshot.Base/Core/OAuth/OAuth2Settings.cs b/src/Greenshot.Base/Core/OAuth/OAuth2Settings.cs index 42345c49c..0a06d7462 100644 --- a/src/Greenshot.Base/Core/OAuth/OAuth2Settings.cs +++ b/src/Greenshot.Base/Core/OAuth/OAuth2Settings.cs @@ -96,7 +96,7 @@ namespace Greenshot.Base.Core.OAuth public string AccessToken { get; set; } /// - /// Expire time for the AccessToken, this this time (-60 seconds) is passed a new AccessToken needs to be generated with the RefreshToken + /// Expire time for the AccessToken, this time (-60 seconds) is passed a new AccessToken needs to be generated with the RefreshToken /// public DateTimeOffset AccessTokenExpires { get; set; } diff --git a/src/Greenshot.Base/Core/WindowDetails.cs b/src/Greenshot.Base/Core/WindowDetails.cs index 39566c8cc..bea7c3475 100644 --- a/src/Greenshot.Base/Core/WindowDetails.cs +++ b/src/Greenshot.Base/Core/WindowDetails.cs @@ -400,10 +400,7 @@ namespace Greenshot.Base.Core /// public bool Iconic { - get - { - return User32Api.IsIconic(Handle) || Location.X <= -32000; - } + get => User32Api.IsIconic(Handle) || Location.X <= -32000; set { if (value) @@ -422,10 +419,7 @@ namespace Greenshot.Base.Core /// public bool Maximised { - get - { - return User32Api.IsZoomed(Handle); - } + get => User32Api.IsZoomed(Handle); set { if (value) @@ -623,7 +617,7 @@ namespace Greenshot.Base.Core User32Api.GetWindowPlacement(Handle, ref placement); return placement; } - set { User32Api.SetWindowPlacement(Handle, ref value); } + set => User32Api.SetWindowPlacement(Handle, ref value); } /// @@ -1116,12 +1110,11 @@ namespace Greenshot.Base.Core return false; } - foreach (string excludeProcess in ExcludeProcessesFromFreeze) + foreach (var _ in from string excludeProcess in ExcludeProcessesFromFreeze + where titleOrProcessname.ToLower().Contains(excludeProcess) + select new { }) { - if (titleOrProcessname.ToLower().Contains(excludeProcess)) - { - return false; - } + return false; } return true; @@ -1333,13 +1326,13 @@ namespace Greenshot.Base.Core return this; } + foreach (var childWindow in // Look into the child windows - foreach (var childWindow in Children) + from childWindow in Children + where childWindow.Contains(point) + select childWindow) { - if (childWindow.Contains(point)) - { - return childWindow.FindChildUnderPoint(point); - } + return childWindow.FindChildUnderPoint(point); } return this; @@ -1389,14 +1382,9 @@ namespace Greenshot.Base.Core public static IEnumerable GetVisibleWindows() { var screenBounds = DisplayInfo.ScreenBounds; - - foreach (var window in GetAllWindows()) - { - if (IsVisible(window, screenBounds)) - { - yield return window; - } - } + return from window in GetAllWindows() + where IsVisible(window, screenBounds) + select window; } /// @@ -1460,13 +1448,9 @@ namespace Greenshot.Base.Core /// List WindowDetails with all the top level windows public static IEnumerable GetTopLevelWindows() { - foreach (var possibleTopLevel in GetAllWindows()) - { - if (IsTopLevel(possibleTopLevel)) - { - yield return possibleTopLevel; - } - } + return from possibleTopLevel in GetAllWindows() + where IsTopLevel(possibleTopLevel) + select possibleTopLevel; } /// diff --git a/src/Greenshot.Base/IniFile/IniAttributes.cs b/src/Greenshot.Base/IniFile/IniAttributes.cs index 4d8e45245..2ab9907a8 100644 --- a/src/Greenshot.Base/IniFile/IniAttributes.cs +++ b/src/Greenshot.Base/IniFile/IniAttributes.cs @@ -30,9 +30,8 @@ namespace Greenshot.Base.IniFile public class IniSectionAttribute : Attribute { public IniSectionAttribute(string name) => Name = name; - - public string Description; public string Name { get; set; } + public string Description { get; set; } } /// diff --git a/src/Greenshot.Base/IniFile/IniValue.cs b/src/Greenshot.Base/IniFile/IniValue.cs index 34d776386..cef903ec5 100644 --- a/src/Greenshot.Base/IniFile/IniValue.cs +++ b/src/Greenshot.Base/IniFile/IniValue.cs @@ -57,10 +57,7 @@ namespace Greenshot.Base.IniFile /// public bool IsFixed { - get - { - return Attributes?.FixedValue == true; - } + get => Attributes?.FixedValue == true; set { if (Attributes != null) @@ -75,10 +72,7 @@ namespace Greenshot.Base.IniFile /// public bool IsExpert { - get - { - return Attributes?.Expert == true; - } + get => Attributes?.Expert == true; set { if (Attributes != null) @@ -115,10 +109,7 @@ namespace Greenshot.Base.IniFile /// public object Value { - get - { - return _propertyInfo == null ? _fieldInfo.GetValue(ContainingIniSection) : _propertyInfo.GetValue(ContainingIniSection, null); - } + get => _propertyInfo == null ? _fieldInfo.GetValue(ContainingIniSection) : _propertyInfo.GetValue(ContainingIniSection, null); set { if (_propertyInfo == null) diff --git a/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs b/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs index 7d867b1d7..e08acbc4c 100644 --- a/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs +++ b/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs @@ -72,12 +72,10 @@ namespace Greenshot.Base.Interfaces.Plugin public bool ReduceColors { - get - { + get => // Fix for Bug #3468436, force quantizing when output format is gif as this has only 256 colors! - return !(!OutputFormat.gif.Equals(Format) && !_reduceColors); - } - set { _reduceColors = value; } + !(!OutputFormat.gif.Equals(Format) && !_reduceColors); + set => _reduceColors = value; } /// @@ -85,7 +83,7 @@ namespace Greenshot.Base.Interfaces.Plugin /// public bool DisableReduceColors { - get { return _disableReduceColors; } + get => _disableReduceColors; set { // Quantizing os needed when output format is gif as this has only 256 colors! diff --git a/src/Greenshot.Base/Interop/COMWrapper.cs b/src/Greenshot.Base/Interop/COMWrapper.cs index 0ac8b10c2..73637a094 100644 --- a/src/Greenshot.Base/Interop/COMWrapper.cs +++ b/src/Greenshot.Base/Interop/COMWrapper.cs @@ -593,8 +593,8 @@ namespace Greenshot.Base.Interop /// public string TypeName { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); } } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Controls/BindableToolStripDropDownButton.cs b/src/Greenshot.Editor/Controls/BindableToolStripDropDownButton.cs index 60723c091..e21c4aa87 100644 --- a/src/Greenshot.Editor/Controls/BindableToolStripDropDownButton.cs +++ b/src/Greenshot.Editor/Controls/BindableToolStripDropDownButton.cs @@ -44,7 +44,7 @@ namespace Greenshot.Editor.Controls if (Tag == null && DropDownItems.Count > 0) Tag = DropDownItems[0].Tag; return Tag; } - set { AdoptFromTag(value); } + set => AdoptFromTag(value); } protected override void OnDropDownItemClicked(ToolStripItemClickedEventArgs e) diff --git a/src/Greenshot.Editor/Controls/ColorButton.cs b/src/Greenshot.Editor/Controls/ColorButton.cs index 6a01aeb62..3006250af 100644 --- a/src/Greenshot.Editor/Controls/ColorButton.cs +++ b/src/Greenshot.Editor/Controls/ColorButton.cs @@ -45,7 +45,7 @@ namespace Greenshot.Editor.Controls public Color SelectedColor { - get { return _selectedColor; } + get => _selectedColor; set { _selectedColor = value; diff --git a/src/Greenshot.Editor/Controls/FontFamilyComboBox.cs b/src/Greenshot.Editor/Controls/FontFamilyComboBox.cs index c9e8470f0..2b215c2ec 100644 --- a/src/Greenshot.Editor/Controls/FontFamilyComboBox.cs +++ b/src/Greenshot.Editor/Controls/FontFamilyComboBox.cs @@ -37,7 +37,7 @@ namespace Greenshot.Editor.Controls public FontFamily FontFamily { - get { return (FontFamily)SelectedItem; } + get => (FontFamily)SelectedItem; set { if (!SelectedItem.Equals(value)) diff --git a/src/Greenshot.Editor/Controls/Pipette.cs b/src/Greenshot.Editor/Controls/Pipette.cs index 830a7ab72..df483ab86 100644 --- a/src/Greenshot.Editor/Controls/Pipette.cs +++ b/src/Greenshot.Editor/Controls/Pipette.cs @@ -184,8 +184,9 @@ namespace Greenshot.Editor.Controls public class PipetteUsedArgs : EventArgs { - public Color Color; public PipetteUsedArgs(Color c) => Color = c; + + public Color Color { get; set; } } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Controls/ToolStripColorButton.cs b/src/Greenshot.Editor/Controls/ToolStripColorButton.cs index c0eae1707..03cd0afde 100644 --- a/src/Greenshot.Editor/Controls/ToolStripColorButton.cs +++ b/src/Greenshot.Editor/Controls/ToolStripColorButton.cs @@ -43,7 +43,7 @@ namespace Greenshot.Editor.Controls public Color SelectedColor { - get { return _selectedColor; } + get => _selectedColor; set { _selectedColor = value; diff --git a/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs b/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs index 7de612b60..dc6d9a992 100644 --- a/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs +++ b/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs @@ -39,32 +39,32 @@ namespace Greenshot.Editor.Controls public decimal Value { - get { return NumericUpDown.Value; } - set { NumericUpDown.Value = value; } + get => NumericUpDown.Value; + set => NumericUpDown.Value = value; } public decimal Minimum { - get { return NumericUpDown.Minimum; } - set { NumericUpDown.Minimum = value; } + get => NumericUpDown.Minimum; + set => NumericUpDown.Minimum = value; } public decimal Maximum { - get { return NumericUpDown.Maximum; } - set { NumericUpDown.Maximum = value; } + get => NumericUpDown.Maximum; + set => NumericUpDown.Maximum = value; } public decimal Increment { - get { return NumericUpDown.Increment; } - set { NumericUpDown.Increment = value; } + get => NumericUpDown.Increment; + set => NumericUpDown.Increment = value; } public int DecimalPlaces { - get { return NumericUpDown.DecimalPlaces; } - set { NumericUpDown.DecimalPlaces = value; } + get => NumericUpDown.DecimalPlaces; + set => NumericUpDown.DecimalPlaces = value; } protected override void OnSubscribeControlEvents(Control control) diff --git a/src/Greenshot.Editor/Drawing/CursorContainer.cs b/src/Greenshot.Editor/Drawing/CursorContainer.cs index 47076a3d4..7a314be54 100644 --- a/src/Greenshot.Editor/Drawing/CursorContainer.cs +++ b/src/Greenshot.Editor/Drawing/CursorContainer.cs @@ -65,7 +65,7 @@ namespace Greenshot.Editor.Drawing Width = value.Size.Width; Height = value.Size.Height; } - get { return cursor; } + get => cursor; } /// diff --git a/src/Greenshot.Editor/Drawing/DrawableContainerList.cs b/src/Greenshot.Editor/Drawing/DrawableContainerList.cs index f4804fa92..8d052751d 100644 --- a/src/Greenshot.Editor/Drawing/DrawableContainerList.cs +++ b/src/Greenshot.Editor/Drawing/DrawableContainerList.cs @@ -59,7 +59,7 @@ namespace Greenshot.Editor.Drawing public EditStatus Status { - get { return this[Count - 1].Status; } + get => this[Count - 1].Status; set { foreach (var dc in this) @@ -108,10 +108,7 @@ namespace Greenshot.Editor.Drawing /// public ISurface Parent { - get - { - return Count > 0 ? this[Count - 1].Parent : null; - } + get => Count > 0 ? this[Count - 1].Parent : null; set { ParentID = value?.ID ?? Guid.NewGuid(); diff --git a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs index 16b6ab273..42296ef97 100644 --- a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs +++ b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs @@ -48,8 +48,8 @@ namespace Greenshot.Editor.Drawing.Fields public event FieldChangedEventHandler FieldChanged { - add { _fieldChanged += value; } - remove { _fieldChanged -= value; } + add => _fieldChanged += value; + remove => _fieldChanged -= value; } // we keep two Collections of our fields, dictionary for quick access, list for serialization diff --git a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs index 1eba099f1..af9aeb076 100644 --- a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -41,11 +41,11 @@ namespace Greenshot.Editor.Drawing.Fields public event EventHandler ChildrenChanged { - add { childrenChanged += value; } - remove { childrenChanged -= value; } + add => childrenChanged += value; + remove => childrenChanged -= value; } - public IList Children = new List(); + public IList Children { get; set; } = new List(); protected AbstractFieldHolderWithChildren() => _fieldChangedEventHandler = OnFieldChanged; diff --git a/src/Greenshot.Editor/Drawing/Fields/Field.cs b/src/Greenshot.Editor/Drawing/Fields/Field.cs index 951ed6c58..673db9a71 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Field.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Field.cs @@ -38,7 +38,7 @@ namespace Greenshot.Editor.Drawing.Fields public object Value { - get { return _myValue; } + get => _myValue; set { if (!Equals(_myValue, value)) diff --git a/src/Greenshot.Editor/Drawing/Fields/FieldType.cs b/src/Greenshot.Editor/Drawing/Fields/FieldType.cs index 1a79fb6f9..31a932c96 100644 --- a/src/Greenshot.Editor/Drawing/Fields/FieldType.cs +++ b/src/Greenshot.Editor/Drawing/Fields/FieldType.cs @@ -53,14 +53,13 @@ namespace Greenshot.Editor.Drawing.Fields public static readonly IFieldType FLAGS = new FieldType(nameof(FLAGS)); public static readonly IFieldType CROPMODE = new FieldType(nameof(CROPMODE)); - public static IFieldType[] Values = + public string Name { get; set; } + public static IFieldType[] Values { get; set; } = { ARROWHEADS, BLUR_RADIUS, BRIGHTNESS, FILL_COLOR, FONT_BOLD, FONT_FAMILY, FONT_ITALIC, FONT_SIZE, TEXT_HORIZONTAL_ALIGNMENT, TEXT_VERTICAL_ALIGNMENT, HIGHLIGHT_COLOR, LINE_COLOR, LINE_THICKNESS, MAGNIFICATION_FACTOR, PIXEL_SIZE, PREVIEW_QUALITY, SHADOW, PREPARED_FILTER_OBFUSCATE, PREPARED_FILTER_HIGHLIGHT, FLAGS, CROPMODE }; - public string Name { get; set; } - private FieldType(string name) => Name = name; public override string ToString() => Name; diff --git a/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs b/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs index e1b9ea13b..93c66ab98 100644 --- a/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs @@ -40,15 +40,15 @@ namespace Greenshot.Editor.Drawing.Filters public event PropertyChangedEventHandler PropertyChanged { - add { propertyChanged += value; } - remove { propertyChanged -= value; } + add => propertyChanged += value; + remove => propertyChanged -= value; } private bool invert; public bool Invert { - get { return invert; } + get => invert; set { invert = value; @@ -60,8 +60,8 @@ namespace Greenshot.Editor.Drawing.Filters public DrawableContainer Parent { - get { return parent; } - set { parent = value; } + get => parent; + set => parent = value; } protected AbstractFilter(DrawableContainer parent) => this.parent = parent; diff --git a/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs b/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs index 9a90a0235..7781c4305 100644 --- a/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs @@ -37,7 +37,7 @@ namespace Greenshot.Editor.Drawing.Filters public double PreviewQuality { - get { return previewQuality; } + get => previewQuality; set { previewQuality = value; diff --git a/src/Greenshot.Editor/Drawing/ImageContainer.cs b/src/Greenshot.Editor/Drawing/ImageContainer.cs index e8f83c787..bd805c491 100644 --- a/src/Greenshot.Editor/Drawing/ImageContainer.cs +++ b/src/Greenshot.Editor/Drawing/ImageContainer.cs @@ -133,7 +133,7 @@ namespace Greenshot.Editor.Drawing Top -= _shadowOffset.Y; } } - get { return _image; } + get => _image; } /// diff --git a/src/Greenshot.Editor/Forms/ColorDialog.cs b/src/Greenshot.Editor/Forms/ColorDialog.cs index 7853788ca..0e0f4480e 100644 --- a/src/Greenshot.Editor/Forms/ColorDialog.cs +++ b/src/Greenshot.Editor/Forms/ColorDialog.cs @@ -61,8 +61,8 @@ namespace Greenshot.Editor.Forms public Color Color { - get { return colorPanel.BackColor; } - set { PreviewColor(value, this); } + get => colorPanel.BackColor; + set => PreviewColor(value, this); } private void CreateColorPalette(int x, int y, int w, int h) diff --git a/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs b/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs index c1c7421ca..adf10dbb7 100644 --- a/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs +++ b/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs @@ -33,7 +33,6 @@ namespace Greenshot.Editor.Forms public class ColorPickerToolStripButton : ToolStripButton { private Color _color; - public NativePoint Offset = new(0, 0); public event ColorPickerEventHandler ColorPicked; private readonly ColorDialog _cd; @@ -50,9 +49,11 @@ namespace Greenshot.Editor.Forms _color = value; Invalidate(); } - get { return _color; } + get => _color; } + public NativePoint Offset { get; set; } = new(0, 0); + protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); diff --git a/src/Greenshot.Editor/Forms/ImageEditorForm.cs b/src/Greenshot.Editor/Forms/ImageEditorForm.cs index 9afcca2cb..18ee68c3c 100644 --- a/src/Greenshot.Editor/Forms/ImageEditorForm.cs +++ b/src/Greenshot.Editor/Forms/ImageEditorForm.cs @@ -550,8 +550,8 @@ namespace Greenshot.Editor.Forms public ISurface Surface { - get { return _surface; } - set { SetSurface(value); } + get => _surface; + set => SetSurface(value); } public void SetImagePath(string fullpath) diff --git a/src/Greenshot.Editor/Helpers/ScaleHelper.cs b/src/Greenshot.Editor/Helpers/ScaleHelper.cs index 11be13231..814274853 100644 --- a/src/Greenshot.Editor/Helpers/ScaleHelper.cs +++ b/src/Greenshot.Editor/Helpers/ScaleHelper.cs @@ -55,7 +55,7 @@ namespace Greenshot.Editor.Helpers /// NativeRectFloat the bounds of the element to be aligned /// NativeRectFloat with the rectangle for alignment of the element /// the System.Drawing.ContentAlignment value indicating how the element is to be aligned should the width or height differ from targetSize - /// NativeRectFloat object with Location aligned aligned to targetRect + /// NativeRectFloat object with Location aligned to targetRect public static NativeRectFloat GetAlignedRectangle(NativeRectFloat currentRect, NativeRectFloat targetRect, ContentAlignment alignment) { var newRect = new NativeRectFloat(targetRect.Location, currentRect.Size); @@ -171,7 +171,7 @@ namespace Greenshot.Editor.Helpers } /// - /// For an original size, and a selected size, returns the the largest possible size that + /// For an original size, and a selected size, returns the largest possible size that /// * has the same aspect ratio as the original /// * fits into selected size /// diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs index e56140750..65240deb4 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs @@ -32,7 +32,7 @@ namespace Greenshot.Plugin.Confluence /// /// Description of ConfluenceUtils. /// - public class ConfluenceUtils + public static class ConfluenceUtils { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceUtils)); diff --git a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs index f29402c1d..f2c9a311f 100644 --- a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs +++ b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs @@ -38,7 +38,7 @@ namespace Greenshot.Plugin.Confluence public Type Type { - get { return _type; } + get => _type; set { if (!value.IsEnum) diff --git a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs index 3a90b2a60..64429e14c 100644 --- a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs +++ b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs @@ -110,7 +110,7 @@ namespace Greenshot.Plugin.Imgur.Forms listview_imgur_uploads.Columns.Add(column); } - foreach (ImgurInfo imgurInfo in Config.runtimeImgurHistory.Values) + foreach (ImgurInfo imgurInfo in Config.RuntimeImgurHistory.Values) { var item = new ListViewItem(imgurInfo.Hash) { @@ -211,7 +211,7 @@ namespace Greenshot.Plugin.Imgur.Forms DialogResult result = MessageBox.Show(Language.GetString("imgur", LangKey.clear_question), "Imgur", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { - Config.runtimeImgurHistory.Clear(); + Config.RuntimeImgurHistory.Clear(); Config.ImgurUploadHistory.Clear(); IniConfig.Save(); Redraw(); diff --git a/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs b/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs index 18f7b6e1f..40ef331b0 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs @@ -80,10 +80,8 @@ namespace Greenshot.Plugin.Imgur [IniProperty("ImgurUploadHistory", Description = "Imgur upload history (ImgurUploadHistory.hash=deleteHash)")] public Dictionary ImgurUploadHistory { get; set; } - - // Not stored, only run-time! - public Dictionary runtimeImgurHistory = new(); public int Credits { get; set; } + public Dictionary RuntimeImgurHistory { get; set; } = new(); /// /// Upgrade certain values diff --git a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs index 49eefced1..d86cc6542 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs @@ -38,7 +38,7 @@ namespace Greenshot.Plugin.Imgur public string DeleteHash { - get { return _deleteHash; } + get => _deleteHash; set { _deleteHash = value; @@ -66,7 +66,7 @@ namespace Greenshot.Plugin.Imgur public Image Image { - get { return _image; } + get => _image; set { _image?.Dispose(); diff --git a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs index 1d9aa9995..7bd327c72 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs @@ -190,7 +190,7 @@ namespace Greenshot.Plugin.Imgur { Log.InfoFormat("Storing imgur upload for hash {0} and delete hash {1}", imgurInfo.Hash, imgurInfo.DeleteHash); _config.ImgurUploadHistory.Add(imgurInfo.Hash, imgurInfo.DeleteHash); - _config.runtimeImgurHistory.Add(imgurInfo.Hash, imgurInfo); + _config.RuntimeImgurHistory.Add(imgurInfo.Hash, imgurInfo); UpdateHistoryMenuItem(); } } diff --git a/src/Greenshot.Plugin.Imgur/ImgurUtils.cs b/src/Greenshot.Plugin.Imgur/ImgurUtils.cs index 2ba81ea53..71fbb7a8a 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurUtils.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurUtils.cs @@ -48,8 +48,8 @@ namespace Greenshot.Plugin.Imgur public static bool IsHistoryLoadingNeeded() { Log.InfoFormat("Checking if imgur cache loading needed, configuration has {0} imgur hashes, loaded are {1} hashes.", Config.ImgurUploadHistory.Count, - Config.runtimeImgurHistory.Count); - return Config.runtimeImgurHistory.Count != Config.ImgurUploadHistory.Count; + Config.RuntimeImgurHistory.Count); + return Config.RuntimeImgurHistory.Count != Config.ImgurUploadHistory.Count; } /// @@ -67,7 +67,7 @@ namespace Greenshot.Plugin.Imgur // Load the ImUr history foreach (string hash in Config.ImgurUploadHistory.Keys.ToList()) { - if (Config.runtimeImgurHistory.ContainsKey(hash)) + if (Config.RuntimeImgurHistory.ContainsKey(hash)) { // Already loaded continue; @@ -80,13 +80,13 @@ namespace Greenshot.Plugin.Imgur if (imgurInfo != null) { RetrieveImgurThumbnail(imgurInfo); - Config.runtimeImgurHistory[hash] = imgurInfo; + Config.RuntimeImgurHistory[hash] = imgurInfo; } else { Log.InfoFormat("Deleting unknown ImgUr {0} from config, delete hash was {1}.", hash, deleteHash); Config.ImgurUploadHistory.Remove(hash); - Config.runtimeImgurHistory.Remove(hash); + Config.RuntimeImgurHistory.Remove(hash); saveNeeded = true; } } @@ -108,7 +108,7 @@ namespace Greenshot.Plugin.Imgur { Log.InfoFormat("ImgUr image for hash {0} is no longer available, removing it from the history", hash); Config.ImgurUploadHistory.Remove(hash); - Config.runtimeImgurHistory.Remove(hash); + Config.RuntimeImgurHistory.Remove(hash); redirected = true; } } @@ -346,7 +346,7 @@ namespace Greenshot.Plugin.Imgur } // Make sure we remove it from the history, if no error occurred - Config.runtimeImgurHistory.Remove(imgurInfo.Hash); + Config.RuntimeImgurHistory.Remove(imgurInfo.Hash); Config.ImgurUploadHistory.Remove(imgurInfo.Hash); imgurInfo.Image = null; } diff --git a/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs b/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs index 15aea3005..ccbc90e78 100644 --- a/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs @@ -27,6 +27,7 @@ using Greenshot.Base.Core; using Greenshot.Base.Interfaces; using Greenshot.Plugin.Office.OfficeExport; using Greenshot.Plugin.Office.OfficeExport.Entities; +using System.Linq; namespace Greenshot.Plugin.Office.Destinations { @@ -72,10 +73,8 @@ namespace Greenshot.Plugin.Office.Destinations public override IEnumerable DynamicDestinations() { - foreach (OneNotePage page in _oneNoteExporter.GetPages()) - { - yield return new OneNoteDestination(page); - } + return from OneNotePage page in _oneNoteExporter.GetPages() + select new OneNoteDestination(page); } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) diff --git a/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs b/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs index 52b407287..3bc0fcdae 100644 --- a/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs +++ b/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs @@ -51,8 +51,8 @@ namespace Greenshot.Plugin.Win10.Internal /// public ulong Size { - get { return (ulong)Length; } - set { SetLength((long)value); } + get => (ulong)Length; + set => SetLength((long)value); } /// diff --git a/src/Greenshot/Forms/CaptureForm.cs b/src/Greenshot/Forms/CaptureForm.cs index 737c43fa8..941ade58d 100644 --- a/src/Greenshot/Forms/CaptureForm.cs +++ b/src/Greenshot/Forms/CaptureForm.cs @@ -944,25 +944,26 @@ namespace Greenshot.Forms using var pen = new Pen(Color.Red); var highlightColor = Color.FromArgb(128, Color.Yellow); using var highlightTextBrush = new SolidBrush(highlightColor); - foreach (var line in ocrInfo.Lines) + foreach (var (line, lineBounds) in from line in ocrInfo.Lines + let lineBounds = line.CalculatedBounds + select (line, lineBounds)) { - var lineBounds = line.CalculatedBounds; if (lineBounds.IsEmpty) { continue; } + graphics.DrawRectangle(pen, line.CalculatedBounds); if (_mouseDown) { // Highlight the text which is selected if (lineBounds.IntersectsWith(_captureRect)) { - foreach (var word in line.Words) + foreach (var word in from word in line.Words + where word.Bounds.IntersectsWith(_captureRect) + select word) { - if (word.Bounds.IntersectsWith(_captureRect)) - { - graphics.FillRectangle(highlightTextBrush, word.Bounds); - } + graphics.FillRectangle(highlightTextBrush, word.Bounds); } } } diff --git a/src/Greenshot/Forms/MainForm.cs b/src/Greenshot/Forms/MainForm.cs index 30e8a5ad5..61ff645f1 100644 --- a/src/Greenshot/Forms/MainForm.cs +++ b/src/Greenshot/Forms/MainForm.cs @@ -67,7 +67,6 @@ namespace Greenshot.Forms private static ILog LOG; private static ResourceMutex _applicationMutex; private static CoreConfiguration _conf; - public static string LogFileLocation; public static void Start(string[] arguments) { @@ -378,6 +377,8 @@ namespace Greenshot.Forms // Timer for the double click test private readonly Timer _doubleClickTimer = new(); + public static string LogFileLocation { get; set; } + public MainForm(CopyDataTransport dataTransport) { var uiContext = TaskScheduler.FromCurrentSynchronizationContext(); diff --git a/src/Greenshot/Helpers/IEInterop/IEContainer.cs b/src/Greenshot/Helpers/IEInterop/IEContainer.cs index 56bb535b4..ee9342a16 100644 --- a/src/Greenshot/Helpers/IEInterop/IEContainer.cs +++ b/src/Greenshot/Helpers/IEInterop/IEContainer.cs @@ -514,14 +514,14 @@ namespace Greenshot.Helpers.IEInterop public int DestinationLeft { - get { return DestinationLocation.X; } - set { DestinationLocation = DestinationLocation.ChangeX(value); } + get => DestinationLocation.X; + set => DestinationLocation = DestinationLocation.ChangeX(value); } public int DestinationTop { - get { return DestinationLocation.Y; } - set { DestinationLocation = DestinationLocation.ChangeY(value); } + get => DestinationLocation.Y; + set => DestinationLocation = DestinationLocation.ChangeY(value); } public int DestinationRight => DestinationLocation.X + ScrollWidth; @@ -530,14 +530,14 @@ namespace Greenshot.Helpers.IEInterop public int ScrollLeft { - get { return ScaleX(GetAttributeAsInt("scrollLeft")); } - set { SetAttribute("scrollLeft", UnscaleX(value)); } + get => ScaleX(GetAttributeAsInt("scrollLeft")); + set => SetAttribute("scrollLeft", UnscaleX(value)); } public int ScrollTop { - get { return ScaleY(GetAttributeAsInt("scrollTop")); } - set { SetAttribute("scrollTop", UnscaleY(value)); } + get => ScaleY(GetAttributeAsInt("scrollTop")); + set => SetAttribute("scrollTop", UnscaleY(value)); } public IList Frames { get; } = new List(); diff --git a/src/Greenshot/Helpers/MailHelper.cs b/src/Greenshot/Helpers/MailHelper.cs index a0285885b..383444053 100644 --- a/src/Greenshot/Helpers/MailHelper.cs +++ b/src/Greenshot/Helpers/MailHelper.cs @@ -441,20 +441,10 @@ namespace Greenshot.Helpers /// public class Recipient { - /// - /// The email address of this recipient. - /// - public string Address; - /// - /// The display name of this recipient. - /// - public string DisplayName; - - /// - /// How the recipient will receive this message (To, CC, BCC). - /// - public MapiMailMessage.RecipientType RecipientType = MapiMailMessage.RecipientType.To; + public string Address { get; set; } + public string DisplayName { get; set; } + public MapiMailMessage.RecipientType RecipientType { get; set; } /// /// Creates a new recipient with the specified address and recipient type. diff --git a/src/Greenshot/Helpers/UpdateService.cs b/src/Greenshot/Helpers/UpdateService.cs index 11d803062..92d305d1d 100644 --- a/src/Greenshot/Helpers/UpdateService.cs +++ b/src/Greenshot/Helpers/UpdateService.cs @@ -69,10 +69,7 @@ namespace Greenshot.Helpers /// public bool IsBetaUpdateAvailable => LatestBetaVersion > CurrentVersion; - /// - /// Keep track of when the update was shown, so it won't be every few minutes - /// - public DateTimeOffset LastUpdateShown = DateTimeOffset.MinValue; + public DateTimeOffset LastUpdateShown { get; set; } = DateTimeOffset.MinValue; /// /// Constructor with dependencies