Merge branch 'release/1.2.9'

# Conflicts:
#	Greenshot/Languages/language-cs-CZ.xml
#	Greenshot/releases/additional_files/readme.txt.template
#	GreenshotImgurPlugin/Forms/ImgurHistory.cs
#	GreenshotImgurPlugin/Forms/SettingsForm.cs
#	GreenshotImgurPlugin/ImgurConfiguration.cs
#	GreenshotImgurPlugin/ImgurPlugin.cs
#	GreenshotImgurPlugin/ImgurUtils.cs
#	GreenshotPlugin/Core/CoreConfiguration.cs
#	GreenshotPlugin/Core/ImageHelper.cs
#	GreenshotPlugin/Core/SourceForgeHelper.cs
#	GreenshotPlugin/GreenshotPlugin.csproj
#	appveyor12.yml
This commit is contained in:
Robin 2017-01-01 07:41:09 +01:00
commit 5d56bfab66
635 changed files with 20621 additions and 30686 deletions

233
.gitignore vendored
View file

@ -1,24 +1,211 @@
.svn/ ## Ignore Visual Studio temporary files, build results, and
*.gsp ## files generated by popular Visual Studio add-ons.
*.bak
Greenshot*INSTALLER*.exe
Greenshot*INSTALLER*.zip
*.paf.exe
*-SVN.*
/Greenshot*/bin/
obj/
fugue/
*Credentials.private.cs
*Credentials.orig.cs
/Greenshot/UpgradeLog*.htm
/Greenshot/UpgradeLog*.XML
/Greenshot/_UpgradeReport_Files/*
*.log
/Greenshot/releases/additional_files/readme.txt
/*.error
/Greenshot/releases/innosetup/setup.iss
/Greenshot/packages
/Greenshot/releases/appinfo.ini
/Greenshot/Backup*
/Greenshot/tools/PortableApps.comInstaller/Data/PortableApps.comInstallerLog.txt # User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
## TODO: Comment the next line if you want to checkin your
## web deploy settings but do note that will include unencrypted
## passwords
#*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# LightSwitch generated files
GeneratedArtifacts/
_Pvt_Extensions/
ModelManifest.xml

View file

@ -1,37 +1,40 @@
 
Microsoft Visual Studio Solution File, Format Version 11.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2010 # Visual Studio 14
# SharpDevelop 4.2.2.8818 VisualStudioVersion = 14.0.25420.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Greenshot", "Greenshot.csproj", "{CD642BF4-D815-4D67-A0B5-C69F0B8231AF}" MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Greenshot", "Greenshot\Greenshot.csproj", "{CD642BF4-D815-4D67-A0B5-C69F0B8231AF}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotPlugin", "..\GreenshotPlugin\GreenshotPlugin.csproj", "{5B924697-4DCD-4F98-85F1-105CB84B7341}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotPlugin", "GreenshotPlugin\GreenshotPlugin.csproj", "{5B924697-4DCD-4F98-85F1-105CB84B7341}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotExternalCommandPlugin", "..\GreenshotExternalCommandPlugin\GreenshotExternalCommandPlugin.csproj", "{47F23C86-604E-4CC3-8767-B3D4088F30BB}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotExternalCommandPlugin", "GreenshotExternalCommandPlugin\GreenshotExternalCommandPlugin.csproj", "{47F23C86-604E-4CC3-8767-B3D4088F30BB}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotConfluencePlugin", "..\GreenshotConfluencePlugin\GreenshotConfluencePlugin.csproj", "{C3052651-598A-44E2-AAB3-2E41311D50F9}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotConfluencePlugin", "GreenshotConfluencePlugin\GreenshotConfluencePlugin.csproj", "{C3052651-598A-44E2-AAB3-2E41311D50F9}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotImgurPlugin", "..\GreenshotImgurPlugin\GreenshotImgurPlugin.csproj", "{80D8DEB9-94E3-4876-8CCA-2DF1ED5F2C50}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotImgurPlugin", "GreenshotImgurPlugin\GreenshotImgurPlugin.csproj", "{80D8DEB9-94E3-4876-8CCA-2DF1ED5F2C50}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotJiraPlugin", "..\GreenshotJiraPlugin\GreenshotJiraPlugin.csproj", "{19FEEF09-313F-43C7-819D-F1BCA782B08B}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotJiraPlugin", "GreenshotJiraPlugin\GreenshotJiraPlugin.csproj", "{19FEEF09-313F-43C7-819D-F1BCA782B08B}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotOCRPlugin", "..\GreenshotOCRPlugin\GreenshotOCRPlugin.csproj", "{C6988EE8-2FEE-4349-9F09-F9628A0D8965}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotOCRPlugin", "GreenshotOCRPlugin\GreenshotOCRPlugin.csproj", "{C6988EE8-2FEE-4349-9F09-F9628A0D8965}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotOCRCommand", "..\GreenshotOCRCommand\GreenshotOCRCommand.csproj", "{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotOCRCommand", "GreenshotOCRCommand\GreenshotOCRCommand.csproj", "{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}"
ProjectSection(ProjectDependencies) = postProject ProjectSection(ProjectDependencies) = postProject
{C6988EE8-2FEE-4349-9F09-F9628A0D8965} = {C6988EE8-2FEE-4349-9F09-F9628A0D8965} {C6988EE8-2FEE-4349-9F09-F9628A0D8965} = {C6988EE8-2FEE-4349-9F09-F9628A0D8965}
EndProjectSection EndProjectSection
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotBoxPlugin", "..\GreenshotBoxPlugin\GreenshotBoxPlugin.csproj", "{697CF066-9077-4F22-99D9-D989CCE7282B}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotBoxPlugin", "GreenshotBoxPlugin\GreenshotBoxPlugin.csproj", "{697CF066-9077-4F22-99D9-D989CCE7282B}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotDropboxPlugin", "..\GreenshotDropboxPlugin\GreenshotDropboxPlugin.csproj", "{AD7CFFE2-40E7-46CF-A172-D48CF7AE9A12}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotDropboxPlugin", "GreenshotDropboxPlugin\GreenshotDropboxPlugin.csproj", "{AD7CFFE2-40E7-46CF-A172-D48CF7AE9A12}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotFlickrPlugin", "..\GreenshotFlickrPlugin\GreenshotFlickrPlugin.csproj", "{7EC72A5A-D73A-4B4B-9CA1-2216C7D92D5E}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotFlickrPlugin", "GreenshotFlickrPlugin\GreenshotFlickrPlugin.csproj", "{7EC72A5A-D73A-4B4B-9CA1-2216C7D92D5E}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotPicasaPlugin", "..\GreenshotPicasaPlugin\GreenshotPicasaPlugin.csproj", "{1893A2E4-A78A-4713-A8E7-E70058DABEE0}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotPicasaPlugin", "GreenshotPicasaPlugin\GreenshotPicasaPlugin.csproj", "{1893A2E4-A78A-4713-A8E7-E70058DABEE0}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotOfficePlugin", "..\GreenshotOfficePlugin\GreenshotOfficePlugin.csproj", "{92599C09-FF29-4ABD-B6E6-C48ECD781BAB}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotOfficePlugin", "GreenshotOfficePlugin\GreenshotOfficePlugin.csproj", "{92599C09-FF29-4ABD-B6E6-C48ECD781BAB}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotPhotobucketPlugin", "..\GreenshotPhotobucketPlugin\GreenshotPhotobucketPlugin.csproj", "{9C0ECC4C-7807-4111-916A-4F57BB29788A}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotPhotobucketPlugin", "GreenshotPhotobucketPlugin\GreenshotPhotobucketPlugin.csproj", "{9C0ECC4C-7807-4111-916A-4F57BB29788A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotWin10Plugin", "GreenshotWin10Plugin\GreenshotWin10Plugin.csproj", "{9801F62C-540F-4BFE-9211-6405DEDE563B}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -107,6 +110,7 @@ Global
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|x86.ActiveCfg = Release|x86 {C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|x86.ActiveCfg = Release|x86
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Any CPU.ActiveCfg = Debug|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Any CPU.ActiveCfg = Debug|x86
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Any CPU.Build.0 = Debug|x86
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.ActiveCfg = Debug|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.ActiveCfg = Debug|x86
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.Build.0 = Debug|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.Build.0 = Debug|x86
@ -175,6 +179,16 @@ Global
{9C0ECC4C-7807-4111-916A-4F57BB29788A}.Release|Mixed Platforms.Build.0 = Release|Any CPU {9C0ECC4C-7807-4111-916A-4F57BB29788A}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{9C0ECC4C-7807-4111-916A-4F57BB29788A}.Release|x86.ActiveCfg = Release|x86 {9C0ECC4C-7807-4111-916A-4F57BB29788A}.Release|x86.ActiveCfg = Release|x86
{9C0ECC4C-7807-4111-916A-4F57BB29788A}.Release|x86.Build.0 = Release|x86 {9C0ECC4C-7807-4111-916A-4F57BB29788A}.Release|x86.Build.0 = Release|x86
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Debug|x86.ActiveCfg = Debug|Any CPU
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Debug|x86.Build.0 = Debug|Any CPU
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Release|x86.ActiveCfg = Release|Any CPU
{9801F62C-540F-4BFE-9211-6405DEDE563B}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,7 +21,6 @@
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -25,7 +25,8 @@ using System.Drawing;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
using Greenshot.IniFile; using Greenshot.IniFile;
using Greenshot.Core; using GreenshotPlugin.Effects;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Configuration { namespace Greenshot.Configuration {
/// <summary> /// <summary>
@ -34,35 +35,35 @@ namespace Greenshot.Configuration {
[IniSection("Editor", Description="Greenshot editor configuration")] [IniSection("Editor", Description="Greenshot editor configuration")]
public class EditorConfiguration : IniSection { public class EditorConfiguration : IniSection {
[IniProperty("RecentColors", Separator="|", Description="Last used colors")] [IniProperty("RecentColors", Separator="|", Description="Last used colors")]
public List<Color> RecentColors; public List<Color> RecentColors { get; set; }
[IniProperty("LastFieldValue", Separator="|", Description="Field values, make sure the last used settings are re-used")] [IniProperty("LastFieldValue", Separator="|", Description="Field values, make sure the last used settings are re-used")]
public Dictionary<string, object> LastUsedFieldValues; public Dictionary<string, object> LastUsedFieldValues { get; set; }
[IniProperty("MatchSizeToCapture", Description="Match the editor window size to the capture", DefaultValue="True")] [IniProperty("MatchSizeToCapture", Description="Match the editor window size to the capture", DefaultValue="True")]
public bool MatchSizeToCapture; public bool MatchSizeToCapture { get; set; }
[IniProperty("WindowPlacementFlags", Description="Placement flags", DefaultValue="0")] [IniProperty("WindowPlacementFlags", Description="Placement flags", DefaultValue="0")]
public WindowPlacementFlags WindowPlacementFlags; public WindowPlacementFlags WindowPlacementFlags { get; set; }
[IniProperty("WindowShowCommand", Description="Show command", DefaultValue="Normal")] [IniProperty("WindowShowCommand", Description="Show command", DefaultValue="Normal")]
public ShowWindowCommand ShowWindowCommand; public ShowWindowCommand ShowWindowCommand { get; set; }
[IniProperty("WindowMinPosition", Description="Position of minimized window", DefaultValue="-1,-1")] [IniProperty("WindowMinPosition", Description="Position of minimized window", DefaultValue="-1,-1")]
public Point WindowMinPosition; public Point WindowMinPosition { get; set; }
[IniProperty("WindowMaxPosition", Description="Position of maximized window", DefaultValue="-1,-1")] [IniProperty("WindowMaxPosition", Description="Position of maximized window", DefaultValue="-1,-1")]
public Point WindowMaxPosition; public Point WindowMaxPosition { get; set; }
[IniProperty("WindowNormalPosition", Description="Position of normal window", DefaultValue="100,100,400,400")] [IniProperty("WindowNormalPosition", Description="Position of normal window", DefaultValue="100,100,400,400")]
public Rectangle WindowNormalPosition; public Rectangle WindowNormalPosition { get; set; }
[IniProperty("ReuseEditor", Description = "Reuse already open editor", DefaultValue = "false")] [IniProperty("ReuseEditor", Description = "Reuse already open editor", DefaultValue = "false")]
public bool ReuseEditor; public bool ReuseEditor { get; set; }
[IniProperty("FreehandSensitivity", Description = "The smaller this number, the less smoothing is used. Decrease for detailed drawing, e.g. when using a pen. Increase for smoother lines. e.g. when you want to draw a smooth line.", DefaultValue = "3")] [IniProperty("FreehandSensitivity", Description = "The smaller this number, the less smoothing is used. Decrease for detailed drawing, e.g. when using a pen. Increase for smoother lines. e.g. when you want to draw a smooth line.", DefaultValue = "3")]
public int FreehandSensitivity; public int FreehandSensitivity { get; set; }
[IniProperty("SuppressSaveDialogAtClose", Description="Suppressed the 'do you want to save' dialog when closing the editor.", DefaultValue="False")] [IniProperty("SuppressSaveDialogAtClose", Description="Suppressed the 'do you want to save' dialog when closing the editor.", DefaultValue="False")]
public bool SuppressSaveDialogAtClose; public bool SuppressSaveDialogAtClose { get; set; }
[IniProperty("DropShadowEffectSettings", Description = "Settings for the drop shadow effect.")] [IniProperty("DropShadowEffectSettings", Description = "Settings for the drop shadow effect.")]
public DropShadowEffect DropShadowEffectSettings; public DropShadowEffect DropShadowEffectSettings { get; set; }
[IniProperty("TornEdgeEffectSettings", Description = "Settings for the torn edge effect.")] [IniProperty("TornEdgeEffectSettings", Description = "Settings for the torn edge effect.")]
public TornEdgeEffect TornEdgeEffectSettings; public TornEdgeEffect TornEdgeEffectSettings { get; set; }
public override void AfterLoad() { public override void AfterLoad() {
base.AfterLoad(); base.AfterLoad();
@ -73,9 +74,10 @@ namespace Greenshot.Configuration {
/// <param name="requestingType">Type of the class for which to create the field</param> /// <param name="requestingType">Type of the class for which to create the field</param>
/// <param name="fieldType">FieldType of the field to construct</param> /// <param name="fieldType">FieldType of the field to construct</param>
/// <param name="scope">FieldType of the field to construct</param> /// <param name="preferredDefaultValue"></param>
/// <returns>a new Field of the given fieldType, with the scope of it's value being restricted to the Type scope</returns> /// <returns>a new Field of the given fieldType, with the scope of it's value being restricted to the Type scope</returns>
public Field CreateField(Type requestingType, FieldType fieldType, object preferredDefaultValue) { public IField CreateField(Type requestingType, IFieldType fieldType, object preferredDefaultValue)
{
string requestingTypeName = requestingType.Name; string requestingTypeName = requestingType.Name;
string requestedField = requestingTypeName + "." + fieldType.Name; string requestedField = requestingTypeName + "." + fieldType.Name;
object fieldValue = preferredDefaultValue; object fieldValue = preferredDefaultValue;
@ -97,12 +99,14 @@ namespace Greenshot.Configuration {
} else { } else {
LastUsedFieldValues.Add(requestedField, fieldValue); LastUsedFieldValues.Add(requestedField, fieldValue);
} }
Field returnField = new Field(fieldType, requestingType); return new Field(fieldType, requestingType)
returnField.Value = fieldValue; {
return returnField; Value = fieldValue
};
} }
public void UpdateLastFieldValue(Field field) { public void UpdateLastFieldValue(IField field)
{
string requestedField = field.Scope + "." + field.FieldType.Name; string requestedField = field.Scope + "." + field.FieldType.Name;
// Check if the configuration exists // Check if the configuration exists
if (LastUsedFieldValues == null) { if (LastUsedFieldValues == null) {
@ -110,12 +114,21 @@ namespace Greenshot.Configuration {
} }
// check if settings for the requesting type exist, if not create! // check if settings for the requesting type exist, if not create!
if (LastUsedFieldValues.ContainsKey(requestedField)) { if (LastUsedFieldValues.ContainsKey(requestedField)) {
LastUsedFieldValues[requestedField] = field.myValue; LastUsedFieldValues[requestedField] = field.Value;
} else { } else {
LastUsedFieldValues.Add(requestedField, field.myValue); LastUsedFieldValues.Add(requestedField, field.Value);
} }
} }
public void ResetEditorPlacement()
{
WindowNormalPosition = new Rectangle(100, 100, 400, 400);
WindowMaxPosition = new Point(-1,-1);
WindowMinPosition = new Point(-1, -1);
WindowPlacementFlags = 0;
ShowWindowCommand = ShowWindowCommand.Normal;
}
public WindowPlacement GetEditorPlacement() { public WindowPlacement GetEditorPlacement() {
WindowPlacement placement = WindowPlacement.Default; WindowPlacement placement = WindowPlacement.Default;
placement.NormalPosition = new RECT(WindowNormalPosition); placement.NormalPosition = new RECT(WindowNormalPosition);

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -19,7 +19,10 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System.Diagnostics.CodeAnalysis;
namespace Greenshot.Configuration { namespace Greenshot.Configuration {
[SuppressMessage("ReSharper", "InconsistentNaming")]
public enum LangKey { public enum LangKey {
none, none,
about_bugs, about_bugs,

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -36,12 +36,14 @@ namespace Greenshot.Controls {
set; set;
} }
public BindableToolStripButton() :base() { public BindableToolStripButton()
{
CheckedChanged += BindableToolStripButton_CheckedChanged; CheckedChanged += BindableToolStripButton_CheckedChanged;
} }
void BindableToolStripButton_CheckedChanged(object sender, EventArgs e) { private void BindableToolStripButton_CheckedChanged(object sender, EventArgs e)
if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Checked")); {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Checked"));
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -36,15 +36,14 @@ namespace Greenshot.Controls {
set; set;
} }
public BindableToolStripComboBox() :base() { public BindableToolStripComboBox()
{
SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged;
} }
void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) { private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e)
if(PropertyChanged != null) { {
PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedItem"));
}
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -38,9 +38,6 @@ namespace Greenshot.Controls {
set; set;
} }
public BindableToolStripDropDownButton() {
}
public object SelectedTag { public object SelectedTag {
get { if(Tag==null && DropDownItems.Count>0) Tag=DropDownItems[0].Tag; return Tag; } get { if(Tag==null && DropDownItems.Count>0) Tag=DropDownItems[0].Tag; return Tag; }
set { AdoptFromTag(value); } set { AdoptFromTag(value); }
@ -51,7 +48,7 @@ namespace Greenshot.Controls {
if(Tag == null || !Tag.Equals(clickedItem.Tag)) { if(Tag == null || !Tag.Equals(clickedItem.Tag)) {
Tag = clickedItem.Tag; Tag = clickedItem.Tag;
Image = clickedItem.Image; Image = clickedItem.Image;
if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SelectedTag")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedTag"));
} }
base.OnDropDownItemClicked(e); base.OnDropDownItemClicked(e);
} }
@ -66,7 +63,7 @@ namespace Greenshot.Controls {
} }
} }
Tag = tag; Tag = tag;
if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SelectedTag")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedTag"));
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -31,7 +31,7 @@ namespace Greenshot.Controls {
/// </summary> /// </summary>
public class ColorButton : Button, IGreenshotLanguageBindable { public class ColorButton : Button, IGreenshotLanguageBindable {
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;
private Color selectedColor = Color.White; private Color _selectedColor = Color.White;
[Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")] [Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")]
public string LanguageKey { public string LanguageKey {
@ -44,9 +44,9 @@ namespace Greenshot.Controls {
} }
public Color SelectedColor { public Color SelectedColor {
get {return selectedColor;} get {return _selectedColor;}
set { set {
selectedColor = value; _selectedColor = value;
Brush brush; Brush brush;
if(value != Color.Transparent) { if(value != Color.Transparent) {
@ -67,19 +67,21 @@ namespace Greenshot.Controls {
} }
} }
void ColorButtonClick(object sender, EventArgs e) { private void ColorButtonClick(object sender, EventArgs e) {
ColorDialog colorDialog = ColorDialog.GetInstance(); ColorDialog colorDialog = ColorDialog.GetInstance();
colorDialog.Color = SelectedColor; colorDialog.Color = SelectedColor;
// Using the parent to make sure the dialog doesn't show on another window // Using the parent to make sure the dialog doesn't show on another window
colorDialog.ShowDialog(Parent.Parent); colorDialog.ShowDialog(Parent.Parent);
if (colorDialog.DialogResult != DialogResult.Cancel) { if (colorDialog.DialogResult == DialogResult.Cancel)
if (!colorDialog.Color.Equals(SelectedColor)) { {
return;
}
if (colorDialog.Color.Equals(SelectedColor))
{
return;
}
SelectedColor = colorDialog.Color; SelectedColor = colorDialog.Color;
if(PropertyChanged != null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedColor"));
PropertyChanged(this, new PropertyChangedEventArgs("SelectedColor"));
}
}
}
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -22,7 +22,6 @@
using Greenshot.IniFile; using Greenshot.IniFile;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms; using System.Windows.Forms;
namespace Greenshot.Controls { namespace Greenshot.Controls {
@ -30,18 +29,16 @@ namespace Greenshot.Controls {
/// ToolStripProfessionalRenderer which draws the Check correctly when the icons are larger /// ToolStripProfessionalRenderer which draws the Check correctly when the icons are larger
/// </summary> /// </summary>
public class ContextMenuToolStripProfessionalRenderer : ToolStripProfessionalRenderer { public class ContextMenuToolStripProfessionalRenderer : ToolStripProfessionalRenderer {
private static CoreConfiguration coreConfiguration = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private static Image scaledCheckbox; private static Image _scaledCheckbox;
protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) {
if (scaledCheckbox == null || scaledCheckbox.Size != coreConfiguration.IconSize) { if (_scaledCheckbox == null || _scaledCheckbox.Size != CoreConfig.IconSize) {
if (scaledCheckbox != null) { _scaledCheckbox?.Dispose();
scaledCheckbox.Dispose(); _scaledCheckbox = ImageHelper.ResizeImage(e.Image, true, CoreConfig.IconSize.Width, CoreConfig.IconSize.Height, null);
}
scaledCheckbox = ImageHelper.ResizeImage(e.Image, true, coreConfiguration.IconSize.Width, coreConfiguration.IconSize.Height, null);
} }
Rectangle old = e.ImageRectangle; Rectangle old = e.ImageRectangle;
ToolStripItemImageRenderEventArgs clone = new ToolStripItemImageRenderEventArgs(e.Graphics, e.Item, scaledCheckbox, new Rectangle(old.X, 0, old.Width, old.Height)); ToolStripItemImageRenderEventArgs clone = new ToolStripItemImageRenderEventArgs(e.Graphics, e.Item, _scaledCheckbox, new Rectangle(old.X, 0, old.Width, old.Height));
base.OnRenderItemCheck(clone); base.OnRenderItemCheck(clone);
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -41,15 +41,19 @@ namespace Greenshot.Controls {
} }
} }
public FontFamilyComboBox() : base() { public FontFamilyComboBox()
{
if (ComboBox != null)
{
ComboBox.DataSource = FontFamily.Families; ComboBox.DataSource = FontFamily.Families;
ComboBox.DisplayMember = "Name"; ComboBox.DisplayMember = "Name";
SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged;
ComboBox.DrawMode = DrawMode.OwnerDrawFixed; ComboBox.DrawMode = DrawMode.OwnerDrawFixed;
ComboBox.DrawItem += ComboBox_DrawItem; ComboBox.DrawItem += ComboBox_DrawItem;
} }
}
void ComboBox_DrawItem(object sender, DrawItemEventArgs e) { private void ComboBox_DrawItem(object sender, DrawItemEventArgs e) {
// DrawBackground handles drawing the background (i.e,. hot-tracked v. not) // DrawBackground handles drawing the background (i.e,. hot-tracked v. not)
// It uses the system colors (Bluish, and and white, by default) // It uses the system colors (Bluish, and and white, by default)
// same as calling e.Graphics.FillRectangle ( SystemBrushes.Highlight, e.Bounds ); // same as calling e.Graphics.FillRectangle ( SystemBrushes.Highlight, e.Bounds );
@ -58,7 +62,7 @@ namespace Greenshot.Controls {
if (e.Index > -1) { if (e.Index > -1) {
FontFamily fontFamily = Items[e.Index] as FontFamily; FontFamily fontFamily = Items[e.Index] as FontFamily;
FontStyle fontStyle = FontStyle.Regular; FontStyle fontStyle = FontStyle.Regular;
if (!fontFamily.IsStyleAvailable(FontStyle.Regular)) { if (fontFamily != null && !fontFamily.IsStyleAvailable(FontStyle.Regular)) {
if (fontFamily.IsStyleAvailable(FontStyle.Bold)) { if (fontFamily.IsStyleAvailable(FontStyle.Bold)) {
fontStyle = FontStyle.Bold; fontStyle = FontStyle.Bold;
} else if (fontFamily.IsStyleAvailable(FontStyle.Italic)) { } else if (fontFamily.IsStyleAvailable(FontStyle.Italic)) {
@ -70,12 +74,18 @@ namespace Greenshot.Controls {
} }
} }
try { try {
if (fontFamily != null)
{
DrawText(e.Graphics, fontFamily, fontStyle, e.Bounds, fontFamily.Name); DrawText(e.Graphics, fontFamily, fontStyle, e.Bounds, fontFamily.Name);
}
} catch { } catch {
// If the drawing failed, BUG-1770 seems to have a weird case that causes: Font 'Lucida Sans Typewriter' does not support style 'Regular' // If the drawing failed, BUG-1770 seems to have a weird case that causes: Font 'Lucida Sans Typewriter' does not support style 'Regular'
if (fontFamily != null)
{
DrawText(e.Graphics, FontFamily.GenericSansSerif, FontStyle.Regular, e.Bounds, fontFamily.Name); DrawText(e.Graphics, FontFamily.GenericSansSerif, FontStyle.Regular, e.Bounds, fontFamily.Name);
} }
} }
}
// Uncomment this if you actually like the way the focus rectangle looks // Uncomment this if you actually like the way the focus rectangle looks
//e.DrawFocusRectangle (); //e.DrawFocusRectangle ();
} }
@ -89,7 +99,7 @@ namespace Greenshot.Controls {
/// <param name="bounds"></param> /// <param name="bounds"></param>
/// <param name="text"></param> /// <param name="text"></param>
private void DrawText(Graphics graphics, FontFamily fontFamily, FontStyle fontStyle, Rectangle bounds, string text) { private void DrawText(Graphics graphics, FontFamily fontFamily, FontStyle fontStyle, Rectangle bounds, string text) {
using (Font font = new Font(fontFamily, this.Font.Size + 5, fontStyle, GraphicsUnit.Pixel)) { using (Font font = new Font(fontFamily, Font.Size + 5, fontStyle, GraphicsUnit.Pixel)) {
// Make sure the text is visible by centering it in the line // Make sure the text is visible by centering it in the line
using (StringFormat stringFormat = new StringFormat()) { using (StringFormat stringFormat = new StringFormat()) {
stringFormat.LineAlignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Center;
@ -98,7 +108,7 @@ namespace Greenshot.Controls {
} }
} }
void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) { private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) {
if (PropertyChanged != null) { if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("Text")); PropertyChanged(this, new PropertyChangedEventArgs("Text"));
PropertyChanged(this, new PropertyChangedEventArgs("FontFamily")); PropertyChanged(this, new PropertyChangedEventArgs("FontFamily"));

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -29,14 +29,12 @@ namespace Greenshot.Controls {
public class MenuStripEx : MenuStrip { public class MenuStripEx : MenuStrip {
private const int WM_MOUSEACTIVATE = 0x21; private const int WM_MOUSEACTIVATE = 0x21;
enum NativeConstants : uint { private enum NativeConstants : uint {
MA_ACTIVATE = 1, MA_ACTIVATE = 1,
MA_ACTIVATEANDEAT = 2, MA_ACTIVATEANDEAT = 2,
MA_NOACTIVATE = 3,
MA_NOACTIVATEANDEAT = 4,
} }
private bool clickThrough = false; private bool _clickThrough;
/// <summary> /// <summary>
/// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus.
/// </summary> /// </summary>
@ -45,17 +43,17 @@ namespace Greenshot.Controls {
/// </remarks> /// </remarks>
public bool ClickThrough { public bool ClickThrough {
get { get {
return clickThrough; return _clickThrough;
} }
set { set {
clickThrough = value; _clickThrough = value;
} }
} }
protected override void WndProc(ref Message m) { protected override void WndProc(ref Message m) {
base.WndProc(ref 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;
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -19,19 +19,36 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
/// <summary>
/// See: http://nickstips.wordpress.com/2010/03/03/c-panel-resets-scroll-position-after-focus-is-lost-and-regained/
/// </summary>
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
namespace GreenshotPlugin.Controls { namespace GreenshotPlugin.Controls {
/// <summary>
/// See: http://nickstips.wordpress.com/2010/03/03/c-panel-resets-scroll-position-after-focus-is-lost-and-regained/
/// </summary>
public class NonJumpingPanel : Panel { public class NonJumpingPanel : Panel {
protected override Point ScrollToControl(Control activeControl) { protected override Point ScrollToControl(Control activeControl) {
// Returning the current location prevents the panel from // Returning the current location prevents the panel from
// scrolling to the active control when the panel loses and regains focus // scrolling to the active control when the panel loses and regains focus
return DisplayRectangle.Location; return DisplayRectangle.Location;
} }
/// <summary>
/// Add horizontal scrolling to the panel, when using the wheel and the shift key is pressed
/// </summary>
/// <param name="e">MouseEventArgs</param>
protected override void OnMouseWheel(MouseEventArgs e)
{
if (VScroll && (ModifierKeys & Keys.Shift) == Keys.Shift)
{
VScroll = false;
base.OnMouseWheel(e);
VScroll = true;
}
else
{
base.OnMouseWheel(e);
}
}
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -30,22 +30,22 @@ namespace Greenshot.Controls {
/// This code was supplied by Hi-Coder as a patch for Greenshot /// This code was supplied by Hi-Coder as a patch for Greenshot
/// Needed some modifications to be stable. /// Needed some modifications to be stable.
/// </summary> /// </summary>
public class Pipette : Label, IMessageFilter, IDisposable { public sealed class Pipette : Label, IMessageFilter, IDisposable {
private MovableShowColorForm movableShowColorForm; private MovableShowColorForm _movableShowColorForm;
private bool dragging; private bool _dragging;
private Cursor _cursor; private Cursor _cursor;
private Bitmap _image; private readonly Bitmap _image;
private const int VK_ESC = 27; private const int VkEsc = 27;
public event EventHandler<PipetteUsedArgs> PipetteUsed; public event EventHandler<PipetteUsedArgs> PipetteUsed;
public Pipette() { public Pipette() {
BorderStyle = BorderStyle.FixedSingle; BorderStyle = BorderStyle.FixedSingle;
dragging = false; _dragging = false;
_image = (Bitmap)new ComponentResourceManager(typeof(ColorDialog)).GetObject("pipette.Image"); _image = (Bitmap)new ComponentResourceManager(typeof(ColorDialog)).GetObject("pipette.Image");
Image = _image; Image = _image;
_cursor = CreateCursor((Bitmap)_image, 1, 14); _cursor = CreateCursor(_image, 1, 14);
movableShowColorForm = new MovableShowColorForm(); _movableShowColorForm = new MovableShowColorForm();
Application.AddMessageFilter(this); Application.AddMessageFilter(this);
} }
@ -58,13 +58,12 @@ namespace Greenshot.Controls {
/// <returns>Cursor</returns> /// <returns>Cursor</returns>
private static Cursor CreateCursor(Bitmap bitmap, int hotspotX, int hotspotY) { private static Cursor CreateCursor(Bitmap bitmap, int hotspotX, int hotspotY) {
using (SafeIconHandle iconHandle = new SafeIconHandle( bitmap.GetHicon())) { using (SafeIconHandle iconHandle = new SafeIconHandle( bitmap.GetHicon())) {
IntPtr icon; IconInfo iconInfo;
IconInfo iconInfo = new IconInfo();
User32.GetIconInfo(iconHandle, out iconInfo); User32.GetIconInfo(iconHandle, out iconInfo);
iconInfo.xHotspot = hotspotX; iconInfo.xHotspot = hotspotX;
iconInfo.yHotspot = hotspotY; iconInfo.yHotspot = hotspotY;
iconInfo.fIcon = false; iconInfo.fIcon = false;
icon = User32.CreateIconIndirect(ref iconInfo); var icon = User32.CreateIconIndirect(ref iconInfo);
return new Cursor(icon); return new Cursor(icon);
} }
} }
@ -85,11 +84,9 @@ namespace Greenshot.Controls {
if (_cursor != null) { if (_cursor != null) {
_cursor.Dispose(); _cursor.Dispose();
} }
if (movableShowColorForm != null) { _movableShowColorForm?.Dispose();
movableShowColorForm.Dispose();
} }
} _movableShowColorForm = null;
movableShowColorForm = null;
_cursor = null; _cursor = null;
base.Dispose(disposing); base.Dispose(disposing);
} }
@ -101,7 +98,7 @@ namespace Greenshot.Controls {
protected override void OnMouseDown(MouseEventArgs e) { protected override void OnMouseDown(MouseEventArgs e) {
if (e.Button == MouseButtons.Left) { if (e.Button == MouseButtons.Left) {
User32.SetCapture(Handle); User32.SetCapture(Handle);
movableShowColorForm.MoveTo(PointToScreen(new Point(e.X, e.Y))); _movableShowColorForm.MoveTo(PointToScreen(new Point(e.X, e.Y)));
} }
base.OnMouseDown(e); base.OnMouseDown(e);
} }
@ -111,10 +108,11 @@ namespace Greenshot.Controls {
/// </summary> /// </summary>
/// <param name="e">MouseEventArgs</param> /// <param name="e">MouseEventArgs</param>
protected override void OnMouseUp(MouseEventArgs e) { protected override void OnMouseUp(MouseEventArgs e) {
if (e.Button == MouseButtons.Left) { if (e.Button == MouseButtons.Left)
{
//Release Capture should consume MouseUp when canceled with the escape key //Release Capture should consume MouseUp when canceled with the escape key
User32.ReleaseCapture(); User32.ReleaseCapture();
PipetteUsed(this, new PipetteUsedArgs(movableShowColorForm.color)); PipetteUsed?.Invoke(this, new PipetteUsedArgs(_movableShowColorForm.color));
} }
base.OnMouseUp(e); base.OnMouseUp(e);
} }
@ -124,10 +122,10 @@ namespace Greenshot.Controls {
/// </summary> /// </summary>
/// <param name="e">MouseEventArgs</param> /// <param name="e">MouseEventArgs</param>
protected override void OnMouseMove(MouseEventArgs e) { protected override void OnMouseMove(MouseEventArgs e) {
if (dragging) { if (_dragging) {
//display the form on the right side of the cursor by default; //display the form on the right side of the cursor by default;
Point zp = PointToScreen(new Point(e.X, e.Y)); Point zp = PointToScreen(new Point(e.X, e.Y));
movableShowColorForm.MoveTo(zp); _movableShowColorForm.MoveTo(zp);
} }
base.OnMouseMove(e); base.OnMouseMove(e);
} }
@ -138,16 +136,16 @@ namespace Greenshot.Controls {
/// <param name="e"></param> /// <param name="e"></param>
protected override void OnMouseCaptureChanged(EventArgs e) { protected override void OnMouseCaptureChanged(EventArgs e) {
if (Capture) { if (Capture) {
dragging = true; _dragging = true;
Image = null; Image = null;
Cursor c = _cursor; Cursor c = _cursor;
Cursor = c; Cursor = c;
movableShowColorForm.Visible = true; _movableShowColorForm.Visible = true;
} else { } else {
dragging = false; _dragging = false;
Image = _image; Image = _image;
Cursor = Cursors.Arrow; Cursor = Cursors.Arrow;
movableShowColorForm.Visible = false; _movableShowColorForm.Visible = false;
} }
Update(); Update();
base.OnMouseCaptureChanged(e); base.OnMouseCaptureChanged(e);
@ -156,9 +154,9 @@ namespace Greenshot.Controls {
#region IMessageFilter Members #region IMessageFilter Members
public bool PreFilterMessage(ref Message m) { public bool PreFilterMessage(ref Message m) {
if (dragging) { if (_dragging) {
if (m.Msg == (int)WindowsMessages.WM_CHAR) { if (m.Msg == (int)WindowsMessages.WM_CHAR) {
if ((int)m.WParam == VK_ESC) { if ((int)m.WParam == VkEsc) {
User32.ReleaseCapture(); User32.ReleaseCapture();
} }
} }
@ -170,10 +168,10 @@ namespace Greenshot.Controls {
} }
public class PipetteUsedArgs : EventArgs { public class PipetteUsedArgs : EventArgs {
public Color color; public Color Color;
public PipetteUsedArgs(Color c) { public PipetteUsedArgs(Color c) {
color = c; Color = c;
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -35,16 +35,16 @@ namespace Greenshot.Controls {
set; set;
} }
private Color selectedColor = Color.Transparent; private Color _selectedColor = Color.Transparent;
public ToolStripColorButton() { public ToolStripColorButton() {
Click+= ColorButtonClick; Click+= ColorButtonClick;
} }
public Color SelectedColor { public Color SelectedColor {
get {return selectedColor;} get {return _selectedColor;}
set { set {
selectedColor = value; _selectedColor = value;
Brush brush; Brush brush;
if(value != Color.Transparent) { if(value != Color.Transparent) {
@ -65,19 +65,21 @@ namespace Greenshot.Controls {
} }
} }
void ColorButtonClick(object sender, EventArgs e) { private void ColorButtonClick(object sender, EventArgs e) {
ColorDialog colorDialog = ColorDialog.GetInstance(); ColorDialog colorDialog = ColorDialog.GetInstance();
colorDialog.Color = SelectedColor; colorDialog.Color = SelectedColor;
// Using the parent to make sure the dialog doesn't show on another window // Using the parent to make sure the dialog doesn't show on another window
colorDialog.ShowDialog(Parent.Parent); colorDialog.ShowDialog(Parent.Parent);
if (colorDialog.DialogResult != DialogResult.Cancel) { if (colorDialog.DialogResult == DialogResult.Cancel)
if (!colorDialog.Color.Equals(SelectedColor)) { {
return;
}
if (colorDialog.Color.Equals(SelectedColor))
{
return;
}
SelectedColor = colorDialog.Color; SelectedColor = colorDialog.Color;
if (PropertyChanged != null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedColor"));
PropertyChanged(this, new PropertyChangedEventArgs("SelectedColor"));
}
}
}
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -26,17 +26,15 @@ namespace Greenshot.Controls {
/// This is an extension of the default ToolStrip and allows us to click it even when the form doesn't have focus. /// This is an extension of the default ToolStrip and allows us to click it even when the form doesn't have focus.
/// See: http://blogs.msdn.com/b/rickbrew/archive/2006/01/09/511003.aspx /// See: http://blogs.msdn.com/b/rickbrew/archive/2006/01/09/511003.aspx
/// </summary> /// </summary>
class ToolStripEx : ToolStrip { internal class ToolStripEx : ToolStrip {
private const int WM_MOUSEACTIVATE = 0x21; private const int WM_MOUSEACTIVATE = 0x21;
enum NativeConstants : uint { private enum NativeConstants : uint {
MA_ACTIVATE = 1, MA_ACTIVATE = 1,
MA_ACTIVATEANDEAT = 2, MA_ACTIVATEANDEAT = 2,
MA_NOACTIVATE = 3,
MA_NOACTIVATEANDEAT = 4,
} }
private bool clickThrough = false; private bool _clickThrough;
/// <summary> /// <summary>
/// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus.
/// </summary> /// </summary>
@ -46,17 +44,17 @@ namespace Greenshot.Controls {
public bool ClickThrough { public bool ClickThrough {
get { get {
return clickThrough; return _clickThrough;
} }
set { set {
clickThrough = value; _clickThrough = value;
} }
} }
protected override void WndProc(ref Message m) { protected override void WndProc(ref Message m) {
base.WndProc(ref 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;
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -34,10 +34,7 @@ namespace Greenshot.Controls {
{ {
} }
public NumericUpDown NumericUpDown public NumericUpDown NumericUpDown => Control as NumericUpDown;
{
get {return Control as NumericUpDown;}
}
public decimal Value public decimal Value
{ {
@ -74,8 +71,9 @@ namespace Greenshot.Controls {
NumericUpDown.ValueChanged -= _valueChanged; NumericUpDown.ValueChanged -= _valueChanged;
} }
private void _valueChanged(object sender, EventArgs e) { private void _valueChanged(object sender, EventArgs e)
if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Value")); {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -25,16 +25,12 @@ using System.Windows.Forms;
using Greenshot.Configuration; using Greenshot.Configuration;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations { namespace Greenshot.Destinations {
/// <summary> /// <summary>
/// Description of ClipboardDestination. /// Description of ClipboardDestination.
/// </summary> /// </summary>
public class ClipboardDestination : AbstractDestination { public class ClipboardDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(ClipboardDestination));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
public const string DESIGNATION = "Clipboard"; public const string DESIGNATION = "Clipboard";
public override string Designation { public override string Designation {

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -32,11 +32,11 @@ namespace Greenshot.Destinations {
/// Description of EditorDestination. /// Description of EditorDestination.
/// </summary> /// </summary>
public class EditorDestination : AbstractDestination { public class EditorDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(EditorDestination)); private static readonly ILog LOG = LogManager.GetLogger(typeof(EditorDestination));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>(); private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
public const string DESIGNATION = "Editor"; public const string DESIGNATION = "Editor";
private IImageEditor editor = null; private readonly IImageEditor editor;
private static Image greenshotIcon = GreenshotResources.getGreenshotIcon().ToBitmap(); private static readonly Image greenshotIcon = GreenshotResources.getGreenshotIcon().ToBitmap();
public EditorDestination() { public EditorDestination() {
} }
@ -66,7 +66,7 @@ namespace Greenshot.Destinations {
} }
} }
public override bool isDynamic { public override bool IsDynamic {
get { get {
return true; return true;
} }
@ -79,8 +79,8 @@ namespace Greenshot.Destinations {
} }
public override IEnumerable<IDestination> DynamicDestinations() { public override IEnumerable<IDestination> DynamicDestinations() {
foreach (IImageEditor editor in ImageEditorForm.Editors) { foreach (IImageEditor someEditor in ImageEditorForm.Editors) {
yield return new EditorDestination(editor); yield return new EditorDestination(someEditor);
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -26,86 +26,62 @@ using Greenshot.Configuration;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin; using Greenshot.Plugin;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations { namespace Greenshot.Destinations {
/// <summary> /// <summary>
/// Description of EmailDestination. /// Description of EmailDestination.
/// </summary> /// </summary>
public class EmailDestination : AbstractDestination { public class EmailDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(EmailDestination)); private static readonly Image MailIcon = GreenshotResources.getImage("Email.Image");
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static bool _isActiveFlag;
private static Image mailIcon = GreenshotResources.getImage("Email.Image"); private static string _mapiClient;
private static bool isActiveFlag = false;
private static string mapiClient = null;
public const string DESIGNATION = "EMail"; public const string DESIGNATION = "EMail";
static EmailDestination() { static EmailDestination() {
// Logic to decide what email implementation we use // Logic to decide what email implementation we use
if (EmailConfigHelper.HasMAPI()) { if (EmailConfigHelper.HasMapi()) {
isActiveFlag = true; _isActiveFlag = true;
mapiClient = EmailConfigHelper.GetMapiClient(); _mapiClient = EmailConfigHelper.GetMapiClient();
if (!string.IsNullOrEmpty(mapiClient)) { if (!string.IsNullOrEmpty(_mapiClient)) {
// Active as we have a mapi client, can be disabled later // Active as we have a mapi client, can be disabled later
isActiveFlag = true; _isActiveFlag = true;
} }
} }
} }
public EmailDestination() { public override string Designation => DESIGNATION;
}
public override string Designation {
get {
return DESIGNATION;
}
}
public override string Description { public override string Description {
get { get {
// Make sure there is some kind of "mail" name // Make sure there is some kind of "mail" name
if (mapiClient == null) { if (_mapiClient == null) {
mapiClient = Language.GetString(LangKey.editor_email); _mapiClient = Language.GetString(LangKey.editor_email);
} }
return mapiClient; return _mapiClient;
} }
} }
public override int Priority { public override int Priority => 3;
get {
return 3;
}
}
public override bool isActive { public override bool IsActive {
get { get {
if (isActiveFlag) { if (_isActiveFlag) {
// Disable if the office plugin is installed and the client is outlook // 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 :( // TODO: Change this! It always creates an exception, as the plugin has not been loaded the type is not there :(
Type outlookdestination = Type.GetType("GreenshotOfficePlugin.OutlookDestination,GreenshotOfficePlugin"); Type outlookdestination = Type.GetType("GreenshotOfficePlugin.OutlookDestination,GreenshotOfficePlugin");
if (outlookdestination != null) { if (outlookdestination != null) {
if (mapiClient.ToLower().Contains("microsoft outlook")) { if (_mapiClient.ToLower().Contains("microsoft outlook")) {
isActiveFlag = false; _isActiveFlag = false;
} }
} }
} }
return base.isActive && isActiveFlag; return base.IsActive && _isActiveFlag;
} }
} }
public override Keys EditorShortcutKeys { public override Keys EditorShortcutKeys => Keys.Control | Keys.E;
get {
return Keys.Control | Keys.E;
}
}
public override Image DisplayIcon { public override Image DisplayIcon => MailIcon;
get {
return mailIcon;
}
}
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(Designation, Description); ExportInformation exportInformation = new ExportInformation(Designation, Description);

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -35,39 +35,19 @@ namespace Greenshot.Destinations {
/// Description of FileSaveAsDestination. /// Description of FileSaveAsDestination.
/// </summary> /// </summary>
public class FileDestination : AbstractDestination { public class FileDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(FileDestination)); private static readonly ILog Log = LogManager.GetLogger(typeof(FileDestination));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
public const string DESIGNATION = "FileNoDialog"; public const string DESIGNATION = "FileNoDialog";
public override string Designation { public override string Designation => DESIGNATION;
get {
return DESIGNATION;
}
}
public override string Description { public override string Description => Language.GetString(LangKey.quicksettings_destination_file);
get {
return Language.GetString(LangKey.quicksettings_destination_file);
}
}
public override int Priority { public override int Priority => 0;
get {
return 0;
}
}
public override Keys EditorShortcutKeys { public override Keys EditorShortcutKeys => Keys.Control | Keys.S;
get {
return Keys.Control | Keys.S;
}
}
public override Image DisplayIcon { public override Image DisplayIcon => GreenshotResources.getImage("Save.Image");
get {
return GreenshotResources.getImage("Save.Image");
}
}
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(Designation, Description); ExportInformation exportInformation = new ExportInformation(Designation, Description);
@ -77,18 +57,18 @@ namespace Greenshot.Destinations {
// Get output settings from the configuration // Get output settings from the configuration
SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(); SurfaceOutputSettings outputSettings = new SurfaceOutputSettings();
if (captureDetails != null && captureDetails.Filename != null) { if (captureDetails?.Filename != null) {
// As we save a pre-selected file, allow to overwrite. // As we save a pre-selected file, allow to overwrite.
overwrite = true; overwrite = true;
LOG.InfoFormat("Using previous filename"); Log.InfoFormat("Using previous filename");
fullPath = captureDetails.Filename; fullPath = captureDetails.Filename;
outputSettings.Format = ImageOutput.FormatForFilename(fullPath); outputSettings.Format = ImageOutput.FormatForFilename(fullPath);
} else { } else {
fullPath = CreateNewFilename(captureDetails); fullPath = CreateNewFilename(captureDetails);
// As we generate a file, the configuration tells us if we allow to overwrite // As we generate a file, the configuration tells us if we allow to overwrite
overwrite = conf.OutputFileAllowOverwrite; overwrite = CoreConfig.OutputFileAllowOverwrite;
} }
if (conf.OutputFilePromptQuality) { if (CoreConfig.OutputFilePromptQuality) {
QualityDialog qualityDialog = new QualityDialog(outputSettings); QualityDialog qualityDialog = new QualityDialog(outputSettings);
qualityDialog.ShowDialog(); qualityDialog.ShowDialog();
} }
@ -96,28 +76,31 @@ namespace Greenshot.Destinations {
// Catching any exception to prevent that the user can't write in the directory. // Catching any exception to prevent that the user can't write in the directory.
// This is done for e.g. bugs #2974608, #2963943, #2816163, #2795317, #2789218, #3004642 // This is done for e.g. bugs #2974608, #2963943, #2816163, #2795317, #2789218, #3004642
try { try {
ImageOutput.Save(surface, fullPath, overwrite, outputSettings, conf.OutputFileCopyPathToClipboard); ImageOutput.Save(surface, fullPath, overwrite, outputSettings, CoreConfig.OutputFileCopyPathToClipboard);
outputMade = true; outputMade = true;
} catch (ArgumentException ex1) { } catch (ArgumentException ex1) {
// Our generated filename exists, display 'save-as' // Our generated filename exists, display 'save-as'
LOG.InfoFormat("Not overwriting: {0}", ex1.Message); Log.InfoFormat("Not overwriting: {0}", ex1.Message);
// when we don't allow to overwrite present a new SaveWithDialog // when we don't allow to overwrite present a new SaveWithDialog
fullPath = ImageOutput.SaveWithDialog(surface, captureDetails); fullPath = ImageOutput.SaveWithDialog(surface, captureDetails);
outputMade = (fullPath != null); outputMade = fullPath != null;
} catch (Exception ex2) { } catch (Exception ex2) {
LOG.Error("Error saving screenshot!", ex2); Log.Error("Error saving screenshot!", ex2);
// Show the problem // Show the problem
MessageBox.Show(Language.GetString(LangKey.error_save), Language.GetString(LangKey.error)); MessageBox.Show(Language.GetString(LangKey.error_save), Language.GetString(LangKey.error));
// when save failed we present a SaveWithDialog // when save failed we present a SaveWithDialog
fullPath = ImageOutput.SaveWithDialog(surface, captureDetails); fullPath = ImageOutput.SaveWithDialog(surface, captureDetails);
outputMade = (fullPath != null); outputMade = fullPath != null;
} }
// Don't overwrite filename if no output is made // Don't overwrite filename if no output is made
if (outputMade) { if (outputMade) {
exportInformation.ExportMade = outputMade; exportInformation.ExportMade = true;
exportInformation.Filepath = fullPath; exportInformation.Filepath = fullPath;
if (captureDetails != null)
{
captureDetails.Filename = fullPath; captureDetails.Filename = fullPath;
conf.OutputFileAsFullpath = fullPath; }
CoreConfig.OutputFileAsFullpath = fullPath;
} }
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surface);
@ -126,18 +109,18 @@ namespace Greenshot.Destinations {
private static string CreateNewFilename(ICaptureDetails captureDetails) { private static string CreateNewFilename(ICaptureDetails captureDetails) {
string fullPath; string fullPath;
LOG.InfoFormat("Creating new filename"); Log.InfoFormat("Creating new filename");
string pattern = conf.OutputFileFilenamePattern; string pattern = CoreConfig.OutputFileFilenamePattern;
if (string.IsNullOrEmpty(pattern)) { if (string.IsNullOrEmpty(pattern)) {
pattern = "greenshot ${capturetime}"; pattern = "greenshot ${capturetime}";
} }
string filename = FilenameHelper.GetFilenameFromPattern(pattern, conf.OutputFileFormat, captureDetails); string filename = FilenameHelper.GetFilenameFromPattern(pattern, CoreConfig.OutputFileFormat, captureDetails);
string filepath = FilenameHelper.FillVariables(conf.OutputFilePath, false); string filepath = FilenameHelper.FillVariables(CoreConfig.OutputFilePath, false);
try { try {
fullPath = Path.Combine(filepath, filename); fullPath = Path.Combine(filepath, filename);
} catch (ArgumentException) { } catch (ArgumentException) {
// configured filename or path not valid, show error message... // configured filename or path not valid, show error message...
LOG.InfoFormat("Generated path or filename not valid: {0}, {1}", filepath, filename); Log.InfoFormat("Generated path or filename not valid: {0}, {1}", filepath, filename);
MessageBox.Show(Language.GetString(LangKey.error_save_invalid_chars), Language.GetString(LangKey.error)); MessageBox.Show(Language.GetString(LangKey.error_save_invalid_chars), Language.GetString(LangKey.error));
// ... lets get the pattern fixed.... // ... lets get the pattern fixed....

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -26,15 +26,13 @@ using Greenshot.Configuration;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.IniFile; using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations { namespace Greenshot.Destinations {
/// <summary> /// <summary>
/// Description of FileWithDialog. /// Description of FileWithDialog.
/// </summary> /// </summary>
public class FileWithDialogDestination : AbstractDestination { public class FileWithDialogDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(FileWithDialogDestination)); private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
public const string DESIGNATION = "FileDialog"; public const string DESIGNATION = "FileDialog";
public override string Designation { public override string Designation {
@ -69,9 +67,8 @@ namespace Greenshot.Destinations {
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(Designation, Description); ExportInformation exportInformation = new ExportInformation(Designation, Description);
string savedTo = null;
// Bug #2918756 don't overwrite path if SaveWithDialog returns null! // Bug #2918756 don't overwrite path if SaveWithDialog returns null!
savedTo = ImageOutput.SaveWithDialog(surface, captureDetails); var savedTo = ImageOutput.SaveWithDialog(surface, captureDetails);
if (savedTo != null) { if (savedTo != null) {
exportInformation.ExportMade = true; exportInformation.ExportMade = true;
exportInformation.Filepath = savedTo; exportInformation.Filepath = savedTo;

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -24,35 +24,19 @@ using Greenshot.Configuration;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations { namespace Greenshot.Destinations {
/// <summary> /// <summary>
/// The PickerDestination shows a context menu with all possible destinations, so the user can "pick" one /// The PickerDestination shows a context menu with all possible destinations, so the user can "pick" one
/// </summary> /// </summary>
public class PickerDestination : AbstractDestination { public class PickerDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(PickerDestination));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
public const string DESIGNATION = "Picker"; public const string DESIGNATION = "Picker";
public override string Designation { public override string Designation => DESIGNATION;
get {
return DESIGNATION;
}
}
public override string Description { public override string Description => Language.GetString(LangKey.settings_destination_picker);
get {
return Language.GetString(LangKey.settings_destination_picker);
}
}
public override int Priority { public override int Priority => 1;
get {
return 1;
}
}
/// <summary> /// <summary>
@ -68,7 +52,7 @@ namespace Greenshot.Destinations {
if ("Picker".Equals(destination.Designation)) { if ("Picker".Equals(destination.Designation)) {
continue; continue;
} }
if (!destination.isActive) { if (!destination.IsActive) {
continue; continue;
} }
destinations.Add(destination); destinations.Add(destination);

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -28,18 +28,14 @@ using Greenshot.Configuration;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations { namespace Greenshot.Destinations {
/// <summary> /// <summary>
/// Description of PrinterDestination. /// Description of PrinterDestination.
/// </summary> /// </summary>
public class PrinterDestination : AbstractDestination { public class PrinterDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(PrinterDestination));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
public const string DESIGNATION = "Printer"; public const string DESIGNATION = "Printer";
public string printerName = null; public readonly string printerName;
public PrinterDestination() { public PrinterDestination() {
} }
@ -80,7 +76,7 @@ namespace Greenshot.Destinations {
} }
} }
public override bool isDynamic { public override bool IsDynamic {
get { get {
return true; return true;
} }
@ -89,7 +85,7 @@ namespace Greenshot.Destinations {
/// <summary> /// <summary>
/// Create destinations for all the installed printers /// Create destinations for all the installed printers
/// </summary> /// </summary>
/// <returns>IEnumerable<IDestination></returns> /// <returns>IEnumerable of IDestination</returns>
public override IEnumerable<IDestination> DynamicDestinations() { public override IEnumerable<IDestination> DynamicDestinations() {
PrinterSettings settings = new PrinterSettings(); PrinterSettings settings = new PrinterSettings();
string defaultPrinter = settings.PrinterName; string defaultPrinter = settings.PrinterName;
@ -121,7 +117,7 @@ namespace Greenshot.Destinations {
/// <returns>ExportInformation</returns> /// <returns>ExportInformation</returns>
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(Designation, Description); ExportInformation exportInformation = new ExportInformation(Designation, Description);
PrinterSettings printerSettings = null; PrinterSettings printerSettings;
if (!string.IsNullOrEmpty(printerName)) { if (!string.IsNullOrEmpty(printerName)) {
using (PrintHelper printHelper = new PrintHelper(surface, captureDetails)) { using (PrintHelper printHelper = new PrintHelper(surface, captureDetails)) {
printerSettings = printHelper.PrintTo(printerName); printerSettings = printHelper.PrintTo(printerName);

View file

@ -0,0 +1,146 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Greenshot.Plugin.Drawing;
using Greenshot.Plugin.Drawing.Adorners;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Greenshot.Drawing.Adorners
{
public class AbstractAdorner : IAdorner
{
public virtual EditStatus EditStatus { get; protected set; } = EditStatus.IDLE;
protected Size _size = new Size(4, 4);
public AbstractAdorner(IDrawableContainer owner)
{
Owner = owner;
}
/// <summary>
/// Returns the cursor for when the mouse is over the adorner
/// </summary>
public virtual Cursor Cursor
{
get
{
return Cursors.SizeAll;
}
}
public virtual IDrawableContainer Owner
{
get;
set;
}
/// <summary>
/// Test if the point is inside the adorner
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public virtual bool HitTest(Point point)
{
Rectangle hitBounds = Bounds;
hitBounds.Inflate(3, 3);
return hitBounds.Contains(point);
}
/// <summary>
/// Handle the mouse down
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public virtual void MouseDown(object sender, MouseEventArgs mouseEventArgs)
{
}
/// <summary>
/// Handle the mouse move
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public virtual void MouseMove(object sender, MouseEventArgs mouseEventArgs)
{
}
/// <summary>
/// Handle the mouse up
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public virtual void MouseUp(object sender, MouseEventArgs mouseEventArgs)
{
EditStatus = EditStatus.IDLE;
}
/// <summary>
/// Return the location of the adorner
/// </summary>
public virtual Point Location
{
get;
set;
}
/// <summary>
/// Return the bounds of the Adorner
/// </summary>
public virtual Rectangle Bounds
{
get
{
Point location = Location;
return new Rectangle(location.X - (_size.Width / 2), location.Y - (_size.Height / 2), _size.Width, _size.Height);
}
}
/// <summary>
/// The adorner is active if the edit status is not idle or undrawn
/// </summary>
public virtual bool IsActive
{
get
{
return EditStatus != EditStatus.IDLE && EditStatus != EditStatus.UNDRAWN;
}
}
/// <summary>
/// Draw the adorner
/// </summary>
/// <param name="paintEventArgs">PaintEventArgs</param>
public virtual void Paint(PaintEventArgs paintEventArgs)
{
}
/// <summary>
/// We ignore the Transform, as the coordinates are directly bound to those of the owner
/// </summary>
/// <param name="matrix"></param>
public virtual void Transform(Matrix matrix)
{
}
}
}

View file

@ -0,0 +1,164 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Greenshot.Helpers;
using Greenshot.Plugin.Drawing;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Greenshot.Drawing.Adorners
{
/// <summary>
/// This is the adorner for the line based containers
/// </summary>
public class MoveAdorner : AbstractAdorner
{
private Rectangle _boundsBeforeResize = Rectangle.Empty;
private RectangleF _boundsAfterResize = RectangleF.Empty;
public Positions Position { get; private set; }
public MoveAdorner(IDrawableContainer owner, Positions position) : base(owner)
{
Position = position;
}
/// <summary>
/// Returns the cursor for when the mouse is over the adorner
/// </summary>
public override Cursor Cursor => Cursors.SizeAll;
/// <summary>
/// Handle the mouse down
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public override void MouseDown(object sender, MouseEventArgs mouseEventArgs)
{
EditStatus = EditStatus.RESIZING;
_boundsBeforeResize = new Rectangle(Owner.Left, Owner.Top, Owner.Width, Owner.Height);
_boundsAfterResize = _boundsBeforeResize;
}
/// <summary>
/// Handle the mouse move
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public override void MouseMove(object sender, MouseEventArgs mouseEventArgs)
{
if (EditStatus != EditStatus.RESIZING)
{
return;
}
Owner.Invalidate();
Owner.MakeBoundsChangeUndoable(false);
// reset "workbench" rectangle to current bounds
_boundsAfterResize.X = _boundsBeforeResize.X;
_boundsAfterResize.Y = _boundsBeforeResize.Y;
_boundsAfterResize.Width = _boundsBeforeResize.Width;
_boundsAfterResize.Height = _boundsBeforeResize.Height;
// calculate scaled rectangle
ScaleHelper.Scale(ref _boundsAfterResize, Position, new PointF(mouseEventArgs.X, mouseEventArgs.Y), ScaleHelper.GetScaleOptions());
// apply scaled bounds to this DrawableContainer
Owner.ApplyBounds(_boundsAfterResize);
Owner.Invalidate();
}
/// <summary>
/// Return the location of the adorner
/// </summary>
public override Point Location {
get
{
int x = 0,y = 0;
switch (Position)
{
case Positions.TopLeft:
x = Owner.Left;
y = Owner.Top;
break;
case Positions.BottomLeft:
x = Owner.Left;
y = Owner.Top + Owner.Height;
break;
case Positions.MiddleLeft:
x = Owner.Left;
y = Owner.Top + (Owner.Height / 2);
break;
case Positions.TopCenter:
x = Owner.Left + (Owner.Width / 2);
y = Owner.Top;
break;
case Positions.BottomCenter:
x = Owner.Left + (Owner.Width / 2);
y = Owner.Top + Owner.Height;
break;
case Positions.TopRight:
x = Owner.Left + Owner.Width;
y = Owner.Top;
break;
case Positions.BottomRight:
x = Owner.Left + Owner.Width;
y = Owner.Top + Owner.Height;
break;
case Positions.MiddleRight:
x = Owner.Left + Owner.Width;
y = Owner.Top + (Owner.Height / 2);
break;
}
return new Point(x, y);
}
}
/// <summary>
/// Draw the adorner
/// </summary>
/// <param name="paintEventArgs">PaintEventArgs</param>
public override void Paint(PaintEventArgs paintEventArgs)
{
Graphics targetGraphics = paintEventArgs.Graphics;
var bounds = Bounds;
GraphicsState state = targetGraphics.Save();
targetGraphics.SmoothingMode = SmoothingMode.None;
targetGraphics.CompositingMode = CompositingMode.SourceCopy;
targetGraphics.PixelOffsetMode = PixelOffsetMode.Half;
targetGraphics.InterpolationMode = InterpolationMode.NearestNeighbor;
try
{
targetGraphics.FillRectangle(Brushes.Black, bounds.X, bounds.Y, bounds.Width, bounds.Height);
}
catch
{
// Ignore, BUG-2065
}
targetGraphics.Restore(state);
}
}
}

View file

@ -0,0 +1,184 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Greenshot.Helpers;
using Greenshot.Plugin.Drawing;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Greenshot.Drawing.Adorners
{
/// <summary>
/// This is the default "legacy" gripper adorner, not the one used for the tail in the speech-bubble
/// </summary>
public class ResizeAdorner : AbstractAdorner
{
private Rectangle _boundsBeforeResize = Rectangle.Empty;
private RectangleF _boundsAfterResize = RectangleF.Empty;
public Positions Position { get; private set; }
public ResizeAdorner(IDrawableContainer owner, Positions position) : base(owner)
{
Position = position;
}
/// <summary>
/// Returns the cursor for when the mouse is over the adorner
/// </summary>
public override Cursor Cursor
{
get
{
bool isNotSwitched = Owner.Width >= 0;
if (Owner.Height < 0)
{
isNotSwitched = !isNotSwitched;
}
switch (Position)
{
case Positions.TopLeft:
case Positions.BottomRight:
return isNotSwitched ? Cursors.SizeNWSE : Cursors.SizeNESW;
case Positions.TopRight:
case Positions.BottomLeft:
return isNotSwitched ? Cursors.SizeNESW : Cursors.SizeNWSE;
case Positions.MiddleLeft:
case Positions.MiddleRight:
return Cursors.SizeWE;
case Positions.TopCenter:
case Positions.BottomCenter:
return Cursors.SizeNS;
default:
return Cursors.SizeAll;
}
}
}
/// <summary>
/// Handle the mouse down
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public override void MouseDown(object sender, MouseEventArgs mouseEventArgs)
{
EditStatus = EditStatus.RESIZING;
_boundsBeforeResize = new Rectangle(Owner.Left, Owner.Top, Owner.Width, Owner.Height);
_boundsAfterResize = _boundsBeforeResize;
}
/// <summary>
/// Handle the mouse move
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public override void MouseMove(object sender, MouseEventArgs mouseEventArgs)
{
if (EditStatus != EditStatus.RESIZING)
{
return;
}
Owner.Invalidate();
Owner.MakeBoundsChangeUndoable(false);
// reset "workbench" rectangle to current bounds
_boundsAfterResize.X = _boundsBeforeResize.X;
_boundsAfterResize.Y = _boundsBeforeResize.Y;
_boundsAfterResize.Width = _boundsBeforeResize.Width;
_boundsAfterResize.Height = _boundsBeforeResize.Height;
// calculate scaled rectangle
ScaleHelper.Scale(ref _boundsAfterResize, Position, new PointF(mouseEventArgs.X, mouseEventArgs.Y), ScaleHelper.GetScaleOptions());
// apply scaled bounds to this DrawableContainer
Owner.ApplyBounds(_boundsAfterResize);
Owner.Invalidate();
}
/// <summary>
/// Return the location of the adorner
/// </summary>
public override Point Location {
get
{
int x = 0,y = 0;
switch (Position)
{
case Positions.TopLeft:
x = Owner.Left;
y = Owner.Top;
break;
case Positions.BottomLeft:
x = Owner.Left;
y = Owner.Top + Owner.Height;
break;
case Positions.MiddleLeft:
x = Owner.Left;
y = Owner.Top + (Owner.Height / 2);
break;
case Positions.TopCenter:
x = Owner.Left + (Owner.Width / 2);
y = Owner.Top;
break;
case Positions.BottomCenter:
x = Owner.Left + (Owner.Width / 2);
y = Owner.Top + Owner.Height;
break;
case Positions.TopRight:
x = Owner.Left + Owner.Width;
y = Owner.Top;
break;
case Positions.BottomRight:
x = Owner.Left + Owner.Width;
y = Owner.Top + Owner.Height;
break;
case Positions.MiddleRight:
x = Owner.Left + Owner.Width;
y = Owner.Top + (Owner.Height / 2);
break;
}
return new Point(x, y);
}
}
/// <summary>
/// Draw the adorner
/// </summary>
/// <param name="paintEventArgs">PaintEventArgs</param>
public override void Paint(PaintEventArgs paintEventArgs)
{
Graphics targetGraphics = paintEventArgs.Graphics;
var bounds = Bounds;
GraphicsState state = targetGraphics.Save();
targetGraphics.SmoothingMode = SmoothingMode.None;
targetGraphics.CompositingMode = CompositingMode.SourceCopy;
targetGraphics.PixelOffsetMode = PixelOffsetMode.Half;
targetGraphics.InterpolationMode = InterpolationMode.NearestNeighbor;
targetGraphics.FillRectangle(Brushes.Black, bounds.X, bounds.Y, bounds.Width , bounds.Height);
targetGraphics.Restore(state);
}
}
}

View file

@ -0,0 +1,118 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Greenshot.Plugin.Drawing;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Greenshot.Drawing.Adorners
{
/// <summary>
/// This implements the special "gripper" for the Speech-Bubble tail
/// </summary>
public class TargetAdorner : AbstractAdorner
{
public TargetAdorner(IDrawableContainer owner, Point location) : base(owner)
{
Location = location;
}
/// <summary>
/// Handle the mouse down
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public override void MouseDown(object sender, MouseEventArgs mouseEventArgs)
{
EditStatus = EditStatus.MOVING;
}
/// <summary>
/// Handle the mouse move
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public override void MouseMove(object sender, MouseEventArgs mouseEventArgs)
{
if (EditStatus != EditStatus.MOVING)
{
return;
}
Owner.Invalidate();
Point newGripperLocation = new Point(mouseEventArgs.X, mouseEventArgs.Y);
Rectangle surfaceBounds = new Rectangle(0, 0, Owner.Parent.Width, Owner.Parent.Height);
// Check if gripper inside the parent (surface), if not we need to move it inside
// This was made for BUG-1682
if (!surfaceBounds.Contains(newGripperLocation))
{
if (newGripperLocation.X > surfaceBounds.Right)
{
newGripperLocation.X = surfaceBounds.Right - 5;
}
if (newGripperLocation.X < surfaceBounds.Left)
{
newGripperLocation.X = surfaceBounds.Left;
}
if (newGripperLocation.Y > surfaceBounds.Bottom)
{
newGripperLocation.Y = surfaceBounds.Bottom - 5;
}
if (newGripperLocation.Y < surfaceBounds.Top)
{
newGripperLocation.Y = surfaceBounds.Top;
}
}
Location = newGripperLocation;
Owner.Invalidate();
}
/// <summary>
/// Draw the adorner
/// </summary>
/// <param name="paintEventArgs">PaintEventArgs</param>
public override void Paint(PaintEventArgs paintEventArgs)
{
Graphics targetGraphics = paintEventArgs.Graphics;
var bounds = Bounds;
targetGraphics.FillRectangle(Brushes.Green, bounds.X, bounds.Y, bounds.Width, bounds.Height);
}
/// <summary>
/// Made sure this adorner is transformed
/// </summary>
/// <param name="matrix">Matrix</param>
public override void Transform(Matrix matrix)
{
if (matrix == null)
{
return;
}
Point[] points = new[] { Location };
matrix.TransformPoints(points);
Location = points[0];
}
}
}

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -79,7 +79,7 @@ namespace Greenshot.Drawing {
Top + currentStep + Height); Top + currentStep + Height);
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,9 +20,11 @@
*/ */
using System.Drawing; using System.Drawing;
using System.Runtime.Serialization;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -30,27 +32,38 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
public class CropContainer : DrawableContainer { public class CropContainer : DrawableContainer {
public CropContainer(Surface parent) : base(parent) { public CropContainer(Surface parent) : base(parent) {
Init();
} }
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
}
protected override void InitializeFields() { protected override void InitializeFields() {
AddField(GetType(), FieldType.FLAGS, FieldType.Flag.CONFIRMABLE); AddField(GetType(), FieldType.FLAGS, FieldFlag.CONFIRMABLE);
} }
public override void Invalidate() { public override void Invalidate() {
_parent.Invalidate(); _parent?.Invalidate();
} }
/// <summary> /// <summary>
/// We need to override the DrawingBound, return a rectangle in the size of the image, to make sure this element is always draw /// We need to override the DrawingBound, return a rectangle in the size of the image, to make sure this element is always draw
/// (we create a transparent brown over the complete picture) /// (we create a transparent brown over the complete picture)
/// </summary> /// </summary>
public override Rectangle DrawingBounds { public override Rectangle DrawingBounds => new Rectangle(0,0,_parent?.Width??0, _parent?.Height ?? 0);
get {
return new Rectangle(0,0,_parent.Width, _parent.Height);
}
}
public override void Draw(Graphics g, RenderMode rm) { public override void Draw(Graphics g, RenderMode rm) {
if (_parent == null)
{
return;
}
using (Brush cropBrush = new SolidBrush(Color.FromArgb(100, 150, 150, 100))) { using (Brush cropBrush = new SolidBrush(Color.FromArgb(100, 150, 150, 100))) {
Rectangle cropRectangle = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); Rectangle cropRectangle = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
Rectangle selectionRect = new Rectangle(cropRectangle.Left - 1, cropRectangle.Top - 1, cropRectangle.Width + 1, cropRectangle.Height + 1); Rectangle selectionRect = new Rectangle(cropRectangle.Left - 1, cropRectangle.Top - 1, cropRectangle.Width + 1, cropRectangle.Height + 1);

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -26,6 +26,7 @@ using System.Windows.Forms;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using log4net; using log4net;
using System.Runtime.Serialization;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -33,14 +34,26 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
[Serializable] [Serializable]
public class CursorContainer : DrawableContainer, ICursorContainer { public class CursorContainer : DrawableContainer, ICursorContainer {
private static ILog LOG = LogManager.GetLogger(typeof(CursorContainer)); private static readonly ILog LOG = LogManager.GetLogger(typeof(CursorContainer));
protected Cursor cursor; protected Cursor cursor;
public CursorContainer(Surface parent) : base(parent) { public CursorContainer(Surface parent) : base(parent) {
Init();
} }
public CursorContainer(Surface parent, string filename) : base(parent) { protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
}
public CursorContainer(Surface parent, string filename) : this(parent) {
Load(filename); Load(filename);
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,6 +20,7 @@
*/ */
using Greenshot.Configuration; using Greenshot.Configuration;
using Greenshot.Drawing.Adorners;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Drawing.Filters; using Greenshot.Drawing.Filters;
using Greenshot.Helpers; using Greenshot.Helpers;
@ -27,15 +28,19 @@ using Greenshot.IniFile;
using Greenshot.Memento; using Greenshot.Memento;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using Greenshot.Plugin.Drawing.Adorners;
using GreenshotPlugin.Interfaces.Drawing;
using log4net; using log4net;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Runtime.Serialization;
using System.Windows.Forms; using System.Windows.Forms;
namespace Greenshot.Drawing { namespace Greenshot.Drawing
{
/// <summary> /// <summary>
/// represents a rectangle, ellipse, label or whatever. Can contain filters, too. /// represents a rectangle, ellipse, label or whatever. Can contain filters, too.
/// serializable for clipboard support /// serializable for clipboard support
@ -46,12 +51,23 @@ namespace Greenshot.Drawing {
public abstract class DrawableContainer : AbstractFieldHolderWithChildren, IDrawableContainer { public abstract class DrawableContainer : AbstractFieldHolderWithChildren, IDrawableContainer {
private static readonly ILog LOG = LogManager.GetLogger(typeof(DrawableContainer)); private static readonly ILog LOG = LogManager.GetLogger(typeof(DrawableContainer));
protected static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>(); protected static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>();
private bool isMadeUndoable;
private const int M11 = 0; private const int M11 = 0;
private const int M12 = 1;
private const int M21 = 2;
private const int M22 = 3; private const int M22 = 3;
[OnDeserialized]
private void OnDeserializedInit(StreamingContext context)
{
_adorners = new List<IAdorner>();
OnDeserialized(context);
}
/// <summary>
/// Override to implement your own deserialization logic, like initializing properties which are not serialized
/// </summary>
/// <param name="streamingContext"></param>
protected virtual void OnDeserialized(StreamingContext streamingContext)
{
}
protected EditStatus _defaultEditMode = EditStatus.DRAWING; protected EditStatus _defaultEditMode = EditStatus.DRAWING;
public EditStatus DefaultEditMode { public EditStatus DefaultEditMode {
@ -73,19 +89,7 @@ namespace Greenshot.Drawing {
if (!disposing) { if (!disposing) {
return; return;
} }
if (_grippers != null) { _parent?.FieldAggregator?.UnbindElement(this);
for (int i = 0; i < _grippers.Length; i++) {
if (_grippers[i] == null) {
continue;
}
_grippers[i].Dispose();
_grippers[i] = null;
}
_grippers = null;
}
FieldAggregator aggProps = _parent.FieldAggregator;
aggProps.UnbindElement(this);
} }
~DrawableContainer() { ~DrawableContainer() {
@ -99,7 +103,7 @@ namespace Greenshot.Drawing {
remove{ _propertyChanged -= value; } remove{ _propertyChanged -= value; }
} }
public List<IFilter> Filters { public IList<IFilter> Filters {
get { get {
List<IFilter> ret = new List<IFilter>(); List<IFilter> ret = new List<IFilter>();
foreach(IFieldHolder c in Children) { foreach(IFieldHolder c in Children) {
@ -117,16 +121,12 @@ namespace Greenshot.Drawing {
get { return _parent; } get { return _parent; }
set { SwitchParent((Surface)value); } set { SwitchParent((Surface)value); }
} }
[NonSerialized]
protected Gripper[] _grippers;
private bool layoutSuspended;
[NonSerialized] [NonSerialized]
private Gripper _targetGripper; private TargetAdorner _targetAdorner;
public TargetAdorner TargetAdorner {
public Gripper TargetGripper {
get { get {
return _targetGripper; return _targetAdorner;
} }
} }
@ -160,7 +160,6 @@ namespace Greenshot.Drawing {
return; return;
} }
left = value; left = value;
DoLayout();
} }
} }
@ -172,7 +171,6 @@ namespace Greenshot.Drawing {
return; return;
} }
top = value; top = value;
DoLayout();
} }
} }
@ -184,7 +182,6 @@ namespace Greenshot.Drawing {
return; return;
} }
width = value; width = value;
DoLayout();
} }
} }
@ -196,7 +193,6 @@ namespace Greenshot.Drawing {
return; return;
} }
height = value; height = value;
DoLayout();
} }
} }
@ -220,6 +216,19 @@ namespace Greenshot.Drawing {
} }
} }
/// <summary>
/// List of available Adorners
/// </summary>
[NonSerialized]
private IList<IAdorner> _adorners = new List<IAdorner>();
public IList<IAdorner> Adorners
{
get
{
return _adorners;
}
}
[NonSerialized] [NonSerialized]
// will store current bounds of this DrawableContainer before starting a resize // will store current bounds of this DrawableContainer before starting a resize
protected Rectangle _boundsBeforeResize = Rectangle.Empty; protected Rectangle _boundsBeforeResize = Rectangle.Empty;
@ -248,7 +257,6 @@ namespace Greenshot.Drawing {
public DrawableContainer(Surface parent) { public DrawableContainer(Surface parent) {
InitializeFields(); InitializeFields();
_parent = parent; _parent = parent;
InitControls();
} }
public void Add(IFilter filter) { public void Add(IFilter filter) {
@ -291,12 +299,15 @@ namespace Greenshot.Drawing {
public virtual void Invalidate() { public virtual void Invalidate() {
if (Status != EditStatus.UNDRAWN) { if (Status != EditStatus.UNDRAWN) {
_parent.Invalidate(DrawingBounds); _parent?.Invalidate(DrawingBounds);
} }
} }
public void AlignToParent(HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) { public void AlignToParent(HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) {
if (_parent == null)
{
return;
}
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS);
if (horizontalAlignment == HorizontalAlignment.Left) { if (horizontalAlignment == HorizontalAlignment.Left) {
Left = lineThickness/2; Left = lineThickness/2;
@ -323,185 +334,32 @@ namespace Greenshot.Drawing {
public virtual void OnDoubleClick() {} public virtual void OnDoubleClick() {}
private void InitControls() {
InitGrippers();
DoLayout();
}
/// <summary>
/// Move the TargetGripper around, confined to the surface to solve BUG-1682
/// </summary>
/// <param name="newX"></param>
/// <param name="newY"></param>
protected virtual void TargetGripperMove(int newX, int newY) {
Point newGripperLocation = new Point(newX, newY);
Rectangle surfaceBounds = new Rectangle(0, 0, _parent.Width, _parent.Height);
// Check if gripper inside the parent (surface), if not we need to move it inside
// This was made for BUG-1682
if (!surfaceBounds.Contains(newGripperLocation)) {
if (newGripperLocation.X > surfaceBounds.Right) {
newGripperLocation.X = surfaceBounds.Right - 5;
}
if (newGripperLocation.X < surfaceBounds.Left) {
newGripperLocation.X = surfaceBounds.Left;
}
if (newGripperLocation.Y > surfaceBounds.Bottom) {
newGripperLocation.Y = surfaceBounds.Bottom - 5;
}
if (newGripperLocation.Y < surfaceBounds.Top) {
newGripperLocation.Y = surfaceBounds.Top;
}
}
_targetGripper.Left = newGripperLocation.X;
_targetGripper.Top = newGripperLocation.Y;
}
/// <summary> /// <summary>
/// Initialize a target gripper /// Initialize a target gripper
/// </summary> /// </summary>
protected void InitTargetGripper(Color gripperColor, Point location) { protected void InitAdorner(Color gripperColor, Point location) {
_targetGripper = new Gripper { _targetAdorner = new TargetAdorner(this, location);
Cursor = Cursors.SizeAll, Adorners.Add(_targetAdorner);
BackColor = gripperColor,
Visible = false,
Parent = _parent,
Location = location
};
_targetGripper.MouseDown += GripperMouseDown;
_targetGripper.MouseUp += GripperMouseUp;
_targetGripper.MouseMove += GripperMouseMove;
if (_parent != null) {
_parent.Controls.Add(_targetGripper); // otherwise we'll attach them in switchParent
}
} }
protected void InitGrippers() { /// <summary>
/// Create the default adorners for a rectangle based container
/// </summary>
_grippers = new Gripper[8]; protected void CreateDefaultAdorners() {
for(int i=0; i<_grippers.Length; i++) { if (Adorners.Count > 0)
_grippers[i] = new Gripper(); {
_grippers[i].Position = i; LOG.Warn("Adorners are already defined!");
_grippers[i].MouseDown += GripperMouseDown;
_grippers[i].MouseUp += GripperMouseUp;
_grippers[i].MouseMove += GripperMouseMove;
_grippers[i].Visible = false;
_grippers[i].Parent = _parent;
} }
_grippers[Gripper.POSITION_TOP_CENTER].Cursor = Cursors.SizeNS; // Create the GripperAdorners
_grippers[Gripper.POSITION_MIDDLE_RIGHT].Cursor = Cursors.SizeWE; Adorners.Add(new ResizeAdorner(this, Positions.TopLeft));
_grippers[Gripper.POSITION_BOTTOM_CENTER].Cursor = Cursors.SizeNS; Adorners.Add(new ResizeAdorner(this, Positions.TopCenter));
_grippers[Gripper.POSITION_MIDDLE_LEFT].Cursor = Cursors.SizeWE; Adorners.Add(new ResizeAdorner(this, Positions.TopRight));
if (_parent != null) { Adorners.Add(new ResizeAdorner(this, Positions.BottomLeft));
_parent.Controls.AddRange(_grippers); // otherwise we'll attach them in switchParent Adorners.Add(new ResizeAdorner(this, Positions.BottomCenter));
} Adorners.Add(new ResizeAdorner(this, Positions.BottomRight));
} Adorners.Add(new ResizeAdorner(this, Positions.MiddleLeft));
Adorners.Add(new ResizeAdorner(this, Positions.MiddleRight));
public void SuspendLayout() {
layoutSuspended = true;
}
public void ResumeLayout() {
layoutSuspended = false;
DoLayout();
}
protected virtual void DoLayout() {
if (_grippers == null) {
return;
}
if (!layoutSuspended) {
int[] xChoords = {Left-2,Left+Width/2-2,Left+Width-2};
int[] yChoords = {Top-2,Top+Height/2-2,Top+Height-2};
_grippers[Gripper.POSITION_TOP_LEFT].Left = xChoords[0]; _grippers[Gripper.POSITION_TOP_LEFT].Top = yChoords[0];
_grippers[Gripper.POSITION_TOP_CENTER].Left = xChoords[1]; _grippers[Gripper.POSITION_TOP_CENTER].Top = yChoords[0];
_grippers[Gripper.POSITION_TOP_RIGHT].Left = xChoords[2]; _grippers[Gripper.POSITION_TOP_RIGHT].Top = yChoords[0];
_grippers[Gripper.POSITION_MIDDLE_RIGHT].Left = xChoords[2]; _grippers[Gripper.POSITION_MIDDLE_RIGHT].Top = yChoords[1];
_grippers[Gripper.POSITION_BOTTOM_RIGHT].Left = xChoords[2]; _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top = yChoords[2];
_grippers[Gripper.POSITION_BOTTOM_CENTER].Left = xChoords[1]; _grippers[Gripper.POSITION_BOTTOM_CENTER].Top = yChoords[2];
_grippers[Gripper.POSITION_BOTTOM_LEFT].Left = xChoords[0]; _grippers[Gripper.POSITION_BOTTOM_LEFT].Top = yChoords[2];
_grippers[Gripper.POSITION_MIDDLE_LEFT].Left = xChoords[0]; _grippers[Gripper.POSITION_MIDDLE_LEFT].Top = yChoords[1];
if((_grippers[Gripper.POSITION_TOP_LEFT].Left < _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left && _grippers[Gripper.POSITION_TOP_LEFT].Top < _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) ||
_grippers[Gripper.POSITION_TOP_LEFT].Left > _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left && _grippers[Gripper.POSITION_TOP_LEFT].Top > _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) {
_grippers[Gripper.POSITION_TOP_LEFT].Cursor = Cursors.SizeNWSE;
_grippers[Gripper.POSITION_TOP_RIGHT].Cursor = Cursors.SizeNESW;
_grippers[Gripper.POSITION_BOTTOM_RIGHT].Cursor = Cursors.SizeNWSE;
_grippers[Gripper.POSITION_BOTTOM_LEFT].Cursor = Cursors.SizeNESW;
} else if((_grippers[Gripper.POSITION_TOP_LEFT].Left > _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left && _grippers[Gripper.POSITION_TOP_LEFT].Top < _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) ||
_grippers[Gripper.POSITION_TOP_LEFT].Left < _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left && _grippers[Gripper.POSITION_TOP_LEFT].Top > _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) {
_grippers[Gripper.POSITION_TOP_LEFT].Cursor = Cursors.SizeNESW;
_grippers[Gripper.POSITION_TOP_RIGHT].Cursor = Cursors.SizeNWSE;
_grippers[Gripper.POSITION_BOTTOM_RIGHT].Cursor = Cursors.SizeNESW;
_grippers[Gripper.POSITION_BOTTOM_LEFT].Cursor = Cursors.SizeNWSE;
} else if (_grippers[Gripper.POSITION_TOP_LEFT].Left == _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left) {
_grippers[Gripper.POSITION_TOP_LEFT].Cursor = Cursors.SizeNS;
_grippers[Gripper.POSITION_BOTTOM_RIGHT].Cursor = Cursors.SizeNS;
} else if (_grippers[Gripper.POSITION_TOP_LEFT].Top == _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) {
_grippers[Gripper.POSITION_TOP_LEFT].Cursor = Cursors.SizeWE;
_grippers[Gripper.POSITION_BOTTOM_RIGHT].Cursor = Cursors.SizeWE;
}
}
}
private void GripperMouseDown(object sender, MouseEventArgs e) {
Gripper originatingGripper = (Gripper)sender;
if (originatingGripper != _targetGripper) {
Status = EditStatus.RESIZING;
_boundsBeforeResize = new Rectangle(left, top, width, height);
_boundsAfterResize = new RectangleF(_boundsBeforeResize.Left, _boundsBeforeResize.Top, _boundsBeforeResize.Width, _boundsBeforeResize.Height);
} else {
Status = EditStatus.MOVING;
}
isMadeUndoable = false;
}
private void GripperMouseUp(object sender, MouseEventArgs e) {
Gripper originatingGripper = (Gripper)sender;
if (originatingGripper != _targetGripper) {
_boundsBeforeResize = Rectangle.Empty;
_boundsAfterResize = RectangleF.Empty;
isMadeUndoable = false;
}
Status = EditStatus.IDLE;
Invalidate();
}
private void GripperMouseMove(object sender, MouseEventArgs e) {
Invalidate();
Gripper originatingGripper = (Gripper)sender;
int absX = originatingGripper.Left + e.X;
int absY = originatingGripper.Top + e.Y;
if (originatingGripper == _targetGripper && Status.Equals(EditStatus.MOVING)) {
TargetGripperMove(absX, absY);
} else if (Status.Equals(EditStatus.RESIZING)) {
// check if we already made this undoable
if (!isMadeUndoable) {
// don't allow another undo until we are finished with this move
isMadeUndoable = true;
// Make undo-able
MakeBoundsChangeUndoable(false);
}
SuspendLayout();
// reset "workbench" rectangle to current bounds
_boundsAfterResize.X = _boundsBeforeResize.X;
_boundsAfterResize.Y = _boundsBeforeResize.Y;
_boundsAfterResize.Width = _boundsBeforeResize.Width;
_boundsAfterResize.Height = _boundsBeforeResize.Height;
// calculate scaled rectangle
ScaleHelper.Scale(ref _boundsAfterResize, originatingGripper.Position, new PointF(absX, absY), ScaleHelper.GetScaleOptions());
// apply scaled bounds to this DrawableContainer
ApplyBounds(_boundsAfterResize);
ResumeLayout();
}
Invalidate();
} }
public bool hasFilters { public bool hasFilters {
@ -558,43 +416,10 @@ namespace Greenshot.Drawing {
} }
} }
public virtual void ShowGrippers() {
if (_grippers != null) {
for (int i = 0; i < _grippers.Length; i++) {
if (_grippers[i].Enabled) {
_grippers[i].Show();
} else {
_grippers[i].Hide();
}
}
}
if (_targetGripper != null) {
if (_targetGripper.Enabled) {
_targetGripper.Show();
} else {
_targetGripper.Hide();
}
}
ResumeLayout();
}
public virtual void HideGrippers() {
SuspendLayout();
if (_grippers != null) {
for (int i = 0; i < _grippers.Length; i++) {
_grippers[i].Hide();
}
}
if (_targetGripper != null) {
_targetGripper.Hide();
}
}
public void ResizeTo(int width, int height, int anchorPosition) { public void ResizeTo(int width, int height, int anchorPosition) {
SuspendLayout();
Width = width; Width = width;
Height = height; Height = height;
ResumeLayout();
} }
/// <summary> /// <summary>
@ -606,10 +431,8 @@ namespace Greenshot.Drawing {
} }
public void MoveBy(int dx, int dy) { public void MoveBy(int dx, int dy) {
SuspendLayout();
Left += dx; Left += dx;
Top += dy; Top += dy;
ResumeLayout();
} }
/// <summary> /// <summary>
@ -632,7 +455,6 @@ namespace Greenshot.Drawing {
/// <returns>true if the event is handled, false if the surface needs to handle it</returns> /// <returns>true if the event is handled, false if the surface needs to handle it</returns>
public virtual bool HandleMouseMove(int x, int y) { public virtual bool HandleMouseMove(int x, int y) {
Invalidate(); Invalidate();
SuspendLayout();
// reset "workrbench" rectangle to current bounds // reset "workrbench" rectangle to current bounds
_boundsAfterResize.X = _boundsBeforeResize.Left; _boundsAfterResize.X = _boundsBeforeResize.Left;
@ -645,7 +467,6 @@ namespace Greenshot.Drawing {
// apply scaled bounds to this DrawableContainer // apply scaled bounds to this DrawableContainer
ApplyBounds(_boundsAfterResize); ApplyBounds(_boundsAfterResize);
ResumeLayout();
Invalidate(); Invalidate();
return true; return true;
} }
@ -659,49 +480,18 @@ namespace Greenshot.Drawing {
} }
protected virtual void SwitchParent(Surface newParent) { protected virtual void SwitchParent(Surface newParent) {
// Target gripper if (newParent == Parent)
if (_parent != null && _targetGripper != null) { {
_parent.Controls.Remove(_targetGripper); return;
}
// Normal grippers
if (_parent != null && _grippers != null) {
for (int i=0; i<_grippers.Length; i++) {
_parent.Controls.Remove(_grippers[i]);
}
} else if (_grippers == null) {
InitControls();
}
_parent = newParent;
// Target gripper
if (_parent != null && _targetGripper != null) {
_parent.Controls.Add(_targetGripper);
}
// Normal grippers
if (_grippers != null) {
_parent.Controls.AddRange(_grippers);
} }
_parent?.FieldAggregator?.UnbindElement(this);
_parent = newParent;
foreach(IFilter filter in Filters) { foreach(IFilter filter in Filters) {
filter.Parent = this; filter.Parent = this;
} }
} }
// drawablecontainers are regarded equal if they are of the same type and their bounds are equal. this should be sufficient.
public override bool Equals(object obj) {
bool ret = false;
if (obj != null && GetType() == obj.GetType()) {
DrawableContainer other = obj as DrawableContainer;
if (other != null && left==other.left && top==other.top && width==other.width && height==other.height) {
ret = true;
}
}
return ret;
}
public override int GetHashCode() {
return left.GetHashCode() ^ top.GetHashCode() ^ width.GetHashCode() ^ height.GetHashCode() ^ GetFields().GetHashCode();
}
protected void OnPropertyChanged(string propertyName) { protected void OnPropertyChanged(string propertyName) {
if (_propertyChanged != null) { if (_propertyChanged != null) {
_propertyChanged(this, new PropertyChangedEventArgs(propertyName)); _propertyChanged(this, new PropertyChangedEventArgs(propertyName));
@ -715,8 +505,8 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="fieldToBeChanged">The field to be changed</param> /// <param name="fieldToBeChanged">The field to be changed</param>
/// <param name="newValue">The new value</param> /// <param name="newValue">The new value</param>
public virtual void BeforeFieldChange(Field fieldToBeChanged, object newValue) { public virtual void BeforeFieldChange(IField fieldToBeChanged, object newValue) {
_parent.MakeUndoable(new ChangeFieldHolderMemento(this, fieldToBeChanged), true); _parent?.MakeUndoable(new ChangeFieldHolderMemento(this, fieldToBeChanged), true);
Invalidate(); Invalidate();
} }
@ -727,10 +517,9 @@ namespace Greenshot.Drawing {
/// <param name="e"></param> /// <param name="e"></param>
public void HandleFieldChanged(object sender, FieldChangedEventArgs e) { public void HandleFieldChanged(object sender, FieldChangedEventArgs e) {
LOG.DebugFormat("Field {0} changed", e.Field.FieldType); LOG.DebugFormat("Field {0} changed", e.Field.FieldType);
if (e.Field.FieldType == FieldType.SHADOW) { if (Equals(e.Field.FieldType, FieldType.SHADOW)) {
accountForShadowChange = true; accountForShadowChange = true;
} }
Invalidate();
} }
/// <summary> /// <summary>
@ -775,26 +564,16 @@ namespace Greenshot.Drawing {
if (matrix == null) { if (matrix == null) {
return; return;
} }
SuspendLayout();
Point topLeft = new Point(Left, Top); Point topLeft = new Point(Left, Top);
Point bottomRight = new Point(Left + Width, Top + Height); Point bottomRight = new Point(Left + Width, Top + Height);
Point[] points; Point[] points = new[] { topLeft, bottomRight };
if (TargetGripper != null) {
points = new[] {topLeft, bottomRight, TargetGripper.Location};
} else {
points = new[] { topLeft, bottomRight };
}
matrix.TransformPoints(points); matrix.TransformPoints(points);
Left = points[0].X; Left = points[0].X;
Top = points[0].Y; Top = points[0].Y;
Width = points[1].X - points[0].X; Width = points[1].X - points[0].X;
Height = points[1].Y - points[0].Y; Height = points[1].Y - points[0].Y;
if (TargetGripper != null) {
TargetGripper.Location = points[points.Length-1];
}
ResumeLayout();
} }
protected virtual ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() { protected virtual ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() {

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,11 +20,11 @@
*/ */
using Greenshot.Configuration; using Greenshot.Configuration;
using Greenshot.Drawing.Fields;
using Greenshot.Memento; using Greenshot.Memento;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -38,8 +38,9 @@ namespace Greenshot.Drawing {
/// Dispatches most of a DrawableContainer's public properties and methods to a list of DrawableContainers. /// Dispatches most of a DrawableContainer's public properties and methods to a list of DrawableContainers.
/// </summary> /// </summary>
[Serializable] [Serializable]
public class DrawableContainerList : List<IDrawableContainer> { public class DrawableContainerList : List<IDrawableContainer>, IDrawableContainerList
private static readonly ComponentResourceManager editorFormResources = new ComponentResourceManager(typeof(ImageEditorForm)); {
private static readonly ComponentResourceManager EditorFormResources = new ComponentResourceManager(typeof(ImageEditorForm));
public Guid ParentID { public Guid ParentID {
get; get;
@ -49,8 +50,8 @@ namespace Greenshot.Drawing {
public DrawableContainerList() { public DrawableContainerList() {
} }
public DrawableContainerList(Guid parentID) { public DrawableContainerList(Guid parentId) {
ParentID = parentID; ParentID = parentId;
} }
public EditStatus Status { public EditStatus Status {
@ -116,14 +117,11 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="allowMerge">true means allow the moves to be merged</param> /// <param name="allowMerge">true means allow the moves to be merged</param>
public void MakeBoundsChangeUndoable(bool allowMerge) { public void MakeBoundsChangeUndoable(bool allowMerge) {
List<IDrawableContainer> movingList = new List<IDrawableContainer>(); if (Count > 0 && Parent != null)
Surface surface = null; {
foreach(DrawableContainer dc in this) { var clone = new DrawableContainerList();
movingList.Add(dc); clone.AddRange(this);
surface = dc._parent; Parent.MakeUndoable(new DrawableContainerBoundsChangeMemento(clone), allowMerge);
}
if (movingList.Count > 0 && surface != null) {
surface.MakeUndoable(new DrawableContainerBoundsChangeMemento(movingList), allowMerge);
} }
} }
@ -171,26 +169,6 @@ namespace Greenshot.Drawing {
} }
} }
/// <summary>
/// Hides the grippers of all elements in the list.
/// </summary>
public void HideGrippers() {
foreach(var dc in this) {
dc.HideGrippers();
dc.Invalidate();
}
}
/// <summary>
/// Shows the grippers of all elements in the list.
/// </summary>
public void ShowGrippers() {
foreach(var dc in this) {
dc.ShowGrippers();
dc.Invalidate();
}
}
/// <summary> /// <summary>
/// Indicates whether on of the elements is clickable at the given location /// Indicates whether on of the elements is clickable at the given location
/// </summary> /// </summary>
@ -266,9 +244,19 @@ namespace Greenshot.Drawing {
/// <param name="renderMode">the rendermode in which the element is to be drawn</param> /// <param name="renderMode">the rendermode in which the element is to be drawn</param>
/// <param name="clipRectangle"></param> /// <param name="clipRectangle"></param>
public void Draw(Graphics g, Bitmap bitmap, RenderMode renderMode, Rectangle clipRectangle) { public void Draw(Graphics g, Bitmap bitmap, RenderMode renderMode, Rectangle clipRectangle) {
foreach(var drawableContainer in this) { if (Parent == null)
{
return;
}
foreach (var drawableContainer in this)
{
var dc = (DrawableContainer)drawableContainer; var dc = (DrawableContainer)drawableContainer;
if (dc.DrawingBounds.IntersectsWith(clipRectangle)) { if (dc.Parent == null)
{
continue;
}
if (dc.DrawingBounds.IntersectsWith(clipRectangle))
{
dc.DrawContent(g, bitmap, renderMode, clipRectangle); dc.DrawContent(g, bitmap, renderMode, clipRectangle);
} }
} }
@ -290,9 +278,16 @@ namespace Greenshot.Drawing {
/// Invalidate the bounds of all the DC's in this list /// Invalidate the bounds of all the DC's in this list
/// </summary> /// </summary>
public void Invalidate() { public void Invalidate() {
foreach(var dc in this) { if (Parent == null)
dc.Invalidate(); {
return;
} }
Rectangle region = Rectangle.Empty;
foreach (var dc in this)
{
region = Rectangle.Union(region, dc.DrawingBounds);
}
Parent.Invalidate(region);
} }
/// <summary> /// <summary>
/// Indicates whether the given list of elements can be pulled up, /// Indicates whether the given list of elements can be pulled up,
@ -300,7 +295,7 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="elements">list of elements to pull up</param> /// <param name="elements">list of elements to pull up</param>
/// <returns>true if the elements could be pulled up</returns> /// <returns>true if the elements could be pulled up</returns>
public bool CanPullUp(DrawableContainerList elements) { public bool CanPullUp(IDrawableContainerList elements) {
if (elements.Count == 0 || elements.Count == Count) { if (elements.Count == 0 || elements.Count == Count) {
return false; return false;
} }
@ -316,13 +311,13 @@ namespace Greenshot.Drawing {
/// Pulls one or several elements up one level in hierarchy (z-index). /// Pulls one or several elements up one level in hierarchy (z-index).
/// </summary> /// </summary>
/// <param name="elements">list of elements to pull up</param> /// <param name="elements">list of elements to pull up</param>
public void PullElementsUp(DrawableContainerList elements) { public void PullElementsUp(IDrawableContainerList elements) {
for(int i=Count-1; i>=0; i--) { for(int i=Count-1; i>=0; i--) {
var dc = this[i]; var dc = this[i];
if (!elements.Contains(dc)) { if (!elements.Contains(dc)) {
continue; continue;
} }
if (Count > (i+1) && !elements.Contains(this[i+1])) { if (Count > i+1 && !elements.Contains(this[i+1])) {
SwapElements(i,i+1); SwapElements(i,i+1);
} }
} }
@ -332,10 +327,11 @@ namespace Greenshot.Drawing {
/// Pulls one or several elements up to the topmost level(s) in hierarchy (z-index). /// Pulls one or several elements up to the topmost level(s) in hierarchy (z-index).
/// </summary> /// </summary>
/// <param name="elements">of elements to pull to top</param> /// <param name="elements">of elements to pull to top</param>
public void PullElementsToTop(DrawableContainerList elements) { public void PullElementsToTop(IDrawableContainerList elements)
{
var dcs = ToArray(); var dcs = ToArray();
for(int i=0; i<dcs.Length; i++) { foreach (var dc in dcs)
var dc = dcs[i]; {
if (!elements.Contains(dc)) { if (!elements.Contains(dc)) {
continue; continue;
} }
@ -351,7 +347,7 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="elements">list of elements to push down</param> /// <param name="elements">list of elements to push down</param>
/// <returns>true if the elements could be pushed down</returns> /// <returns>true if the elements could be pushed down</returns>
public bool CanPushDown(DrawableContainerList elements) { public bool CanPushDown(IDrawableContainerList elements) {
if (elements.Count == 0 || elements.Count == Count) { if (elements.Count == 0 || elements.Count == Count) {
return false; return false;
} }
@ -367,7 +363,7 @@ namespace Greenshot.Drawing {
/// Pushes one or several elements down one level in hierarchy (z-index). /// Pushes one or several elements down one level in hierarchy (z-index).
/// </summary> /// </summary>
/// <param name="elements">list of elements to push down</param> /// <param name="elements">list of elements to push down</param>
public void PushElementsDown(DrawableContainerList elements) { public void PushElementsDown(IDrawableContainerList elements) {
for(int i=0; i<Count; i++) { for(int i=0; i<Count; i++) {
var dc = this[i]; var dc = this[i];
if (!elements.Contains(dc)) { if (!elements.Contains(dc)) {
@ -383,7 +379,7 @@ namespace Greenshot.Drawing {
/// Pushes one or several elements down to the bottommost level(s) in hierarchy (z-index). /// Pushes one or several elements down to the bottommost level(s) in hierarchy (z-index).
/// </summary> /// </summary>
/// <param name="elements">of elements to push to bottom</param> /// <param name="elements">of elements to push to bottom</param>
public void PushElementsToBottom(DrawableContainerList elements) { public void PushElementsToBottom(IDrawableContainerList elements) {
var dcs = ToArray(); var dcs = ToArray();
for(int i=dcs.Length-1; i>=0; i--) { for(int i=dcs.Length-1; i>=0; i--) {
var dc = dcs[i]; var dc = dcs[i];
@ -417,7 +413,7 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="menu"></param> /// <param name="menu"></param>
/// <param name="surface"></param> /// <param name="surface"></param>
public virtual void AddContextMenuItems(ContextMenuStrip menu, Surface surface) { public virtual void AddContextMenuItems(ContextMenuStrip menu, ISurface surface) {
bool push = surface.Elements.CanPushDown(this); bool push = surface.Elements.CanPushDown(this);
bool pull = surface.Elements.CanPullUp(this); bool pull = surface.Elements.CanPullUp(this);
@ -457,7 +453,7 @@ namespace Greenshot.Drawing {
// Duplicate // Duplicate
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_duplicate)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_duplicate));
item.Click += delegate { item.Click += delegate {
DrawableContainerList dcs = this.Clone(); IDrawableContainerList dcs = this.Clone();
dcs.Parent = surface; dcs.Parent = surface;
dcs.MoveBy(10, 10); dcs.MoveBy(10, 10);
surface.AddElements(dcs); surface.AddElements(dcs);
@ -467,49 +463,41 @@ namespace Greenshot.Drawing {
menu.Items.Add(item); menu.Items.Add(item);
// Copy // Copy
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard))
item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); {
Image = (Image) EditorFormResources.GetObject("copyToolStripMenuItem.Image")
};
item.Click += delegate { item.Click += delegate {
ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this);
}; };
menu.Items.Add(item); menu.Items.Add(item);
// Cut // Cut
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard))
item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image"))); {
Image = (Image) EditorFormResources.GetObject("btnCut.Image")
};
item.Click += delegate { item.Click += delegate {
ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this);
List<DrawableContainer> containersToDelete = new List<DrawableContainer>(); surface.RemoveElements(this);
foreach (var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer;
containersToDelete.Add(container);
}
foreach (var container in containersToDelete) {
surface.RemoveElement(container, true);
}
}; };
menu.Items.Add(item); menu.Items.Add(item);
// Delete // Delete
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement));
item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); item.Image = (Image)EditorFormResources.GetObject("removeObjectToolStripMenuItem.Image");
item.Click += delegate { item.Click += delegate {
List<DrawableContainer> containersToDelete = new List<DrawableContainer>(); surface.RemoveElements(this);
foreach(var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer;
containersToDelete.Add(container);
}
foreach (DrawableContainer container in containersToDelete) {
surface.RemoveElement(container, true);
}
}; };
menu.Items.Add(item); menu.Items.Add(item);
// Reset // Reset
bool canReset = false; bool canReset = false;
foreach (var drawableContainer in this) { foreach (var drawableContainer in this)
{
var container = (DrawableContainer)drawableContainer; var container = (DrawableContainer)drawableContainer;
if (container.HasDefaultSize) { if (container.HasDefaultSize)
{
canReset = true; canReset = true;
} }
} }
@ -517,24 +505,29 @@ namespace Greenshot.Drawing {
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_resetsize)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_resetsize));
//item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); //item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image")));
item.Click += delegate { item.Click += delegate {
MakeBoundsChangeUndoable(false);
foreach (var drawableContainer in this) { foreach (var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer; var container = (DrawableContainer) drawableContainer;
if (!container.HasDefaultSize) { if (!container.HasDefaultSize) {
continue; continue;
} }
Size defaultSize = container.DefaultSize; Size defaultSize = container.DefaultSize;
container.Invalidate();
container.MakeBoundsChangeUndoable(false); container.MakeBoundsChangeUndoable(false);
container.Width = defaultSize.Width; container.Width = defaultSize.Width;
container.Height = defaultSize.Height; container.Height = defaultSize.Height;
container.Invalidate();
} }
surface.Invalidate();
}; };
menu.Items.Add(item); menu.Items.Add(item);
} }
} }
public virtual void ShowContextMenu(MouseEventArgs e, Surface surface) { public virtual void ShowContextMenu(MouseEventArgs e, ISurface surface)
{
if (!(surface is Surface))
{
return;
}
bool hasMenu = false; bool hasMenu = false;
foreach (var drawableContainer in this) { foreach (var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer; var container = (DrawableContainer) drawableContainer;
@ -548,7 +541,8 @@ namespace Greenshot.Drawing {
ContextMenuStrip menu = new ContextMenuStrip(); ContextMenuStrip menu = new ContextMenuStrip();
AddContextMenuItems(menu, surface); AddContextMenuItems(menu, surface);
if (menu.Items.Count > 0) { if (menu.Items.Count > 0) {
menu.Show(surface, e.Location); // TODO: cast should be somehow avoided
menu.Show((Surface)surface, e.Location);
while (true) { while (true) {
if (menu.Visible) { if (menu.Visible) {
Application.DoEvents(); Application.DoEvents();
@ -561,5 +555,32 @@ namespace Greenshot.Drawing {
} }
} }
} }
#region IDisposable Support
private bool _disposedValue; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
foreach (var drawableContainer in this)
{
drawableContainer.Dispose();
}
}
_disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -33,6 +33,7 @@ namespace Greenshot.Drawing {
[Serializable()] [Serializable()]
public class EllipseContainer : DrawableContainer { public class EllipseContainer : DrawableContainer {
public EllipseContainer(Surface parent) : base(parent) { public EllipseContainer(Surface parent) : base(parent) {
CreateDefaultAdorners();
} }
protected override void InitializeFields() { protected override void InitializeFields() {
@ -59,12 +60,15 @@ namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// This allows another container to draw an ellipse /// This allows another container to draw an ellipse
/// </summary> /// </summary>
/// <param name="caller"></param> /// <param name="rect"></param>
/// <param name="graphics"></param> /// <param name="graphics"></param>
/// <param name="renderMode"></param> /// <param name="renderMode"></param>
/// <param name="lineThickness"></param>
/// <param name="lineColor"></param>
/// <param name="fillColor"></param>
/// <param name="shadow"></param>
public static void DrawEllipse(Rectangle rect, Graphics graphics, RenderMode renderMode, int lineThickness, Color lineColor, Color fillColor, bool shadow) { public static void DrawEllipse(Rectangle rect, Graphics graphics, RenderMode renderMode, int lineThickness, Color lineColor, Color fillColor, bool shadow) {
bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor));
// draw shadow before anything else // draw shadow before anything else
if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { if (shadow && (lineVisible || Colors.IsVisible(fillColor))) {
int basealpha = 100; int basealpha = 100;

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,147 +20,183 @@
*/ */
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing; using System.Drawing;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Greenshot.Configuration; using Greenshot.Configuration;
using Greenshot.IniFile; using Greenshot.IniFile;
using log4net; using log4net;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing.Fields { namespace Greenshot.Drawing.Fields
{
/// <summary> /// <summary>
/// Basic IFieldHolder implementation, providing access to a set of fields /// Basic IFieldHolder implementation, providing access to a set of fields
/// </summary> /// </summary>
[Serializable] [Serializable]
public abstract class AbstractFieldHolder : IFieldHolder { public abstract class AbstractFieldHolder : IFieldHolder
{
private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder)); private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>(); private static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>();
[NonSerialized]
private readonly IDictionary<IField, PropertyChangedEventHandler> _handlers = new Dictionary<IField, PropertyChangedEventHandler>();
/// <summary> /// <summary>
/// called when a field's value has changed /// called when a field's value has changed
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
private FieldChangedEventHandler fieldChanged; private FieldChangedEventHandler _fieldChanged;
public event FieldChangedEventHandler FieldChanged {
add { fieldChanged += value; } public event FieldChangedEventHandler FieldChanged
remove{ fieldChanged -= value; } {
add { _fieldChanged += value; }
remove { _fieldChanged -= value; }
} }
// we keep two Collections of our fields, dictionary for quick access, list for serialization // we keep two Collections of our fields, dictionary for quick access, list for serialization
// this allows us to use default serialization // this allows us to use default serialization
[NonSerialized] [NonSerialized]
private Dictionary<FieldType, Field> fieldsByType = new Dictionary<FieldType, Field>(); private IDictionary<IFieldType, IField> _fieldsByType = new Dictionary<IFieldType, IField>();
private List<Field> fields = new List<Field>(); private readonly IList<IField> fields = new List<IField>();
public AbstractFieldHolder() {}
[OnDeserialized] [OnDeserialized]
private void OnDeserialized(StreamingContext context) { private void OnDeserialized(StreamingContext context)
fieldsByType = new Dictionary<FieldType, Field>(); {
_fieldsByType = new Dictionary<IFieldType, IField>();
// listen to changing properties // listen to changing properties
foreach(Field field in fields) { foreach (var field in fields)
{
field.PropertyChanged += delegate { field.PropertyChanged += delegate {
if (fieldChanged != null) { _fieldChanged?.Invoke(this, new FieldChangedEventArgs(field));
fieldChanged(this, new FieldChangedEventArgs(field));
}
}; };
fieldsByType[field.FieldType] = field; _fieldsByType[field.FieldType] = field;
} }
} }
public void AddField(Type requestingType, FieldType fieldType, object fieldValue) { public void AddField(Type requestingType, IFieldType fieldType, object fieldValue)
AddField(editorConfiguration.CreateField(requestingType, fieldType, fieldValue)); {
AddField(EditorConfig.CreateField(requestingType, fieldType, fieldValue));
} }
public virtual void AddField(Field field) { public virtual void AddField(IField field)
if (fieldsByType != null && fieldsByType.ContainsKey(field.FieldType)) { {
if (LOG.IsDebugEnabled) { fields.Add(field);
if (_fieldsByType == null)
{
return;
}
if (_fieldsByType.ContainsKey(field.FieldType))
{
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());
} }
} }
fields.Add(field); _fieldsByType[field.FieldType] = field;
fieldsByType[field.FieldType] = field;
field.PropertyChanged += delegate { if(fieldChanged != null) fieldChanged(this, new FieldChangedEventArgs(field)); };
}
public void RemoveField(Field field) { _handlers[field] = (sender, args) =>
fields.Remove(field); {
fieldsByType.Remove(field.FieldType); _fieldChanged?.Invoke(this, new FieldChangedEventArgs(field));
field.PropertyChanged -= delegate {
if (fieldChanged != null) {
fieldChanged(this, new FieldChangedEventArgs(field));
}
}; };
field.PropertyChanged += _handlers[field];
} }
public List<Field> GetFields() { public void RemoveField(IField field)
{
fields.Remove(field);
_fieldsByType.Remove(field.FieldType);
field.PropertyChanged -= _handlers[field];
_handlers.Remove(field);
}
public IList<IField> GetFields()
{
return fields; return fields;
} }
public Field GetField(FieldType fieldType) { public IField GetField(IFieldType fieldType)
try { {
return fieldsByType[fieldType]; try
} catch(KeyNotFoundException e) { {
return _fieldsByType[fieldType];
}
catch (KeyNotFoundException e)
{
throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType(), e); throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType(), e);
} }
} }
public object GetFieldValue(FieldType fieldType) { public object GetFieldValue(IFieldType fieldType)
{
return GetField(fieldType).Value; return GetField(fieldType).Value;
} }
#region convenience methods to save us some casts outside #region convenience methods to save us some casts outside
public string GetFieldValueAsString(FieldType fieldType) { public string GetFieldValueAsString(IFieldType fieldType)
{
return Convert.ToString(GetFieldValue(fieldType)); return Convert.ToString(GetFieldValue(fieldType));
} }
public int GetFieldValueAsInt(FieldType fieldType) { public int GetFieldValueAsInt(IFieldType fieldType)
{
return Convert.ToInt32(GetFieldValue(fieldType)); return Convert.ToInt32(GetFieldValue(fieldType));
} }
public decimal GetFieldValueAsDecimal(FieldType fieldType) { public decimal GetFieldValueAsDecimal(IFieldType fieldType)
{
return Convert.ToDecimal(GetFieldValue(fieldType)); return Convert.ToDecimal(GetFieldValue(fieldType));
} }
public double GetFieldValueAsDouble(FieldType fieldType) { public double GetFieldValueAsDouble(IFieldType fieldType)
{
return Convert.ToDouble(GetFieldValue(fieldType)); return Convert.ToDouble(GetFieldValue(fieldType));
} }
public float GetFieldValueAsFloat(FieldType fieldType) { public float GetFieldValueAsFloat(IFieldType fieldType)
{
return Convert.ToSingle(GetFieldValue(fieldType)); return Convert.ToSingle(GetFieldValue(fieldType));
} }
public bool GetFieldValueAsBool(FieldType fieldType) { public bool GetFieldValueAsBool(IFieldType fieldType)
{
return Convert.ToBoolean(GetFieldValue(fieldType)); return Convert.ToBoolean(GetFieldValue(fieldType));
} }
public Color GetFieldValueAsColor(FieldType fieldType) { public Color GetFieldValueAsColor(IFieldType fieldType)
{
return (Color)GetFieldValue(fieldType); return (Color)GetFieldValue(fieldType);
} }
#endregion #endregion
public bool HasField(FieldType fieldType) { public bool HasField(IFieldType fieldType)
return fieldsByType.ContainsKey(fieldType); {
return _fieldsByType.ContainsKey(fieldType);
} }
public bool HasFieldValue(FieldType fieldType) { public bool HasFieldValue(IFieldType fieldType)
return HasField(fieldType) && fieldsByType[fieldType].HasValue; {
return HasField(fieldType) && _fieldsByType[fieldType].HasValue;
} }
public void SetFieldValue(FieldType fieldType, object value) { public void SetFieldValue(IFieldType fieldType, object value)
try { {
fieldsByType[fieldType].Value = value; try
} catch(KeyNotFoundException e) { {
_fieldsByType[fieldType].Value = value;
}
catch (KeyNotFoundException e)
{
throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType(), e); throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType(), e);
} }
} }
protected void OnFieldChanged(object sender, FieldChangedEventArgs e){ protected void OnFieldChanged(object sender, FieldChangedEventArgs e)
if (fieldChanged != null) { {
fieldChanged(sender, e); _fieldChanged?.Invoke(sender, e);
}
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -18,87 +18,110 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace Greenshot.Drawing.Fields { namespace Greenshot.Drawing.Fields
{
/// <summary> /// <summary>
/// Basic IFieldHolderWithChildren implementation. Similar to IFieldHolder, /// Basic IFieldHolderWithChildren implementation. Similar to IFieldHolder,
/// but has a List<IFieldHolder> of children. /// but has a List of IFieldHolder for children.
/// Field values are passed to and from children as well. /// Field values are passed to and from children as well.
/// </summary> /// </summary>
[Serializable()] [Serializable]
public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder { public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder
{
FieldChangedEventHandler fieldChangedEventHandler; [NonSerialized]
private readonly FieldChangedEventHandler _fieldChangedEventHandler;
[NonSerialized] [NonSerialized]
private EventHandler childrenChanged; private EventHandler childrenChanged;
public event EventHandler ChildrenChanged { public event EventHandler ChildrenChanged
{
add { childrenChanged += value; } add { childrenChanged += value; }
remove { childrenChanged -= value; } remove { childrenChanged -= value; }
} }
public List<IFieldHolder> Children = new List<IFieldHolder>(); public List<IFieldHolder> Children = new List<IFieldHolder>();
public AbstractFieldHolderWithChildren() { public AbstractFieldHolderWithChildren()
fieldChangedEventHandler = OnFieldChanged; {
_fieldChangedEventHandler = OnFieldChanged;
} }
[OnDeserialized()] [OnDeserialized()]
private void OnDeserialized(StreamingContext context) { private void OnDeserialized(StreamingContext context)
{
// listen to changing properties // listen to changing properties
foreach(IFieldHolder fieldHolder in Children) { foreach (IFieldHolder fieldHolder in Children)
fieldHolder.FieldChanged += fieldChangedEventHandler; {
fieldHolder.FieldChanged += _fieldChangedEventHandler;
} }
if(childrenChanged != null) childrenChanged(this, EventArgs.Empty); childrenChanged?.Invoke(this, EventArgs.Empty);
} }
public void AddChild(IFieldHolder fieldHolder) { public void AddChild(IFieldHolder fieldHolder)
{
Children.Add(fieldHolder); Children.Add(fieldHolder);
fieldHolder.FieldChanged += fieldChangedEventHandler; fieldHolder.FieldChanged += _fieldChangedEventHandler;
if(childrenChanged != null) childrenChanged(this, EventArgs.Empty); childrenChanged?.Invoke(this, EventArgs.Empty);
} }
public void RemoveChild(IFieldHolder fieldHolder) { public void RemoveChild(IFieldHolder fieldHolder)
{
Children.Remove(fieldHolder); Children.Remove(fieldHolder);
fieldHolder.FieldChanged -= fieldChangedEventHandler; fieldHolder.FieldChanged -= _fieldChangedEventHandler;
if(childrenChanged != null) childrenChanged(this, EventArgs.Empty); childrenChanged?.Invoke(this, EventArgs.Empty);
} }
public new List<Field> GetFields() { public new IList<IField> GetFields()
List<Field> ret = new List<Field>(); {
var ret = new List<IField>();
ret.AddRange(base.GetFields()); ret.AddRange(base.GetFields());
foreach(IFieldHolder fh in Children) { foreach (IFieldHolder fh in Children)
{
ret.AddRange(fh.GetFields()); ret.AddRange(fh.GetFields());
} }
return ret; return ret;
} }
public new Field GetField(FieldType fieldType) { public new IField GetField(IFieldType fieldType)
Field ret = null; {
if(base.HasField(fieldType)) { IField ret = null;
if (base.HasField(fieldType))
{
ret = base.GetField(fieldType); ret = base.GetField(fieldType);
} else { }
foreach(IFieldHolder fh in Children) { else
if(fh.HasField(fieldType)) { {
foreach (IFieldHolder fh in Children)
{
if (fh.HasField(fieldType))
{
ret = fh.GetField(fieldType); ret = fh.GetField(fieldType);
break; break;
} }
} }
} }
if(ret == null) { if (ret == null)
{
throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType()); throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType());
} }
return ret; return ret;
} }
public new bool HasField(FieldType fieldType) { public new bool HasField(IFieldType fieldType)
{
bool ret = base.HasField(fieldType); bool ret = base.HasField(fieldType);
if(!ret) { if (!ret)
foreach(IFieldHolder fh in Children) { {
if(fh.HasField(fieldType)) { foreach (IFieldHolder fh in Children)
{
if (fh.HasField(fieldType))
{
ret = true; ret = true;
break; break;
} }
@ -107,13 +130,15 @@ namespace Greenshot.Drawing.Fields {
return ret; return ret;
} }
public new bool HasFieldValue(FieldType fieldType) { public new bool HasFieldValue(IFieldType fieldType)
Field f = GetField(fieldType); {
IField f = GetField(fieldType);
return f != null && f.HasValue; return f != null && f.HasValue;
} }
public new void SetFieldValue(FieldType fieldType, object value) { public new void SetFieldValue(IFieldType fieldType, object value)
Field f = GetField(fieldType); {
IField f = GetField(fieldType);
if (f != null) f.Value = value; if (f != null) f.Value = value;
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -26,8 +26,6 @@ namespace Greenshot.Drawing.Fields.Binding {
/// </summary> /// </summary>
public abstract class AbstractBindingConverter<T1,T2> : IBindingConverter public abstract class AbstractBindingConverter<T1,T2> : IBindingConverter
{ {
public AbstractBindingConverter() {}
public object convert(object o) { public object convert(object o) {
if(o == null) { if(o == null) {
return null; return null;

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -29,14 +29,14 @@ namespace Greenshot.Drawing.Fields.Binding {
/// behavior (e.g. when binding to a /// behavior (e.g. when binding to a
/// </summary> /// </summary>
public class BidirectionalBinding { public class BidirectionalBinding {
private INotifyPropertyChanged controlObject; private readonly INotifyPropertyChanged _controlObject;
private INotifyPropertyChanged fieldObject; private readonly INotifyPropertyChanged _fieldObject;
private string controlPropertyName; private readonly string _controlPropertyName;
private string fieldPropertyName; private readonly string _fieldPropertyName;
private bool updatingControl = false; private bool _updatingControl;
private bool updatingField = false; private bool _updatingField;
private IBindingConverter converter; private IBindingConverter _converter;
private IBindingValidator validator; private readonly IBindingValidator _validator;
/// <summary> /// <summary>
/// Whether or not null values are passed on to the other object. /// Whether or not null values are passed on to the other object.
@ -46,18 +46,18 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <summary> /// <summary>
/// Bind properties of two objects bidirectionally /// Bind properties of two objects bidirectionally
/// </summary> /// </summary>
/// <param name="object1">Object containing 1st property to bind</param> /// <param name="controlObject">Object containing 1st property to bind</param>
/// <param name="property1">Property of 1st object to bind</param> /// <param name="controlPropertyName">Property of 1st object to bind</param>
/// <param name="object2">Object containing 2nd property to bind</param> /// <param name="fieldObject">Object containing 2nd property to bind</param>
/// <param name="property2">Property of 2nd object to bind</param> /// <param name="fieldPropertyName">Property of 2nd object to bind</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName) { public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName) {
this.controlObject = controlObject; _controlObject = controlObject;
this.fieldObject = fieldObject; _fieldObject = fieldObject;
this.controlPropertyName = controlPropertyName; _controlPropertyName = controlPropertyName;
this.fieldPropertyName = fieldPropertyName; _fieldPropertyName = fieldPropertyName;
this.controlObject.PropertyChanged += ControlPropertyChanged; _controlObject.PropertyChanged += ControlPropertyChanged;
this.fieldObject.PropertyChanged += FieldPropertyChanged; _fieldObject.PropertyChanged += FieldPropertyChanged;
} }
/// <summary> /// <summary>
@ -69,7 +69,7 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <param name="fieldPropertyName">Property of 2nd object to bind</param> /// <param name="fieldPropertyName">Property of 2nd object to bind</param>
/// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param> /// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) { public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) {
this.converter = converter; _converter = converter;
} }
/// <summary> /// <summary>
@ -82,7 +82,7 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <param name="fieldPropertyName">Property of 2nd object to bind</param> /// <param name="fieldPropertyName">Property of 2nd object to bind</param>
/// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param> /// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) { public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) {
this.validator = validator; _validator = validator;
} }
/// <summary> /// <summary>
@ -96,46 +96,46 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param> /// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param>
/// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param> /// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) { public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) {
this.validator = validator; _validator = validator;
} }
public void ControlPropertyChanged(object sender, PropertyChangedEventArgs e) { public void ControlPropertyChanged(object sender, PropertyChangedEventArgs e) {
if (!updatingControl && e.PropertyName.Equals(controlPropertyName)) { if (!_updatingControl && e.PropertyName.Equals(_controlPropertyName)) {
updatingField = true; _updatingField = true;
synchronize(controlObject, controlPropertyName, fieldObject, fieldPropertyName); Synchronize(_controlObject, _controlPropertyName, _fieldObject, _fieldPropertyName);
updatingField = false; _updatingField = false;
} }
} }
public void FieldPropertyChanged(object sender, PropertyChangedEventArgs e) { public void FieldPropertyChanged(object sender, PropertyChangedEventArgs e) {
if (!updatingField && e.PropertyName.Equals(fieldPropertyName)) { if (!_updatingField && e.PropertyName.Equals(_fieldPropertyName)) {
updatingControl = true; _updatingControl = true;
synchronize(fieldObject, fieldPropertyName, controlObject, controlPropertyName); Synchronize(_fieldObject, _fieldPropertyName, _controlObject, _controlPropertyName);
updatingControl = false; _updatingControl = false;
} }
} }
private void synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) { private void Synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) {
PropertyInfo targetPropertyInfo = resolvePropertyInfo(targetObject, targetProperty); PropertyInfo targetPropertyInfo = ResolvePropertyInfo(targetObject, targetProperty);
PropertyInfo sourcePropertyInfo = resolvePropertyInfo(sourceObject, sourceProperty); PropertyInfo sourcePropertyInfo = ResolvePropertyInfo(sourceObject, sourceProperty);
if (sourcePropertyInfo != null && targetPropertyInfo != null && targetPropertyInfo.CanWrite) { if (sourcePropertyInfo != null && targetPropertyInfo != null && targetPropertyInfo.CanWrite) {
object bValue = sourcePropertyInfo.GetValue(sourceObject, null); 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 { try {
if (validator == null || validator.validate(bValue)) { if (_validator == null || _validator.validate(bValue)) {
targetPropertyInfo.SetValue(targetObject, bValue, null); targetPropertyInfo.SetValue(targetObject, bValue, null);
} }
} catch (Exception e) { } catch (Exception e) {
throw new MemberAccessException("Could not set property '"+targetProperty+"' to '"+bValue+"' ["+((bValue!=null)?bValue.GetType().Name:"")+"] on "+targetObject+". Probably other type than expected, IBindingCoverter to the rescue.", e); throw new MemberAccessException("Could not set property '"+targetProperty+"' to '"+bValue+"' ["+(bValue?.GetType().Name ?? "")+"] on "+targetObject+". Probably other type than expected, IBindingCoverter to the rescue.", e);
} }
} }
} }
private PropertyInfo resolvePropertyInfo(object obj, string property) { private static PropertyInfo ResolvePropertyInfo(object obj, string property) {
PropertyInfo ret = null; PropertyInfo ret = null;
string[] properties = property.Split(".".ToCharArray()); string[] properties = property.Split(".".ToCharArray());
for(int i=0; i<properties.Length; i++) { for(int i=0; i<properties.Length; i++) {
@ -149,8 +149,8 @@ namespace Greenshot.Drawing.Fields.Binding {
} }
public IBindingConverter Converter { public IBindingConverter Converter {
get { return converter; } get { return _converter; }
set { converter = value; } set { _converter = value; }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -22,7 +22,7 @@ using System;
namespace Greenshot.Drawing.Fields.Binding { namespace Greenshot.Drawing.Fields.Binding {
/// <summary> /// <summary>
/// Converts decimal to double (%) and vice versa, e.g. 95f <---> 0.95d /// Converts decimal to double (%) and vice versa, e.g. 95f to 0.95d
/// </summary> /// </summary>
public class DecimalDoublePercentageConverter : AbstractBindingConverter<double, decimal> public class DecimalDoublePercentageConverter : AbstractBindingConverter<double, decimal>
{ {

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -18,35 +18,49 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
using System.ComponentModel; using System.ComponentModel;
namespace Greenshot.Drawing.Fields { namespace Greenshot.Drawing.Fields
{
/// <summary> /// <summary>
/// Represents a single field of a drawable element, i.e. /// Represents a single field of a drawable element, i.e.
/// line thickness of a rectangle. /// line thickness of a rectangle.
/// </summary> /// </summary>
[Serializable] [Serializable]
public class Field : INotifyPropertyChanged { public class Field : IField
{
[field: NonSerialized] [field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;
public object myValue; private object _myValue;
public object Value { public object Value
get { {
return myValue; get
{
return _myValue;
} }
set { set
if (!Equals(myValue,value)) { {
myValue = value; if (!Equals(_myValue, value))
if (PropertyChanged!=null) { {
PropertyChanged(this, new PropertyChangedEventArgs("Value")); _myValue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
} }
} }
} }
public IFieldType FieldType
{
get;
set;
}
public string Scope
{
get;
set;
} }
public FieldType FieldType;
public string Scope;
/// <summary> /// <summary>
/// Constructs a new Field instance, usually you should be using FieldFactory /// Constructs a new Field instance, usually you should be using FieldFactory
@ -59,37 +73,39 @@ namespace Greenshot.Drawing.Fields {
/// When scope is set to a Type (e.g. typeof(RectangleContainer)), its value /// When scope is set to a Type (e.g. typeof(RectangleContainer)), its value
/// should not be reused for FieldHolders of another Type (e.g. typeof(EllipseContainer)) /// should not be reused for FieldHolders of another Type (e.g. typeof(EllipseContainer))
/// </param> /// </param>
public Field(FieldType fieldType, Type scope) { public Field(IFieldType fieldType, Type scope)
{
FieldType = fieldType; FieldType = fieldType;
Scope = scope.Name; Scope = scope.Name;
} }
public Field(FieldType fieldType, string scope) { public Field(IFieldType fieldType, string scope)
{
FieldType = fieldType; FieldType = fieldType;
Scope = scope; Scope = scope;
} }
public Field(FieldType fieldType) { public Field(IFieldType fieldType)
{
FieldType = fieldType; FieldType = fieldType;
} }
/// <summary> /// <summary>
/// Returns true if this field holds a value other than null. /// Returns true if this field holds a value other than null.
/// </summary> /// </summary>
public bool HasValue { public bool HasValue => Value != null;
get{ return Value != null; }
}
/// <summary> /// <summary>
/// Creates a flat clone of this Field. The fields value itself is not cloned. /// Creates a flat clone of this Field. The fields value itself is not cloned.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public Field Clone() { public Field Clone()
Field ret = new Field(FieldType, Scope); {
ret.Value = Value; return new Field(FieldType, Scope) {Value = Value};
return ret;
} }
public override int GetHashCode() { public override int GetHashCode()
{
int hashCode = 0; int hashCode = 0;
unchecked { unchecked
{
hashCode += 1000000009 * FieldType.GetHashCode(); hashCode += 1000000009 * FieldType.GetHashCode();
if (Scope != null) if (Scope != null)
hashCode += 1000000021 * Scope.GetHashCode(); hashCode += 1000000021 * Scope.GetHashCode();
@ -97,32 +113,19 @@ namespace Greenshot.Drawing.Fields {
return hashCode; return hashCode;
} }
public override bool Equals(object obj) { public override bool Equals(object obj)
Field other = obj as Field; {
if (other == null) { var other = obj as Field;
if (other == null)
{
return false; return false;
} }
return FieldType == other.FieldType && Equals(Scope, other.Scope); return FieldType == other.FieldType && Equals(Scope, other.Scope);
} }
public override string ToString() { public override string ToString()
return string.Format("[Field FieldType={1} Value={0} Scope={2}]", myValue, FieldType, Scope); {
} return string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope);
}
/// <summary>
/// EventHandler to be used when a field value changes
/// </summary>
public delegate void FieldChangedEventHandler(object sender, FieldChangedEventArgs e);
/// <summary>
/// EventArgs to be used with FieldChangedEventHandler
/// </summary>
public class FieldChangedEventArgs : EventArgs {
public readonly Field Field;
public FieldChangedEventArgs(Field field) {
Field = field;
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -19,15 +19,17 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System;
using Greenshot.Configuration;
using Greenshot.IniFile;
using Greenshot.Plugin;
using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Interfaces.Drawing;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using Greenshot.Configuration; namespace Greenshot.Drawing.Fields
using Greenshot.IniFile; {
using Greenshot.Plugin.Drawing;
using log4net;
namespace Greenshot.Drawing.Fields {
/// <summary> /// <summary>
/// Represents the current set of properties for the editor. /// Represents the current set of properties for the editor.
/// When one of EditorProperties' properties is updated, the change will be promoted /// When one of EditorProperties' properties is updated, the change will be promoted
@ -39,88 +41,108 @@ namespace Greenshot.Drawing.Fields {
/// Properties that do not apply for ALL selected elements are null (or 0 respectively) /// Properties that do not apply for ALL selected elements are null (or 0 respectively)
/// If the property values of the selected elements differ, the value of the last bound element wins. /// If the property values of the selected elements differ, the value of the last bound element wins.
/// </summary> /// </summary>
public class FieldAggregator : AbstractFieldHolder { [Serializable]
public sealed class FieldAggregator : AbstractFieldHolder
{
private List<IDrawableContainer> boundContainers; private readonly IDrawableContainerList _boundContainers;
private bool internalUpdateRunning = false; private bool _internalUpdateRunning;
enum Status {IDLE, BINDING, UPDATING}; private static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>();
private static readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator)); public FieldAggregator(ISurface parent)
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>(); {
foreach (var fieldType in FieldType.Values)
public FieldAggregator() { {
foreach(FieldType fieldType in FieldType.Values) { var field = new Field(fieldType, GetType());
Field field = new Field(fieldType, GetType());
AddField(field); AddField(field);
} }
boundContainers = new List<IDrawableContainer>(); _boundContainers = new DrawableContainerList
{
Parent = parent
};
} }
public override void AddField(Field field) { public override void AddField(IField field)
{
base.AddField(field); base.AddField(field);
field.PropertyChanged += OwnPropertyChanged; field.PropertyChanged += OwnPropertyChanged;
} }
public void BindElements(DrawableContainerList dcs) { public void BindElements(IDrawableContainerList dcs)
foreach(DrawableContainer dc in dcs) { {
foreach (var dc in dcs)
{
BindElement(dc); BindElement(dc);
} }
} }
public void BindElement(IDrawableContainer dc) { public void BindElement(IDrawableContainer dc)
{
DrawableContainer container = dc as DrawableContainer; DrawableContainer container = dc as DrawableContainer;
if (container != null && !boundContainers.Contains(container)) { if (container == null || _boundContainers.Contains(container))
boundContainers.Add(container); {
return;
}
_boundContainers.Add(container);
container.ChildrenChanged += delegate { container.ChildrenChanged += delegate {
UpdateFromBoundElements(); UpdateFromBoundElements();
}; };
UpdateFromBoundElements(); UpdateFromBoundElements();
} }
}
public void BindAndUpdateElement(IDrawableContainer dc) { public void BindAndUpdateElement(IDrawableContainer dc)
{
UpdateElement(dc); UpdateElement(dc);
BindElement(dc); BindElement(dc);
} }
public void UpdateElement(IDrawableContainer dc) { public void UpdateElement(IDrawableContainer dc)
{
DrawableContainer container = dc as DrawableContainer; DrawableContainer container = dc as DrawableContainer;
if (container == null) { if (container == null)
{
return; return;
} }
internalUpdateRunning = true; _internalUpdateRunning = true;
foreach(Field field in GetFields()) { foreach (var field in GetFields())
if (container.HasField(field.FieldType) && field.HasValue) { {
if (container.HasField(field.FieldType) && field.HasValue)
{
//if(LOG.IsDebugEnabled) LOG.Debug(" "+field+ ": "+field.Value); //if(LOG.IsDebugEnabled) LOG.Debug(" "+field+ ": "+field.Value);
container.SetFieldValue(field.FieldType, field.Value); container.SetFieldValue(field.FieldType, field.Value);
} }
} }
internalUpdateRunning = false; _internalUpdateRunning = false;
} }
public void UnbindElement(IDrawableContainer dc) { public void UnbindElement(IDrawableContainer dc)
if (boundContainers.Contains(dc)) { {
boundContainers.Remove(dc); if (_boundContainers.Contains(dc))
{
_boundContainers.Remove(dc);
UpdateFromBoundElements(); UpdateFromBoundElements();
} }
} }
public void Clear() { public void Clear()
{
ClearFields(); ClearFields();
boundContainers.Clear(); _boundContainers.Clear();
UpdateFromBoundElements(); UpdateFromBoundElements();
} }
/// <summary> /// <summary>
/// sets all field values to null, however does not remove fields /// sets all field values to null, however does not remove fields
/// </summary> /// </summary>
private void ClearFields() { private void ClearFields()
internalUpdateRunning = true; {
foreach(Field field in GetFields()) { _internalUpdateRunning = true;
foreach (var field in GetFields())
{
field.Value = null; field.Value = null;
} }
internalUpdateRunning = false; _internalUpdateRunning = false;
} }
/// <summary> /// <summary>
@ -128,59 +150,73 @@ namespace Greenshot.Drawing.Fields {
/// Fields that do not apply to every bound element are set to null, or 0 respectively. /// Fields that do not apply to every bound element are set to null, or 0 respectively.
/// All other fields will be set to the field value of the least bound element. /// All other fields will be set to the field value of the least bound element.
/// </summary> /// </summary>
private void UpdateFromBoundElements() { private void UpdateFromBoundElements()
{
ClearFields(); ClearFields();
internalUpdateRunning = true; _internalUpdateRunning = true;
foreach(Field field in FindCommonFields()) { foreach (var field in FindCommonFields())
{
SetFieldValue(field.FieldType, field.Value); SetFieldValue(field.FieldType, field.Value);
} }
internalUpdateRunning = false; _internalUpdateRunning = false;
} }
private List<Field> FindCommonFields() { private IList<IField> FindCommonFields()
List<Field> returnFields = null; {
if (boundContainers.Count > 0) { IList<IField> returnFields = null;
if (_boundContainers.Count > 0)
{
// take all fields from the least selected container... // take all fields from the least selected container...
DrawableContainer leastSelectedContainer = boundContainers[boundContainers.Count - 1] as DrawableContainer; DrawableContainer leastSelectedContainer = _boundContainers[_boundContainers.Count - 1] as DrawableContainer;
if (leastSelectedContainer != null) { if (leastSelectedContainer != null)
{
returnFields = leastSelectedContainer.GetFields(); returnFields = leastSelectedContainer.GetFields();
for (int i = 0; i < boundContainers.Count - 1; i++) { for (int i = 0; i < _boundContainers.Count - 1; i++)
DrawableContainer dc = boundContainers[i] as DrawableContainer; {
if (dc != null) { DrawableContainer dc = _boundContainers[i] as DrawableContainer;
List<Field> fieldsToRemove = new List<Field>(); if (dc != null)
foreach (Field f in returnFields) { {
IList<IField> fieldsToRemove = new List<IField>();
foreach (IField field in returnFields)
{
// ... throw out those that do not apply to one of the other containers // ... throw out those that do not apply to one of the other containers
if (!dc.HasField(f.FieldType)) { if (!dc.HasField(field.FieldType))
fieldsToRemove.Add(f); {
fieldsToRemove.Add(field);
} }
} }
foreach (Field f in fieldsToRemove) { foreach (var field in fieldsToRemove)
returnFields.Remove(f); {
returnFields.Remove(field);
} }
} }
} }
} }
} }
if (returnFields == null) { return returnFields ?? new List<IField>();
returnFields = new List<Field>();
}
return returnFields;
} }
public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea) { public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea)
Field field = (Field) sender; {
if (!internalUpdateRunning && field.Value != null) { IField field = (IField)sender;
foreach(DrawableContainer drawableContainer in boundContainers) { if (_internalUpdateRunning || field.Value == null)
if (drawableContainer.HasField(field.FieldType)) { {
Field drawableContainerField = drawableContainer.GetField(field.FieldType); return;
}
foreach (var drawableContainer1 in _boundContainers)
{
var drawableContainer = (DrawableContainer) drawableContainer1;
if (!drawableContainer.HasField(field.FieldType))
{
continue;
}
IField drawableContainerField = drawableContainer.GetField(field.FieldType);
// Notify before change, so we can e.g. invalidate the area // Notify before change, so we can e.g. invalidate the area
drawableContainer.BeforeFieldChange(drawableContainerField, field.Value); drawableContainer.BeforeFieldChange(drawableContainerField, field.Value);
drawableContainerField.Value = field.Value; drawableContainerField.Value = field.Value;
// update last used from DC field, so that scope is honored // update last used from DC field, so that scope is honored
editorConfiguration.UpdateLastFieldValue(drawableContainerField); EditorConfig.UpdateLastFieldValue(drawableContainerField);
}
}
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -18,38 +18,41 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
namespace Greenshot.Drawing.Fields { namespace Greenshot.Drawing.Fields
{
/// <summary> /// <summary>
/// Defines all FieldTypes + their default value. /// Defines all FieldTypes + their default value.
/// (The additional value is why this is not an enum) /// (The additional value is why this is not an enum)
/// </summary> /// </summary>
[Serializable] [Serializable]
public class FieldType { public class FieldType : IFieldType
{
public static readonly FieldType ARROWHEADS = new FieldType("ARROWHEADS"); public static readonly IFieldType ARROWHEADS = new FieldType("ARROWHEADS");
public static readonly FieldType BLUR_RADIUS = new FieldType("BLUR_RADIUS"); public static readonly IFieldType BLUR_RADIUS = new FieldType("BLUR_RADIUS");
public static readonly FieldType BRIGHTNESS = new FieldType("BRIGHTNESS"); public static readonly IFieldType BRIGHTNESS = new FieldType("BRIGHTNESS");
public static readonly FieldType FILL_COLOR = new FieldType("FILL_COLOR"); public static readonly IFieldType FILL_COLOR = new FieldType("FILL_COLOR");
public static readonly FieldType FONT_BOLD = new FieldType("FONT_BOLD"); public static readonly IFieldType FONT_BOLD = new FieldType("FONT_BOLD");
public static readonly FieldType FONT_FAMILY = new FieldType("FONT_FAMILY"); public static readonly IFieldType FONT_FAMILY = new FieldType("FONT_FAMILY");
public static readonly FieldType FONT_ITALIC = new FieldType("FONT_ITALIC"); public static readonly IFieldType FONT_ITALIC = new FieldType("FONT_ITALIC");
public static readonly FieldType FONT_SIZE = new FieldType("FONT_SIZE"); public static readonly IFieldType FONT_SIZE = new FieldType("FONT_SIZE");
public static readonly FieldType TEXT_HORIZONTAL_ALIGNMENT = new FieldType("TEXT_HORIZONTAL_ALIGNMENT"); public static readonly IFieldType TEXT_HORIZONTAL_ALIGNMENT = new FieldType("TEXT_HORIZONTAL_ALIGNMENT");
public static readonly FieldType TEXT_VERTICAL_ALIGNMENT = new FieldType("TEXT_VERTICAL_ALIGNMENT"); public static readonly IFieldType TEXT_VERTICAL_ALIGNMENT = new FieldType("TEXT_VERTICAL_ALIGNMENT");
public static readonly FieldType HIGHLIGHT_COLOR = new FieldType("HIGHLIGHT_COLOR"); public static readonly IFieldType HIGHLIGHT_COLOR = new FieldType("HIGHLIGHT_COLOR");
public static readonly FieldType LINE_COLOR = new FieldType("LINE_COLOR"); public static readonly IFieldType LINE_COLOR = new FieldType("LINE_COLOR");
public static readonly FieldType LINE_THICKNESS = new FieldType("LINE_THICKNESS"); public static readonly IFieldType LINE_THICKNESS = new FieldType("LINE_THICKNESS");
public static readonly FieldType MAGNIFICATION_FACTOR = new FieldType("MAGNIFICATION_FACTOR"); public static readonly IFieldType MAGNIFICATION_FACTOR = new FieldType("MAGNIFICATION_FACTOR");
public static readonly FieldType PIXEL_SIZE = new FieldType("PIXEL_SIZE"); public static readonly IFieldType PIXEL_SIZE = new FieldType("PIXEL_SIZE");
public static readonly FieldType PREVIEW_QUALITY = new FieldType("PREVIEW_QUALITY"); public static readonly IFieldType PREVIEW_QUALITY = new FieldType("PREVIEW_QUALITY");
public static readonly FieldType SHADOW = new FieldType("SHADOW"); public static readonly IFieldType SHADOW = new FieldType("SHADOW");
public static readonly FieldType PREPARED_FILTER_OBFUSCATE = new FieldType("PREPARED_FILTER_OBFUSCATE"); public static readonly IFieldType PREPARED_FILTER_OBFUSCATE = new FieldType("PREPARED_FILTER_OBFUSCATE");
public static readonly FieldType PREPARED_FILTER_HIGHLIGHT = new FieldType("PREPARED_FILTER_HIGHLIGHT"); public static readonly IFieldType PREPARED_FILTER_HIGHLIGHT = new FieldType("PREPARED_FILTER_HIGHLIGHT");
public static readonly FieldType FLAGS = new FieldType("FLAGS"); public static readonly IFieldType FLAGS = new FieldType("FLAGS");
public static FieldType[] Values = new FieldType[]{ public static IFieldType[] Values = {
ARROWHEADS, ARROWHEADS,
BLUR_RADIUS, BLUR_RADIUS,
BRIGHTNESS, BRIGHTNESS,
@ -72,24 +75,25 @@ namespace Greenshot.Drawing.Fields {
FLAGS FLAGS
}; };
[Flags] public string Name
public enum Flag { {
NONE = 0, get;
CONFIRMABLE = 1 set;
} }
private FieldType(string name)
public string Name; {
private FieldType(string name) {
Name = name; Name = name;
} }
public override string ToString() { public override string ToString()
{
return Name; return Name;
} }
public override int GetHashCode() public override int GetHashCode()
{ {
int hashCode = 0; int hashCode = 0;
unchecked { unchecked
{
if (Name != null) if (Name != null)
hashCode += 1000000009 * Name.GetHashCode(); hashCode += 1000000009 * Name.GetHashCode();
} }
@ -100,19 +104,20 @@ namespace Greenshot.Drawing.Fields {
{ {
FieldType other = obj as FieldType; FieldType other = obj as FieldType;
if (other == null) if (other == null)
{
return false; return false;
}
return Equals(Name, other.Name); return Equals(Name, other.Name);
} }
public static bool operator ==(FieldType a, FieldType b) { public static bool operator ==(FieldType a, FieldType b)
{
return Equals(a, b); return Equals(a, b);
} }
public static bool operator !=(FieldType a, FieldType b) { public static bool operator !=(FieldType a, FieldType b)
{
return !Equals(a, b); return !Equals(a, b);
} }
} }
} }

View file

@ -3,7 +3,7 @@
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -24,6 +24,7 @@ using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Runtime.Serialization;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -40,6 +41,18 @@ namespace Greenshot.Drawing {
} }
public FilterContainer(Surface parent) : base(parent) { public FilterContainer(Surface parent) : base(parent) {
Init();
}
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
} }
protected override void InitializeFields() { protected override void InitializeFields() {
@ -52,7 +65,7 @@ namespace Greenshot.Drawing {
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS);
Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR);
bool shadow = GetFieldValueAsBool(FieldType.SHADOW); bool shadow = GetFieldValueAsBool(FieldType.SHADOW);
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
if (lineVisible) { if (lineVisible) {
graphics.SmoothingMode = SmoothingMode.HighSpeed; graphics.SmoothingMode = SmoothingMode.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
@ -69,7 +82,7 @@ namespace Greenshot.Drawing {
Rectangle shadowRect = GuiRectangle.GetGuiRectangle(Left + currentStep, Top + currentStep, Width, Height); Rectangle shadowRect = GuiRectangle.GetGuiRectangle(Left + currentStep, Top + currentStep, Width, Height);
graphics.DrawRectangle(shadowPen, shadowRect); graphics.DrawRectangle(shadowPen, shadowRect);
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -25,13 +25,13 @@ using System.Drawing;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
namespace Greenshot.Drawing.Filters {
/// <summary> /// <summary>
/// Graphical filter which can be added to DrawableContainer. /// Graphical filter which can be added to DrawableContainer.
/// Subclasses should fulfill INotifyPropertyChanged contract, i.e. call /// Subclasses should fulfill INotifyPropertyChanged contract, i.e. call
/// OnPropertyChanged whenever a public property has been changed. /// OnPropertyChanged whenever a public property has been changed.
/// </summary> /// </summary>
namespace Greenshot.Drawing.Filters { [Serializable]
[Serializable()]
public abstract class AbstractFilter : AbstractFieldHolder, IFilter { public abstract class AbstractFilter : AbstractFieldHolder, IFilter {
[NonSerialized] [NonSerialized]
@ -41,7 +41,7 @@ namespace Greenshot.Drawing.Filters {
remove{ propertyChanged -= value; } remove{ propertyChanged -= value; }
} }
private bool invert = false; private bool invert;
public bool Invert { public bool Invert {
get { get {
return invert; return invert;
@ -72,10 +72,9 @@ namespace Greenshot.Drawing.Filters {
public abstract void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode); public abstract void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode);
protected void OnPropertyChanged(string propertyName) { protected void OnPropertyChanged(string propertyName)
if (propertyChanged != null) { {
propertyChanged(this, new PropertyChangedEventArgs(propertyName)); propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -18,6 +18,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System; using System;
using System.Drawing; using System.Drawing;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,11 +21,11 @@
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using Greenshot.Drawing.Fields;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing.Filters { namespace Greenshot.Drawing.Filters
{
public interface IFilter : INotifyPropertyChanged, IFieldHolder { public interface IFilter : INotifyPropertyChanged, IFieldHolder {
DrawableContainer Parent {get; set; } DrawableContainer Parent {get; set; }
void Apply(Graphics graphics, Bitmap bmp, Rectangle rect, RenderMode renderMode); void Apply(Graphics graphics, Bitmap bmp, Rectangle rect, RenderMode renderMode);

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -53,7 +53,7 @@ namespace Greenshot.Drawing.Filters {
int halfHeight = rect.Height / 2; int halfHeight = rect.Height / 2;
int newWidth = rect.Width / magnificationFactor; int newWidth = rect.Width / magnificationFactor;
int newHeight = rect.Height / magnificationFactor; int newHeight = rect.Height / magnificationFactor;
Rectangle source = new Rectangle(rect.X + halfWidth - (newWidth / 2), rect.Y + halfHeight - (newHeight / 2), newWidth, newHeight); Rectangle source = new Rectangle(rect.X + halfWidth - newWidth / 2, rect.Y + halfHeight - newHeight / 2, newWidth, newHeight);
graphics.DrawImage(applyBitmap, rect, source, GraphicsUnit.Pixel); graphics.DrawImage(applyBitmap, rect, source, GraphicsUnit.Pixel);
graphics.Restore(state); graphics.Restore(state);
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -37,7 +37,7 @@ namespace Greenshot.Drawing.Filters {
public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) { public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) {
int pixelSize = GetFieldValueAsInt(FieldType.PIXEL_SIZE); int pixelSize = GetFieldValueAsInt(FieldType.PIXEL_SIZE);
Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert); ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert);
if (pixelSize <= 1 || rect.Width == 0 || rect.Height == 0) { if (pixelSize <= 1 || rect.Width == 0 || rect.Height == 0) {
// Nothing to do // Nothing to do
return; return;

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -22,7 +22,6 @@
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using log4net;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
@ -35,21 +34,19 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
[Serializable] [Serializable]
public class FreehandContainer : DrawableContainer { public class FreehandContainer : DrawableContainer {
private static readonly ILog LOG = LogManager.GetLogger(typeof(FreehandContainer)); private static readonly float [] PointOffset = {0.5f, 0.25f, 0.75f};
private static readonly float [] POINT_OFFSET = new float[]{0.5f, 0.25f, 0.75f};
[NonSerialized] [NonSerialized]
private GraphicsPath freehandPath = new GraphicsPath(); private GraphicsPath freehandPath = new GraphicsPath();
private Rectangle myBounds = Rectangle.Empty; private Rectangle myBounds = Rectangle.Empty;
private Point lastMouse = Point.Empty; private Point lastMouse = Point.Empty;
private List<Point> capturePoints = new List<Point>(); private readonly List<Point> capturePoints = new List<Point>();
private bool isRecalculated = false; private bool isRecalculated;
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public FreehandContainer(Surface parent) : base(parent) { public FreehandContainer(Surface parent) : base(parent) {
Init();
Width = parent.Width; Width = parent.Width;
Height = parent.Height; Height = parent.Height;
Top = 0; Top = 0;
@ -61,16 +58,6 @@ namespace Greenshot.Drawing {
AddField(GetType(), FieldType.LINE_COLOR, Color.Red); AddField(GetType(), FieldType.LINE_COLOR, Color.Red);
} }
protected void Init() {
if (_grippers != null) {
for (int i = 0; i < _grippers.Length; i++) {
_grippers[i].Enabled = false;
_grippers[i].Visible = false;
}
}
}
public override void Transform(Matrix matrix) { public override void Transform(Matrix matrix) {
Point[] points = capturePoints.ToArray(); Point[] points = capturePoints.ToArray();
@ -80,11 +67,7 @@ namespace Greenshot.Drawing {
RecalculatePath(); RecalculatePath();
} }
[OnDeserialized] protected override void OnDeserialized(StreamingContext context) {
private void OnDeserialized(StreamingContext context) {
InitGrippers();
DoLayout();
Init();
RecalculatePath(); RecalculatePath();
} }
@ -94,10 +77,9 @@ namespace Greenshot.Drawing {
/// <param name="disposing">When disposing==true all non-managed resources should be freed too!</param> /// <param name="disposing">When disposing==true all non-managed resources should be freed too!</param>
protected override void Dispose(bool disposing) { protected override void Dispose(bool disposing) {
base.Dispose(disposing); base.Dispose(disposing);
if (disposing) { if (disposing)
if (freehandPath != null) { {
freehandPath.Dispose(); freehandPath?.Dispose();
}
} }
freehandPath = null; freehandPath = null;
} }
@ -119,7 +101,7 @@ namespace Greenshot.Drawing {
public override bool HandleMouseMove(int mouseX, int mouseY) { public override bool HandleMouseMove(int mouseX, int mouseY) {
Point previousPoint = capturePoints[capturePoints.Count-1]; Point previousPoint = capturePoints[capturePoints.Count-1];
if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= (2*EditorConfig.FreehandSensitivity)) { if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= 2*EditorConfig.FreehandSensitivity) {
capturePoints.Add(new Point(mouseX, mouseY)); capturePoints.Add(new Point(mouseX, mouseY));
} }
if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= EditorConfig.FreehandSensitivity) { if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= EditorConfig.FreehandSensitivity) {
@ -150,9 +132,7 @@ namespace Greenshot.Drawing {
private void RecalculatePath() { private void RecalculatePath() {
isRecalculated = true; isRecalculated = true;
// Dispose the previous path, if we have one // Dispose the previous path, if we have one
if (freehandPath != null) { freehandPath?.Dispose();
freehandPath.Dispose();
}
freehandPath = new GraphicsPath(); freehandPath = new GraphicsPath();
// Here we can put some cleanup... like losing all the uninteresting points. // Here we can put some cleanup... like losing all the uninteresting points.
@ -160,7 +140,7 @@ namespace Greenshot.Drawing {
int index = 0; int index = 0;
while ((capturePoints.Count - 1) % 3 != 0) { while ((capturePoints.Count - 1) % 3 != 0) {
// duplicate points, first at 50% than 25% than 75% // duplicate points, first at 50% than 25% than 75%
capturePoints.Insert((int)(capturePoints.Count*POINT_OFFSET[index]), capturePoints[(int)(capturePoints.Count*POINT_OFFSET[index++])]); capturePoints.Insert((int)(capturePoints.Count*PointOffset[index]), capturePoints[(int)(capturePoints.Count*PointOffset[index++])]);
} }
freehandPath.AddBeziers(capturePoints.ToArray()); freehandPath.AddBeziers(capturePoints.ToArray());
} else if (capturePoints.Count == 2) { } else if (capturePoints.Count == 2) {
@ -232,9 +212,9 @@ namespace Greenshot.Drawing {
if (!myBounds.IsEmpty) { if (!myBounds.IsEmpty) {
int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS)); int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS));
int safetymargin = 10; int safetymargin = 10;
return new Rectangle((myBounds.Left + Left) - (safetymargin+lineThickness), (myBounds.Top + Top) - (safetymargin+lineThickness), myBounds.Width + (2*(lineThickness+safetymargin)), myBounds.Height + (2*(lineThickness+safetymargin))); return new Rectangle(myBounds.Left + Left - (safetymargin+lineThickness), myBounds.Top + Top - (safetymargin+lineThickness), myBounds.Width + 2*(lineThickness+safetymargin), myBounds.Height + 2*(lineThickness+safetymargin));
} }
return new Rectangle(0, 0, _parent.Width, _parent.Height); return new Rectangle(0, 0, _parent?.Width??0, _parent?.Height?? 0);
} }
} }
@ -245,9 +225,9 @@ namespace Greenshot.Drawing {
/// <returns></returns> /// <returns></returns>
public override bool Equals(object obj) { public override bool Equals(object obj) {
bool ret = false; bool ret = false;
if(obj != null && GetType().Equals(obj.GetType())) { if(obj != null && GetType() == obj.GetType()) {
FreehandContainer other = obj as FreehandContainer; FreehandContainer other = obj as FreehandContainer;
if(freehandPath.Equals(other.freehandPath)) { if(other != null && freehandPath.Equals(other.freehandPath)) {
ret = true; ret = true;
} }
} }
@ -258,17 +238,6 @@ namespace Greenshot.Drawing {
return freehandPath.GetHashCode(); return freehandPath.GetHashCode();
} }
/// <summary>
/// This is overriden to prevent the grippers to be modified.
/// Might not be the best way...
/// </summary>
protected override void DoLayout() {
}
public override void ShowGrippers() {
ResumeLayout();
}
public override bool ClickableAt(int x, int y) { public override bool ClickableAt(int x, int y) {
bool returnValue = base.ClickableAt(x, y); bool returnValue = base.ClickableAt(x, y);
if (returnValue) { if (returnValue) {

View file

@ -1,56 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Drawing;
using System.Windows.Forms;
namespace Greenshot.Drawing {
/// <summary>
/// Grippers are the dragable edges of our containers
/// </summary>
public class Gripper : Label {
/// <summary>
/// Constants for anchor/gripper position:
/// 0 1 2
/// 7 3
/// 6 5 4
/// </summary>
public const int POSITION_TOP_LEFT = 0;
public const int POSITION_TOP_CENTER = 1;
public const int POSITION_TOP_RIGHT = 2;
public const int POSITION_MIDDLE_RIGHT = 3;
public const int POSITION_BOTTOM_RIGHT = 4;
public const int POSITION_BOTTOM_CENTER = 5;
public const int POSITION_BOTTOM_LEFT = 6;
public const int POSITION_MIDDLE_LEFT = 7;
public int Position {
get;
set;
}
public Gripper() {
Width = 5;
Height = 5;
BackColor = Color.Black;
}
}
}

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -19,11 +19,11 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System; using System;
using System.Drawing;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Drawing.Filters; using Greenshot.Drawing.Filters;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -43,8 +43,8 @@ namespace Greenshot.Drawing {
AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT); AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT);
} }
[OnDeserialized] protected override void OnDeserialized(StreamingContext context)
private void OnDeserialized(StreamingContext context) { {
Init(); Init();
} }
@ -57,7 +57,7 @@ namespace Greenshot.Drawing {
if (!sender.Equals(this)) { if (!sender.Equals(this)) {
return; return;
} }
if (e.Field.FieldType == FieldType.PREPARED_FILTER_HIGHLIGHT) { if (Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_HIGHLIGHT)) {
ConfigurePreparedFilters(); ConfigurePreparedFilters();
} }
} }
@ -72,12 +72,16 @@ namespace Greenshot.Drawing {
Add(new HighlightFilter(this)); Add(new HighlightFilter(this));
break; break;
case PreparedFilter.AREA_HIGHLIGHT: case PreparedFilter.AREA_HIGHLIGHT:
AbstractFilter bf = new BrightnessFilter(this); var brightnessFilter = new BrightnessFilter(this)
bf.Invert = true; {
Add(bf); Invert = true
bf = new BlurFilter(this); };
bf.Invert = true; Add(brightnessFilter);
Add(bf); var blurFilter = new BlurFilter(this)
{
Invert = true
};
Add(blurFilter);
break; break;
case PreparedFilter.GRAYSCALE: case PreparedFilter.GRAYSCALE:
AbstractFilter f = new GrayscaleFilter(this); AbstractFilter f = new GrayscaleFilter(this);

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -24,6 +24,7 @@ using System.IO;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using log4net; using log4net;
using System.Runtime.Serialization;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -31,11 +32,23 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
[Serializable] [Serializable]
public class IconContainer : DrawableContainer, IIconContainer { public class IconContainer : DrawableContainer, IIconContainer {
private static ILog LOG = LogManager.GetLogger(typeof(IconContainer)); private static readonly ILog Log = LogManager.GetLogger(typeof(IconContainer));
protected Icon icon; protected Icon icon;
public IconContainer(Surface parent) : base(parent) { public IconContainer(Surface parent) : base(parent) {
Init();
}
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
} }
public IconContainer(Surface parent, string filename) : base(parent) { public IconContainer(Surface parent, string filename) : base(parent) {
@ -44,9 +57,7 @@ namespace Greenshot.Drawing {
public Icon Icon { public Icon Icon {
set { set {
if (icon != null) { icon?.Dispose();
icon.Dispose();
}
icon = (Icon)value.Clone(); icon = (Icon)value.Clone();
Width = value.Width; Width = value.Width;
Height = value.Height; Height = value.Height;
@ -59,10 +70,9 @@ namespace Greenshot.Drawing {
* When disposing==true all non-managed resources should be freed too! * When disposing==true all non-managed resources should be freed too!
*/ */
protected override void Dispose(bool disposing) { protected override void Dispose(bool disposing) {
if (disposing) { if (disposing)
if (icon != null) { {
icon.Dispose(); icon?.Dispose();
}
} }
icon = null; icon = null;
base.Dispose(disposing); base.Dispose(disposing);
@ -72,7 +82,7 @@ namespace Greenshot.Drawing {
if (File.Exists(filename)) { if (File.Exists(filename)) {
using (Icon fileIcon = new Icon(filename)) { using (Icon fileIcon = new Icon(filename)) {
Icon = fileIcon; Icon = fileIcon;
LOG.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width); Log.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width);
} }
} }
} }
@ -87,16 +97,8 @@ namespace Greenshot.Drawing {
} }
} }
public override bool HasDefaultSize { public override bool HasDefaultSize => true;
get {
return true;
}
}
public override Size DefaultSize { public override Size DefaultSize => icon.Size;
get {
return icon.Size;
}
}
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -25,8 +25,10 @@ using Greenshot.Drawing.Fields;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using Greenshot.Core;
using log4net; using log4net;
using System.Runtime.Serialization;
using GreenshotPlugin.Effects;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -34,7 +36,7 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
[Serializable] [Serializable]
public class ImageContainer : DrawableContainer, IImageContainer { public class ImageContainer : DrawableContainer, IImageContainer {
private static ILog LOG = LogManager.GetLogger(typeof(ImageContainer)); private static readonly ILog Log = LogManager.GetLogger(typeof(ImageContainer));
private Image image; private Image image;
@ -58,6 +60,18 @@ namespace Greenshot.Drawing {
public ImageContainer(Surface parent) : base(parent) { public ImageContainer(Surface parent) : base(parent) {
FieldChanged += BitmapContainer_OnFieldChanged; FieldChanged += BitmapContainer_OnFieldChanged;
Init();
}
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
} }
protected override void InitializeFields() { protected override void InitializeFields() {
@ -66,7 +80,7 @@ namespace Greenshot.Drawing {
protected void BitmapContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { protected void BitmapContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) {
if (sender.Equals(this)) { if (sender.Equals(this)) {
if (e.Field.FieldType == FieldType.SHADOW) { if (FieldType.SHADOW.Equals(e.Field.FieldType)) {
ChangeShadowField(); ChangeShadowField();
} }
} }
@ -126,15 +140,11 @@ namespace Greenshot.Drawing {
} }
private void DisposeImage() { private void DisposeImage() {
if (image != null) { image?.Dispose();
image.Dispose();
}
image = null; image = null;
} }
private void DisposeShadow() { private void DisposeShadow() {
if (_shadowBitmap != null) { _shadowBitmap?.Dispose();
_shadowBitmap.Dispose();
}
_shadowBitmap = null; _shadowBitmap = null;
} }
@ -148,10 +158,11 @@ namespace Greenshot.Drawing {
int rotateAngle = CalculateAngle(matrix); int rotateAngle = CalculateAngle(matrix);
// we currently assume only one transformation has been made. // we currently assume only one transformation has been made.
if (rotateAngle != 0) { if (rotateAngle != 0) {
LOG.DebugFormat("Rotating element with {0} degrees.", rotateAngle); Log.DebugFormat("Rotating element with {0} degrees.", rotateAngle);
DisposeShadow(); DisposeShadow();
using (var tmpMatrix = new Matrix()) { using (var tmpMatrix = new Matrix()) {
using (Image tmpImage = image) { using (image)
{
image = ImageHelper.ApplyEffect(image, new RotateEffect(rotateAngle), tmpMatrix); image = ImageHelper.ApplyEffect(image, new RotateEffect(rotateAngle), tmpMatrix);
} }
} }
@ -164,14 +175,16 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
public void Load(string filename) { public void Load(string filename) {
if (File.Exists(filename)) { if (!File.Exists(filename))
{
return;
}
// Always make sure ImageHelper.LoadBitmap results are disposed some time, // Always make sure ImageHelper.LoadBitmap results are disposed some time,
// as we close the bitmap internally, we need to do it afterwards // as we close the bitmap internally, we need to do it afterwards
using (Image tmpImage = ImageHelper.LoadImage(filename)) { using (var tmpImage = ImageHelper.LoadImage(filename)) {
Image = tmpImage; Image = tmpImage;
} }
LOG.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width); Log.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width);
}
} }
/// <summary> /// <summary>
@ -208,16 +221,8 @@ namespace Greenshot.Drawing {
} }
} }
public override bool HasDefaultSize { public override bool HasDefaultSize => true;
get {
return true;
}
}
public override Size DefaultSize { public override Size DefaultSize => image.Size;
get {
return image.Size;
}
}
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -26,6 +26,7 @@ using System.Runtime.Serialization;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using Greenshot.Drawing.Adorners;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -45,19 +46,14 @@ namespace Greenshot.Drawing {
AddField(GetType(), FieldType.SHADOW, true); AddField(GetType(), FieldType.SHADOW, true);
} }
[OnDeserialized()] protected override void OnDeserialized(StreamingContext context)
private void OnDeserialized(StreamingContext context) { {
InitGrippers();
DoLayout();
Init(); Init();
} }
protected void Init() { protected void Init() {
if (_grippers != null) { Adorners.Add(new MoveAdorner(this, Positions.TopLeft));
foreach (int index in new[] { 1, 2, 3, 5, 6, 7 }) { Adorners.Add(new MoveAdorner(this, Positions.BottomRight));
_grippers[index].Enabled = false;
}
}
} }
public override void Draw(Graphics graphics, RenderMode rm) { public override void Draw(Graphics graphics, RenderMode rm) {
@ -86,7 +82,7 @@ namespace Greenshot.Drawing {
Top + currentStep + Height); Top + currentStep + Height);
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }
} }
@ -114,7 +110,5 @@ namespace Greenshot.Drawing {
protected override ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() { protected override ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() {
return ScaleHelper.LineAngleRoundBehavior.Instance; return ScaleHelper.LineAngleRoundBehavior.Instance;
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -22,6 +22,7 @@ using System;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Drawing.Filters; using Greenshot.Drawing.Filters;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -38,19 +39,20 @@ namespace Greenshot.Drawing {
AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE); AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE);
} }
[OnDeserialized] protected override void OnDeserialized(StreamingContext context)
private void OnDeserialized(StreamingContext context) { {
Init(); Init();
} }
private void Init() { private void Init() {
FieldChanged += ObfuscateContainer_OnFieldChanged; FieldChanged += ObfuscateContainer_OnFieldChanged;
ConfigurePreparedFilters(); ConfigurePreparedFilters();
CreateDefaultAdorners();
} }
protected void ObfuscateContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { protected void ObfuscateContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) {
if(sender.Equals(this)) { if(sender.Equals(this)) {
if(e.Field.FieldType == FieldType.PREPARED_FILTER_OBFUSCATE) { if(Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_OBFUSCATE)) {
ConfigurePreparedFilters(); ConfigurePreparedFilters();
} }
} }

View file

@ -1,6 +1,6 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2014 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
@ -18,12 +18,21 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System;
using System.Collections.Generic;
using System.Text;
using GreenshotPlugin.Controls;
namespace PluginExample { namespace Greenshot.Drawing
public class ExampleForm : GreenshotForm{ {
/// <summary>
/// Position
/// </summary>
public enum Positions : int
{
TopLeft = 0,
TopCenter = 1,
TopRight = 2,
MiddleRight = 3,
BottomRight = 4,
BottomCenter = 5,
BottomLeft = 6,
MiddleLeft = 7
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -25,6 +25,7 @@ using System.Drawing.Drawing2D;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System.Runtime.Serialization;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -34,6 +35,22 @@ namespace Greenshot.Drawing {
public class RectangleContainer : DrawableContainer { public class RectangleContainer : DrawableContainer {
public RectangleContainer(Surface parent) : base(parent) { public RectangleContainer(Surface parent) : base(parent) {
Init();
}
/// <summary>
/// Do some logic to make sure all field are initiated correctly
/// </summary>
/// <param name="streamingContext">StreamingContext</param>
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
} }
protected override void InitializeFields() { protected override void InitializeFields() {
@ -69,7 +86,7 @@ namespace Greenshot.Drawing {
graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.None; graphics.PixelOffsetMode = PixelOffsetMode.None;
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { if (shadow && (lineVisible || Colors.IsVisible(fillColor))) {
//draw shadow first //draw shadow first
int basealpha = 100; int basealpha = 100;
@ -86,7 +103,7 @@ namespace Greenshot.Drawing {
rect.Height); rect.Height);
graphics.DrawRectangle(shadowPen, shadowRect); graphics.DrawRectangle(shadowPen, shadowRect);
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -19,6 +19,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
@ -27,6 +28,7 @@ namespace Greenshot.Drawing {
/// TODO: currently this is only used in the capture form, we might move this code directly to there! /// TODO: currently this is only used in the capture form, we might move this code directly to there!
/// </summary> /// </summary>
public abstract class RoundedRectangle { public abstract class RoundedRectangle {
[Flags]
public enum RectangleCorners { public enum RectangleCorners {
None = 0, TopLeft = 1, TopRight = 2, None = 0, TopLeft = 1, TopRight = 2,
BottomLeft = 4, BottomRight = 8, BottomLeft = 4, BottomRight = 8,
@ -35,13 +37,13 @@ namespace Greenshot.Drawing {
public static GraphicsPath Create2(int x, int y, int width, int height, int radius) { public static GraphicsPath Create2(int x, int y, int width, int height, int radius) {
GraphicsPath gp = new GraphicsPath(); GraphicsPath gp = new GraphicsPath();
gp.AddLine(x + radius, y, x + width - (radius * 2), y); // 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.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.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.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.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.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, y + height - radius * 2, x, y + radius); // Line
gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner
gp.CloseFigure(); gp.CloseFigure();

View file

@ -3,7 +3,7 @@
* Copyright (C) 2007-2012 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2012 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,17 +21,15 @@
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System; using System;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Text; using System.Drawing.Text;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Windows.Forms;
using log4net;
namespace Greenshot.Drawing { namespace Greenshot.Drawing
{
/// <summary> /// <summary>
/// Description of SpeechbubbleContainer. /// Description of SpeechbubbleContainer.
/// </summary> /// </summary>
@ -50,8 +48,8 @@ namespace Greenshot.Drawing {
/// <param name="context"></param> /// <param name="context"></param>
[OnSerializing] [OnSerializing]
private void SetValuesOnSerializing(StreamingContext context) { private void SetValuesOnSerializing(StreamingContext context) {
if (TargetGripper != null) { if (TargetAdorner != null) {
_storedTargetGripperLocation = TargetGripper.Location; _storedTargetGripperLocation = TargetAdorner.Location;
} }
} }
@ -59,9 +57,9 @@ namespace Greenshot.Drawing {
/// Restore the target gripper /// Restore the target gripper
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
[OnDeserialized] protected override void OnDeserialized(StreamingContext context)
private void SetValuesOnDeserialized(StreamingContext context) { {
InitTargetGripper(Color.Green, _storedTargetGripperLocation); InitAdorner(Color.Green, _storedTargetGripperLocation);
} }
#endregion #endregion
@ -90,9 +88,9 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <returns>true if the surface doesn't need to handle the event</returns> /// <returns>true if the surface doesn't need to handle the event</returns>
public override bool HandleMouseDown(int mouseX, int mouseY) { public override bool HandleMouseDown(int mouseX, int mouseY) {
if (TargetGripper == null) { if (TargetAdorner == null) {
_initialGripperPoint = new Point(mouseX, mouseY); _initialGripperPoint = new Point(mouseX, mouseY);
InitTargetGripper(Color.Green, new Point(mouseX, mouseY)); InitAdorner(Color.Green, new Point(mouseX, mouseY));
} }
return base.HandleMouseDown(mouseX, mouseY); return base.HandleMouseDown(mouseX, mouseY);
} }
@ -116,9 +114,9 @@ namespace Greenshot.Drawing {
Point newGripperLocation = _initialGripperPoint; Point newGripperLocation = _initialGripperPoint;
newGripperLocation.Offset(xOffset, yOffset); newGripperLocation.Offset(xOffset, yOffset);
if (TargetGripper.Location != newGripperLocation) { if (TargetAdorner.Location != newGripperLocation) {
Invalidate(); Invalidate();
TargetGripperMove(newGripperLocation.X, newGripperLocation.Y); TargetAdorner.Location = newGripperLocation;
Invalidate(); Invalidate();
} }
return returnValue; return returnValue;
@ -180,7 +178,7 @@ namespace Greenshot.Drawing {
private GraphicsPath CreateTail() { private GraphicsPath CreateTail() {
Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
int tailLength = GeometryHelper.Distance2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetGripper.Left, TargetGripper.Top); int tailLength = GeometryHelper.Distance2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetAdorner.Location.X, TargetAdorner.Location.Y);
int tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20; int tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20;
// This should fix a problem with the tail being to wide // This should fix a problem with the tail being to wide
@ -192,10 +190,10 @@ namespace Greenshot.Drawing {
tail.AddLine(tailWidth, 0, 0, -tailLength); tail.AddLine(tailWidth, 0, 0, -tailLength);
tail.CloseFigure(); tail.CloseFigure();
int tailAngle = 90 + (int)GeometryHelper.Angle2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetGripper.Left, TargetGripper.Top); 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 Matrix()) {
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); tailMatrix.Rotate(tailAngle);
tail.Transform(tailMatrix); tail.Transform(tailMatrix);
} }
@ -209,7 +207,7 @@ namespace Greenshot.Drawing {
/// <param name="graphics"></param> /// <param name="graphics"></param>
/// <param name="renderMode"></param> /// <param name="renderMode"></param>
public override void Draw(Graphics graphics, RenderMode renderMode) { public override void Draw(Graphics graphics, RenderMode renderMode) {
if (TargetGripper == null) { if (TargetAdorner == null) {
return; return;
} }
graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality;
@ -223,7 +221,7 @@ namespace Greenshot.Drawing {
bool shadow = GetFieldValueAsBool(FieldType.SHADOW); bool shadow = GetFieldValueAsBool(FieldType.SHADOW);
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS);
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
if (Selected && renderMode == RenderMode.EDIT) { if (Selected && renderMode == RenderMode.EDIT) {
@ -253,7 +251,7 @@ namespace Greenshot.Drawing {
graphics.DrawPath(shadowPen, bubbleClone); graphics.DrawPath(shadowPen, bubbleClone);
} }
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }
} }

View file

@ -3,7 +3,7 @@
* Copyright (C) 2007-2012 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2012 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -27,6 +27,7 @@ using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Text; using System.Drawing.Text;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -34,7 +35,7 @@ namespace Greenshot.Drawing {
/// To make sure that deleting recalculates, we check the location before every draw. /// To make sure that deleting recalculates, we check the location before every draw.
/// </summary> /// </summary>
[Serializable] [Serializable]
public class StepLabelContainer : DrawableContainer { public sealed class StepLabelContainer : DrawableContainer {
[NonSerialized] [NonSerialized]
private StringFormat _stringFormat = new StringFormat(); private StringFormat _stringFormat = new StringFormat();
@ -45,11 +46,19 @@ namespace Greenshot.Drawing {
public StepLabelContainer(Surface parent) : base(parent) { public StepLabelContainer(Surface parent) : base(parent) {
parent.AddStepLabel(this); parent.AddStepLabel(this);
InitContent(); InitContent();
Init();
}
private void Init()
{
CreateDefaultAdorners();
} }
#region Number serializing #region Number serializing
// Used to store the number of this label, so when deserializing it can be placed back to the StepLabels list in the right location // 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; 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 { public int Number {
get { get {
return _number; return _number;
@ -67,6 +76,7 @@ namespace Greenshot.Drawing {
private void SetValuesOnSerializing(StreamingContext context) { private void SetValuesOnSerializing(StreamingContext context) {
if (Parent != null) { if (Parent != null) {
Number = ((Surface)Parent).CountStepLabels(this); Number = ((Surface)Parent).CountStepLabels(this);
_counterStart = ((Surface) Parent).CounterStart;
} }
} }
#endregion #endregion
@ -75,11 +85,15 @@ namespace Greenshot.Drawing {
/// Restore values that don't serialize /// Restore values that don't serialize
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
[OnDeserialized] protected override void OnDeserialized(StreamingContext context)
private void SetValuesOnDeserialized(StreamingContext context) { {
_stringFormat = new StringFormat(); Init();
_stringFormat.Alignment = StringAlignment.Center; _stringFormat = new StringFormat
_stringFormat.LineAlignment = StringAlignment.Center; {
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
} }
/// <summary> /// <summary>
@ -87,20 +101,22 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="newParent"></param> /// <param name="newParent"></param>
protected override void SwitchParent(Surface newParent) { protected override void SwitchParent(Surface newParent) {
if (Parent != null) { if (newParent == Parent)
((Surface)Parent).RemoveStepLabel(this); {
return;
} }
((Surface) Parent)?.RemoveStepLabel(this);
base.SwitchParent(newParent); base.SwitchParent(newParent);
if (newParent != null) { if (newParent == null)
((Surface)Parent).AddStepLabel(this); {
return;
} }
// Make sure the counter start is restored (this unfortunately happens multiple times... -> hack)
newParent.CounterStart = _counterStart;
newParent.AddStepLabel(this);
} }
public override Size DefaultSize { public override Size DefaultSize => new Size(30, 30);
get {
return new Size(30, 30);
}
}
public override bool InitContent() { public override bool InitContent() {
_defaultEditMode = EditStatus.IDLE; _defaultEditMode = EditStatus.IDLE;
@ -118,7 +134,7 @@ namespace Greenshot.Drawing {
/// This makes it possible for the label to be placed exactly in the middle of the pointer. /// This makes it possible for the label to be placed exactly in the middle of the pointer.
/// </summary> /// </summary>
public override bool HandleMouseDown(int mouseX, int mouseY) { 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);
} }
/// <summary> /// <summary>
@ -127,6 +143,7 @@ namespace Greenshot.Drawing {
protected override void InitializeFields() { protected override void InitializeFields() {
AddField(GetType(), FieldType.FILL_COLOR, Color.DarkRed); AddField(GetType(), FieldType.FILL_COLOR, Color.DarkRed);
AddField(GetType(), FieldType.LINE_COLOR, Color.White); AddField(GetType(), FieldType.LINE_COLOR, Color.White);
AddField(GetType(), FieldType.FLAGS, FieldFlag.COUNTER);
} }
/// <summary> /// <summary>
@ -137,17 +154,19 @@ namespace Greenshot.Drawing {
if (!disposing) { if (!disposing) {
return; return;
} }
((Surface)Parent).RemoveStepLabel(this); ((Surface) Parent)?.RemoveStepLabel(this);
if (_stringFormat != null) { if (_stringFormat == null)
{
return;
}
_stringFormat.Dispose(); _stringFormat.Dispose();
_stringFormat = null; _stringFormat = null;
} }
}
public override bool HandleMouseMove(int x, int y) { public override bool HandleMouseMove(int x, int y) {
Invalidate(); Invalidate();
Left = x - (Width / 2); Left = x - Width / 2;
Top = y - (Height / 2); Top = y - Height / 2;
Invalidate(); Invalidate();
return true; return true;
} }
@ -167,7 +186,7 @@ namespace Greenshot.Drawing {
int widthAfter = rect.Width; int widthAfter = rect.Width;
int heightAfter = rect.Height; int heightAfter = rect.Height;
float factor = (((float)widthAfter / widthBefore) + ((float)heightAfter / heightBefore)) / 2; float factor = ((float)widthAfter / widthBefore + (float)heightAfter / heightBefore) / 2;
fontSize *= factor; fontSize *= factor;
} }
@ -193,8 +212,8 @@ namespace Greenshot.Drawing {
EllipseContainer.DrawEllipse(rect, graphics, rm, 0, Color.Transparent, fillColor, false); EllipseContainer.DrawEllipse(rect, graphics, rm, 0, Color.Transparent, fillColor, false);
} }
using (FontFamily fam = new FontFamily(FontFamily.GenericSansSerif.Name)) { using (FontFamily fam = new FontFamily(FontFamily.GenericSansSerif.Name)) {
using (Font _font = new Font(fam, fontSize, FontStyle.Bold, GraphicsUnit.Pixel)) { using (Font font = new Font(fam, fontSize, FontStyle.Bold, GraphicsUnit.Pixel)) {
TextContainer.DrawText(graphics, rect, 0, lineColor, false, _stringFormat, text, _font); TextContainer.DrawText(graphics, rect, 0, lineColor, false, _stringFormat, text, font);
} }
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -22,32 +22,33 @@
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Memento; using Greenshot.Memento;
using Greenshot.Plugin;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Text; using System.Drawing.Text;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Windows.Forms; using System.Windows.Forms;
namespace Greenshot.Drawing { namespace Greenshot.Drawing
{
/// <summary> /// <summary>
/// Represents a textbox (extends RectangleContainer for border/background support /// Represents a textbox (extends RectangleContainer for border/background support
/// </summary> /// </summary>
[Serializable] [Serializable]
public class TextContainer : RectangleContainer, ITextContainer { public class TextContainer : RectangleContainer, ITextContainer
{
// If makeUndoable is true the next text-change will make the change undoable. // If makeUndoable is true the next text-change will make the change undoable.
// This is set to true AFTER the first change is made, as there is already a "add element" on the undo stack // This is set to true AFTER the first change is made, as there is already a "add element" on the undo stack
// Although the name is wrong, we can't change it due to file serialization
// ReSharper disable once InconsistentNaming
private bool makeUndoable; private bool makeUndoable;
[NonSerialized] [NonSerialized]
private Font _font; private Font _font;
public Font Font { public Font Font => _font;
get {
return _font;
}
}
[NonSerialized] [NonSerialized]
private TextBox _textBox; private TextBox _textBox;
@ -56,24 +57,29 @@ namespace Greenshot.Drawing {
/// The StringFormat object is not serializable!! /// The StringFormat object is not serializable!!
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
StringFormat _stringFormat = new StringFormat(); private StringFormat _stringFormat = new StringFormat();
public StringFormat StringFormat {
get { public StringFormat StringFormat => _stringFormat;
return _stringFormat;
} // Although the name is wrong, we can't change it due to file serialization
} // ReSharper disable once InconsistentNaming
private string text; private string text;
// there is a binding on the following property! // there is a binding on the following property!
public string Text { public string Text
{
get { return text; } get { return text; }
set { set
{
ChangeText(value, true); ChangeText(value, true);
} }
} }
internal void ChangeText(string newText, bool allowUndoable) { internal void ChangeText(string newText, bool allowUndoable)
if ((text == null && newText != null) || !text.Equals(newText)) { {
if (makeUndoable && allowUndoable) { if ((text == null && newText != null) || !string.Equals(text, newText))
{
if (makeUndoable && allowUndoable)
{
makeUndoable = false; makeUndoable = false;
_parent.MakeUndoable(new TextChangeMemento(this), false); _parent.MakeUndoable(new TextChangeMemento(this), false);
} }
@ -82,11 +88,13 @@ namespace Greenshot.Drawing {
} }
} }
public TextContainer(Surface parent) : base(parent) { public TextContainer(Surface parent) : base(parent)
{
Init(); Init();
} }
protected override void InitializeFields() { protected override void InitializeFields()
{
AddField(GetType(), FieldType.LINE_THICKNESS, 2); AddField(GetType(), FieldType.LINE_THICKNESS, 2);
AddField(GetType(), FieldType.LINE_COLOR, Color.Red); AddField(GetType(), FieldType.LINE_COLOR, Color.Red);
AddField(GetType(), FieldType.SHADOW, true); AddField(GetType(), FieldType.SHADOW, true);
@ -99,22 +107,32 @@ namespace Greenshot.Drawing {
AddField(GetType(), FieldType.TEXT_VERTICAL_ALIGNMENT, StringAlignment.Center); AddField(GetType(), FieldType.TEXT_VERTICAL_ALIGNMENT, StringAlignment.Center);
} }
[OnDeserialized] /// <summary>
private void OnDeserialized(StreamingContext context) { /// Do some logic to make sure all field are initiated correctly
/// </summary>
/// <param name="streamingContext">StreamingContext</param>
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init(); Init();
} }
protected override void Dispose(bool disposing) { protected override void Dispose(bool disposing)
if (disposing) { {
if (_font != null) { if (disposing)
{
if (_font != null)
{
_font.Dispose(); _font.Dispose();
_font = null; _font = null;
} }
if (_stringFormat != null) { if (_stringFormat != null)
{
_stringFormat.Dispose(); _stringFormat.Dispose();
_stringFormat = null; _stringFormat = null;
} }
if (_textBox != null) { if (_textBox != null)
{
_textBox.Dispose(); _textBox.Dispose();
_textBox = null; _textBox = null;
} }
@ -122,9 +140,12 @@ namespace Greenshot.Drawing {
base.Dispose(disposing); base.Dispose(disposing);
} }
private void Init() { private void Init()
_stringFormat = new StringFormat(); {
_stringFormat.Trimming = StringTrimming.EllipsisWord; _stringFormat = new StringFormat
{
Trimming = StringTrimming.EllipsisWord
};
CreateTextBox(); CreateTextBox();
@ -136,82 +157,120 @@ namespace Greenshot.Drawing {
} }
public override void Invalidate() { public override void Invalidate()
{
base.Invalidate(); base.Invalidate();
if (_textBox != null && _textBox.Visible) { if (_textBox != null && _textBox.Visible)
{
_textBox.Invalidate(); _textBox.Invalidate();
} }
} }
public void FitToText() { public void FitToText()
{
Size textSize = TextRenderer.MeasureText(text, _font); Size textSize = TextRenderer.MeasureText(text, _font);
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS);
Width = textSize.Width + lineThickness; Width = textSize.Width + lineThickness;
Height = textSize.Height + lineThickness; Height = textSize.Height + lineThickness;
} }
void TextContainer_PropertyChanged(object sender, PropertyChangedEventArgs e) { private void TextContainer_PropertyChanged(object sender, PropertyChangedEventArgs e)
if (_textBox.Visible) { {
if (_textBox == null)
{
return;
}
if (_textBox.Visible)
{
_textBox.Invalidate(); _textBox.Invalidate();
} }
UpdateTextBoxPosition(); UpdateTextBoxPosition();
UpdateTextBoxFormat(); UpdateTextBoxFormat();
if (e.PropertyName.Equals("Selected")) { if (e.PropertyName.Equals("Selected"))
if (!Selected && _textBox.Visible) { {
if (!Selected && _textBox.Visible)
{
HideTextBox(); HideTextBox();
} else if (Selected && Status == EditStatus.DRAWING) { }
else if (Selected && Status == EditStatus.DRAWING)
{
ShowTextBox(); ShowTextBox();
} else if (Selected && Status == EditStatus.IDLE && _textBox.Visible) { }
else if (_parent != null && Selected && Status == EditStatus.IDLE && _textBox.Visible)
{
// Fix (workaround) for BUG-1698 // Fix (workaround) for BUG-1698
_parent.KeysLocked = true; _parent.KeysLocked = true;
} }
} }
if (_textBox.Visible) { if (_textBox.Visible)
{
_textBox.Invalidate(); _textBox.Invalidate();
} }
} }
void TextContainer_FieldChanged(object sender, FieldChangedEventArgs e) { private void TextContainer_FieldChanged(object sender, FieldChangedEventArgs e)
if (_textBox.Visible) { {
if (_textBox == null)
{
return;
}
if (_textBox.Visible)
{
_textBox.Invalidate(); _textBox.Invalidate();
} }
// Only dispose the font, and re-create it, when a font field has changed. // Only dispose the font, and re-create it, when a font field has changed.
if (e.Field.FieldType.Name.StartsWith("FONT")) { if (e.Field.FieldType.Name.StartsWith("FONT"))
{
if (_font != null)
{
_font.Dispose(); _font.Dispose();
_font = null; _font = null;
}
UpdateFormat(); UpdateFormat();
} else { }
else
{
UpdateAlignment(); UpdateAlignment();
} }
UpdateTextBoxFormat(); UpdateTextBoxFormat();
if (_textBox.Visible) { if (_textBox.Visible)
{
_textBox.Invalidate(); _textBox.Invalidate();
} }
} }
public override void OnDoubleClick() { public override void OnDoubleClick()
{
ShowTextBox(); ShowTextBox();
} }
private void CreateTextBox() { private void CreateTextBox()
_textBox = new TextBox(); {
_textBox = new TextBox
{
ImeMode = ImeMode.On,
Multiline = true,
AcceptsTab = true,
AcceptsReturn = true,
BorderStyle = BorderStyle.None,
Visible = false
};
_textBox.ImeMode = ImeMode.On;
_textBox.Multiline = true;
_textBox.AcceptsTab = true;
_textBox.AcceptsReturn = true;
_textBox.DataBindings.Add("Text", this, "Text", false, DataSourceUpdateMode.OnPropertyChanged); _textBox.DataBindings.Add("Text", this, "Text", false, DataSourceUpdateMode.OnPropertyChanged);
_textBox.LostFocus += textBox_LostFocus; _textBox.LostFocus += textBox_LostFocus;
_textBox.KeyDown += textBox_KeyDown; _textBox.KeyDown += textBox_KeyDown;
_textBox.BorderStyle = BorderStyle.None;
_textBox.Visible = false;
} }
private void ShowTextBox() { private void ShowTextBox()
{
if (_parent != null)
{
_parent.KeysLocked = true; _parent.KeysLocked = true;
_parent.Controls.Add(_textBox); _parent.Controls.Add(_textBox);
}
EnsureTextBoxContrast(); EnsureTextBoxContrast();
_textBox.Show(); _textBox.Show();
_textBox.Focus(); _textBox.Focus();
@ -220,16 +279,21 @@ namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// Makes textbox background dark if text color is very bright /// Makes textbox background dark if text color is very bright
/// </summary> /// </summary>
private void EnsureTextBoxContrast() { private void EnsureTextBoxContrast()
{
Color lc = GetFieldValueAsColor(FieldType.LINE_COLOR); Color lc = GetFieldValueAsColor(FieldType.LINE_COLOR);
if (lc.R > 203 && lc.G > 203 && lc.B > 203) { if (lc.R > 203 && lc.G > 203 && lc.B > 203)
{
_textBox.BackColor = Color.FromArgb(51, 51, 51); _textBox.BackColor = Color.FromArgb(51, 51, 51);
} else { }
else
{
_textBox.BackColor = Color.White; _textBox.BackColor = Color.White;
} }
} }
private void HideTextBox() { private void HideTextBox()
{
_parent.Focus(); _parent.Focus();
_textBox.Hide(); _textBox.Hide();
_parent.KeysLocked = false; _parent.KeysLocked = false;
@ -240,7 +304,8 @@ namespace Greenshot.Drawing {
/// Make sure the size of the font is scaled /// Make sure the size of the font is scaled
/// </summary> /// </summary>
/// <param name="matrix"></param> /// <param name="matrix"></param>
public override void Transform(Matrix matrix) { public override void Transform(Matrix matrix)
{
Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
int pixelsBefore = rect.Width * rect.Height; int pixelsBefore = rect.Width * rect.Height;
@ -257,58 +322,98 @@ namespace Greenshot.Drawing {
UpdateFormat(); UpdateFormat();
} }
private Font CreateFont(string fontFamilyName, bool fontBold, bool fontItalic, float fontSize)
{
FontStyle fontStyle = FontStyle.Regular;
bool hasStyle = false;
using (var fontFamily = new FontFamily(fontFamilyName))
{
bool boldAvailable = fontFamily.IsStyleAvailable(FontStyle.Bold);
if (fontBold && boldAvailable)
{
fontStyle |= FontStyle.Bold;
hasStyle = true;
}
bool italicAvailable = fontFamily.IsStyleAvailable(FontStyle.Italic);
if (fontItalic && italicAvailable)
{
fontStyle |= FontStyle.Italic;
hasStyle = true;
}
if (!hasStyle)
{
bool regularAvailable = fontFamily.IsStyleAvailable(FontStyle.Regular);
if (regularAvailable)
{
fontStyle = FontStyle.Regular;
}
else
{
if (boldAvailable)
{
fontStyle = FontStyle.Bold;
}
else if (italicAvailable)
{
fontStyle = FontStyle.Italic;
}
}
}
return new Font(fontFamily, fontSize, fontStyle, GraphicsUnit.Pixel);
}
}
/// <summary> /// <summary>
/// Generate the Font-Formal so we can draw correctly /// Generate the Font-Formal so we can draw correctly
/// </summary> /// </summary>
protected void UpdateFormat() { protected void UpdateFormat()
{
if (_textBox == null)
{
return;
}
string fontFamily = GetFieldValueAsString(FieldType.FONT_FAMILY); string fontFamily = GetFieldValueAsString(FieldType.FONT_FAMILY);
bool fontBold = GetFieldValueAsBool(FieldType.FONT_BOLD); bool fontBold = GetFieldValueAsBool(FieldType.FONT_BOLD);
bool fontItalic = GetFieldValueAsBool(FieldType.FONT_ITALIC); bool fontItalic = GetFieldValueAsBool(FieldType.FONT_ITALIC);
float fontSize = GetFieldValueAsFloat(FieldType.FONT_SIZE); float fontSize = GetFieldValueAsFloat(FieldType.FONT_SIZE);
try { try
FontStyle fs = FontStyle.Regular; {
var newFont = CreateFont(fontFamily, fontBold, fontItalic, fontSize);
bool hasStyle = false; _font?.Dispose();
using(FontFamily fam = new FontFamily(fontFamily)) { _font = newFont;
bool boldAvailable = fam.IsStyleAvailable(FontStyle.Bold);
if (fontBold && boldAvailable) {
fs |= FontStyle.Bold;
hasStyle = true;
}
bool italicAvailable = fam.IsStyleAvailable(FontStyle.Italic);
if (fontItalic && italicAvailable) {
fs |= FontStyle.Italic;
hasStyle = true;
}
if (!hasStyle) {
bool regularAvailable = fam.IsStyleAvailable(FontStyle.Regular);
if (regularAvailable) {
fs = FontStyle.Regular;
} else {
if (boldAvailable) {
fs = FontStyle.Bold;
} else if(italicAvailable) {
fs = FontStyle.Italic;
}
}
}
_font = new Font(fam, fontSize, fs, GraphicsUnit.Pixel);
_textBox.Font = _font; _textBox.Font = _font;
} }
} catch (Exception ex) { catch (Exception ex)
ex.Data.Add("fontFamily", fontFamily); {
// Problem, try again with the default
try
{
fontFamily = FontFamily.GenericSansSerif.Name;
SetFieldValue(FieldType.FONT_FAMILY, fontFamily);
var newFont = CreateFont(fontFamily, fontBold, fontItalic, fontSize);
_font?.Dispose();
_font = newFont;
_textBox.Font = _font;
}
catch (Exception)
{
// When this happens... the PC is broken
ex.Data.Add("fontFamilyName", fontFamily);
ex.Data.Add("fontBold", fontBold); ex.Data.Add("fontBold", fontBold);
ex.Data.Add("fontItalic", fontItalic); ex.Data.Add("fontItalic", fontItalic);
ex.Data.Add("fontSize", fontSize); ex.Data.Add("fontSize", fontSize);
throw; throw ex;
}
} }
UpdateAlignment(); UpdateAlignment();
} }
private void UpdateAlignment() { private void UpdateAlignment()
{
_stringFormat.Alignment = (StringAlignment)GetFieldValue(FieldType.TEXT_HORIZONTAL_ALIGNMENT); _stringFormat.Alignment = (StringAlignment)GetFieldValue(FieldType.TEXT_HORIZONTAL_ALIGNMENT);
_stringFormat.LineAlignment = (StringAlignment)GetFieldValue(FieldType.TEXT_VERTICAL_ALIGNMENT); _stringFormat.LineAlignment = (StringAlignment)GetFieldValue(FieldType.TEXT_VERTICAL_ALIGNMENT);
} }
@ -317,36 +422,43 @@ namespace Greenshot.Drawing {
/// This will create the textbox exactly to the inner size of the element /// This will create the textbox exactly to the inner size of the element
/// is a bit of a hack, but for now it seems to work... /// is a bit of a hack, but for now it seems to work...
/// </summary> /// </summary>
private void UpdateTextBoxPosition() { private void UpdateTextBoxPosition()
{
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); 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; int correction = (lineThickness + 1) % 2;
if (lineThickness <= 1) { if (lineThickness <= 1)
{
lineWidth = 1; lineWidth = 1;
correction = -1; correction = -1;
} }
Rectangle absRectangle = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); Rectangle absRectangle = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
_textBox.Left = absRectangle.Left + lineWidth; _textBox.Left = absRectangle.Left + lineWidth;
_textBox.Top = absRectangle.Top + lineWidth; _textBox.Top = absRectangle.Top + lineWidth;
if (lineThickness <= 1) { if (lineThickness <= 1)
{
lineWidth = 0; lineWidth = 0;
} }
_textBox.Width = absRectangle.Width - (2 * lineWidth) + correction; _textBox.Width = absRectangle.Width - 2 * lineWidth + correction;
_textBox.Height = absRectangle.Height - (2 * lineWidth) + correction; _textBox.Height = absRectangle.Height - 2 * lineWidth + correction;
} }
public override void ApplyBounds(RectangleF newBounds) { public override void ApplyBounds(RectangleF newBounds)
{
base.ApplyBounds(newBounds); base.ApplyBounds(newBounds);
UpdateTextBoxPosition(); UpdateTextBoxPosition();
} }
private void UpdateTextBoxFormat() { private void UpdateTextBoxFormat()
if (_textBox == null) { {
if (_textBox == null)
{
return; return;
} }
StringAlignment alignment = (StringAlignment)GetFieldValue(FieldType.TEXT_HORIZONTAL_ALIGNMENT); var alignment = (StringAlignment)GetFieldValue(FieldType.TEXT_HORIZONTAL_ALIGNMENT);
switch (alignment) { switch (alignment)
{
case StringAlignment.Near: case StringAlignment.Near:
_textBox.TextAlign = HorizontalAlignment.Left; _textBox.TextAlign = HorizontalAlignment.Left;
break; break;
@ -358,25 +470,29 @@ namespace Greenshot.Drawing {
break; break;
} }
Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); var lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR);
_textBox.ForeColor = lineColor; _textBox.ForeColor = lineColor;
} }
void textBox_KeyDown(object sender, KeyEventArgs e) { private void textBox_KeyDown(object sender, KeyEventArgs e)
{
// ESC and Enter/Return (w/o Shift) hide text editor // ESC and Enter/Return (w/o Shift) hide text editor
if(e.KeyCode == Keys.Escape || ((e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter) && e.Modifiers == Keys.None)) { if (e.KeyCode == Keys.Escape || ((e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter) && e.Modifiers == Keys.None))
{
HideTextBox(); HideTextBox();
e.SuppressKeyPress = true; e.SuppressKeyPress = true;
} }
} }
void textBox_LostFocus(object sender, EventArgs e) { private void textBox_LostFocus(object sender, EventArgs e)
{
// next change will be made undoable // next change will be made undoable
makeUndoable = true; makeUndoable = true;
HideTextBox(); HideTextBox();
} }
public override void Draw(Graphics graphics, RenderMode rm) { public override void Draw(Graphics graphics, RenderMode rm)
{
base.Draw(graphics, rm); base.Draw(graphics, rm);
graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality;
@ -386,11 +502,13 @@ namespace Greenshot.Drawing {
graphics.TextRenderingHint = TextRenderingHint.SystemDefault; graphics.TextRenderingHint = TextRenderingHint.SystemDefault;
Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
if (Selected && rm == RenderMode.EDIT) { if (Selected && rm == RenderMode.EDIT)
{
DrawSelectionBorder(graphics, rect); DrawSelectionBorder(graphics, rect);
} }
if (text == null || text.Length == 0 ) { if (string.IsNullOrEmpty(text))
{
return; return;
} }
@ -411,24 +529,38 @@ namespace Greenshot.Drawing {
/// <param name="drawingRectange"></param> /// <param name="drawingRectange"></param>
/// <param name="lineThickness"></param> /// <param name="lineThickness"></param>
/// <param name="fontColor"></param> /// <param name="fontColor"></param>
/// <param name="drawShadow"></param>
/// <param name="stringFormat"></param> /// <param name="stringFormat"></param>
/// <param name="text"></param> /// <param name="text"></param>
/// <param name="font"></param> /// <param name="font"></param>
public static void DrawText(Graphics graphics, Rectangle drawingRectange, int lineThickness, Color fontColor, bool drawShadow, StringFormat stringFormat, string text, Font font) { public static void DrawText(Graphics graphics, Rectangle drawingRectange, int lineThickness, Color fontColor, bool drawShadow, StringFormat stringFormat, string text, Font font)
int textOffset = (lineThickness > 0) ? (int)Math.Ceiling(lineThickness / 2d) : 0; {
#if DEBUG
Debug.Assert(font != null);
#else
if (font == null)
{
return;
}
#endif
int textOffset = lineThickness > 0 ? (int)Math.Ceiling(lineThickness / 2d) : 0;
// draw shadow before anything else // draw shadow before anything else
if (drawShadow) { if (drawShadow)
{
int basealpha = 100; int basealpha = 100;
int alpha = basealpha; int alpha = basealpha;
int steps = 5; int steps = 5;
int currentStep = 1; int currentStep = 1;
while (currentStep <= steps) { while (currentStep <= steps)
{
int offset = currentStep; int offset = currentStep;
Rectangle shadowRect = GuiRectangle.GetGuiRectangle(drawingRectange.Left + offset, drawingRectange.Top + offset, drawingRectange.Width, drawingRectange.Height); Rectangle shadowRect = GuiRectangle.GetGuiRectangle(drawingRectange.Left + offset, drawingRectange.Top + offset, drawingRectange.Width, drawingRectange.Height);
if (lineThickness > 0) { if (lineThickness > 0)
{
shadowRect.Inflate(-textOffset, -textOffset); shadowRect.Inflate(-textOffset, -textOffset);
} }
using (Brush fontBrush = new SolidBrush(Color.FromArgb(alpha, 100, 100, 100))) { using (Brush fontBrush = new SolidBrush(Color.FromArgb(alpha, 100, 100, 100)))
{
graphics.DrawString(text, font, fontBrush, shadowRect, stringFormat); graphics.DrawString(text, font, fontBrush, shadowRect, stringFormat);
currentStep++; currentStep++;
alpha = alpha - basealpha / steps; alpha = alpha - basealpha / steps;
@ -436,19 +568,25 @@ namespace Greenshot.Drawing {
} }
} }
if (lineThickness > 0) { if (lineThickness > 0)
{
drawingRectange.Inflate(-textOffset, -textOffset); drawingRectange.Inflate(-textOffset, -textOffset);
} }
using (Brush fontBrush = new SolidBrush(fontColor)) { using (Brush fontBrush = new SolidBrush(fontColor))
if (stringFormat != null) { {
if (stringFormat != null)
{
graphics.DrawString(text, font, fontBrush, drawingRectange, stringFormat); graphics.DrawString(text, font, fontBrush, drawingRectange, stringFormat);
} else { }
else
{
graphics.DrawString(text, font, fontBrush, drawingRectange); graphics.DrawString(text, font, fontBrush, drawingRectange);
} }
} }
} }
public override bool ClickableAt(int x, int y) { public override bool ClickableAt(int x, int y)
{
Rectangle r = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); Rectangle r = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
r.Inflate(5, 5); r.Inflate(5, 5);
return r.Contains(x, y); return r.Contains(x, y);

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -19,6 +19,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System.Reflection;
namespace Greenshot { namespace Greenshot {
partial class AboutForm { partial class AboutForm {
/// <summary> /// <summary>
@ -104,7 +106,7 @@ namespace Greenshot {
this.linkLblHost.Size = new System.Drawing.Size(465, 23); this.linkLblHost.Size = new System.Drawing.Size(465, 23);
this.linkLblHost.TabIndex = 6; this.linkLblHost.TabIndex = 6;
this.linkLblHost.TabStop = true; this.linkLblHost.TabStop = true;
this.linkLblHost.Text = "http://sourceforge.net/projects/greenshot/"; this.linkLblHost.Text = "https://github.com/greenshot/greenshot";
this.linkLblHost.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked); this.linkLblHost.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked);
// //
// linkLblBugs // linkLblBugs
@ -114,7 +116,7 @@ namespace Greenshot {
this.linkLblBugs.Size = new System.Drawing.Size(465, 23); this.linkLblBugs.Size = new System.Drawing.Size(465, 23);
this.linkLblBugs.TabIndex = 8; this.linkLblBugs.TabIndex = 8;
this.linkLblBugs.TabStop = true; this.linkLblBugs.TabStop = true;
this.linkLblBugs.Text = "http://getgreenshot.org/tickets/"; this.linkLblBugs.Text = "http://getgreenshot.org/tickets/?version=" + Assembly.GetEntryAssembly().GetName().Version;
this.linkLblBugs.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked); this.linkLblBugs.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked);
// //
// lblBugs // lblBugs
@ -132,7 +134,7 @@ namespace Greenshot {
this.linkLblDonations.Size = new System.Drawing.Size(465, 23); this.linkLblDonations.Size = new System.Drawing.Size(465, 23);
this.linkLblDonations.TabIndex = 10; this.linkLblDonations.TabIndex = 10;
this.linkLblDonations.TabStop = true; this.linkLblDonations.TabStop = true;
this.linkLblDonations.Text = "http://getgreenshot.org/support/"; this.linkLblDonations.Text = "http://getgreenshot.org/support/?version=" + Assembly.GetEntryAssembly().GetName().Version;
this.linkLblDonations.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked); this.linkLblDonations.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked);
// //
// lblDonations // lblDonations

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -41,21 +41,21 @@ namespace Greenshot {
/// The about form /// The about form
/// </summary> /// </summary>
public partial class AboutForm : AnimatingBaseForm { public partial class AboutForm : AnimatingBaseForm {
private static ILog LOG = LogManager.GetLogger(typeof(AboutForm)); private static readonly ILog LOG = LogManager.GetLogger(typeof(AboutForm));
private Bitmap gBitmap; private Bitmap _bitmap;
private ColorAnimator backgroundAnimation; private readonly ColorAnimator _backgroundAnimation;
private List<RectangleAnimator> pixels = new List<RectangleAnimator>(); private readonly IList<RectangleAnimator> _pixels = new List<RectangleAnimator>();
private List<Color> colorFlow = new List<Color>(); private readonly IList<Color> _colorFlow = new List<Color>();
private List<Color> pixelColors = new List<Color>(); private readonly IList<Color> _pixelColors = new List<Color>();
private Random rand = new Random(); private readonly Random _rand = new Random();
private readonly Color backColor = Color.FromArgb(61, 61, 61); private readonly Color _backColor = Color.FromArgb(61, 61, 61);
private readonly Color pixelColor = Color.FromArgb(138, 255, 0); private readonly Color _pixelColor = Color.FromArgb(138, 255, 0);
// Variables used for the color-cycle // Variables used for the color-cycle
private int waitFrames = 0; private int _waitFrames;
private int colorIndex = 0; private int _colorIndex;
private int scrollCount = 0; private int _scrollCount;
private bool hasAnimationsLeft; private bool _hasAnimationsLeft;
// Variables are used to define the location of the dots // Variables are used to define the location of the dots
private const int w = 13; private const int w = 13;
@ -70,7 +70,7 @@ namespace Greenshot {
/// <summary> /// <summary>
/// The location of every dot in the "G" /// The location of every dot in the "G"
/// </summary> /// </summary>
private List<Point> gSpots = new List<Point>() { private readonly List<Point> gSpots = new List<Point>() {
// Top row // Top row
new Point(p2, p1), // 0 new Point(p2, p1), // 0
new Point(p3, p1), // 1 new Point(p3, p1), // 1
@ -116,15 +116,15 @@ namespace Greenshot {
// 18 19 20 21 22 23 // 18 19 20 21 22 23
// The order in which we draw the dots & flow the collors. // The order in which we draw the dots & flow the collors.
List<int> flowOrder = new List<int>() { 4, 3, 2, 1, 0, 5, 6, 7, 8, 9, 10, 14, 15, 18, 19, 20, 21, 22, 23, 16, 17, 13, 12, 11 }; private readonly List<int> flowOrder = new List<int>() { 4, 3, 2, 1, 0, 5, 6, 7, 8, 9, 10, 14, 15, 18, 19, 20, 21, 22, 23, 16, 17, 13, 12, 11 };
/// <summary> /// <summary>
/// Cleanup all the allocated resources /// Cleanup all the allocated resources
/// </summary> /// </summary>
private void Cleanup(object sender, EventArgs e) { private void Cleanup(object sender, EventArgs e) {
if (gBitmap != null) { if (_bitmap != null) {
gBitmap.Dispose(); _bitmap.Dispose();
gBitmap = null; _bitmap = null;
} }
} }
@ -144,22 +144,22 @@ namespace Greenshot {
InitializeComponent(); InitializeComponent();
// Only use double-buffering when we are NOT in a Terminal Server session // Only use double-buffering when we are NOT in a Terminal Server session
DoubleBuffered = !isTerminalServerSession; DoubleBuffered = !IsTerminalServerSession;
// Use the self drawn image, first we create the background to be the backcolor (as we animate from this) // Use the self drawn image, first we create the background to be the backcolor (as we animate from this)
gBitmap = ImageHelper.CreateEmpty(90, 90, PixelFormat.Format24bppRgb, BackColor, 96, 96); _bitmap = ImageHelper.CreateEmpty(90, 90, PixelFormat.Format24bppRgb, BackColor, 96, 96);
pictureBox1.Image = gBitmap; pictureBox1.Image = _bitmap;
Version v = Assembly.GetExecutingAssembly().GetName().Version; Version v = Assembly.GetExecutingAssembly().GetName().Version;
// Format is like this: AssemblyVersion("Major.Minor.Build.Revision")] // Format is like this: AssemblyVersion("Major.Minor.Build.Revision")]
lblTitle.Text = "Greenshot " + v.Major + "." + v.Minor + "." + v.Build + " Build " + v.Revision + (IniConfig.IsPortable ? " Portable" : "") + (" (" + OSInfo.Bits + " bit)"); lblTitle.Text = "Greenshot " + v.Major + "." + v.Minor + "." + v.Build + " Build " + v.Revision + (IniConfig.IsPortable ? " Portable" : "") + (" (" + OsInfo.Bits) + " bit)";
//Random rand = new Random(); //Random rand = new Random();
// Number of frames the pixel animation takes // Number of frames the pixel animation takes
int frames = FramesForMillis(2000); int frames = FramesForMillis(2000);
// The number of frames the color-cycle waits before it starts // The number of frames the color-cycle waits before it starts
waitFrames = FramesForMillis(6000); _waitFrames = FramesForMillis(6000);
// Every pixel is created after pixelWaitFrames frames, which is increased in the loop. // Every pixel is created after pixelWaitFrames frames, which is increased in the loop.
int pixelWaitFrames = FramesForMillis(2000); int pixelWaitFrames = FramesForMillis(2000);
@ -174,7 +174,7 @@ namespace Greenshot {
int offset = (w - 2) / 2; int offset = (w - 2) / 2;
// If the optimize for Terminal Server is set we make the animation without much ado // If the optimize for Terminal Server is set we make the animation without much ado
if (isTerminalServerSession) { if (IsTerminalServerSession) {
// No animation // No animation
pixelAnimation = new RectangleAnimator(new Rectangle(gSpot.X, gSpot.Y, w - 2, w - 2), new Rectangle(gSpot.X, gSpot.Y, w - 2, w - 2), 1, EasingType.Cubic, EasingMode.EaseIn); pixelAnimation = new RectangleAnimator(new Rectangle(gSpot.X, gSpot.Y, w - 2, w - 2), new Rectangle(gSpot.X, gSpot.Y, w - 2, w - 2), 1, EasingType.Cubic, EasingMode.EaseIn);
} else { } else {
@ -187,23 +187,23 @@ namespace Greenshot {
// Increase the wait frames // Increase the wait frames
pixelWaitFrames += FramesForMillis(100); pixelWaitFrames += FramesForMillis(100);
// Add to the list of to be animated pixels // Add to the list of to be animated pixels
pixels.Add(pixelAnimation); _pixels.Add(pixelAnimation);
// Add a color to the list for this pixel. // Add a color to the list for this pixel.
pixelColors.Add(pixelColor); _pixelColors.Add(_pixelColor);
} }
// Make sure the frame "loop" knows we have to animate // Make sure the frame "loop" knows we have to animate
hasAnimationsLeft = true; _hasAnimationsLeft = true;
// Pixel Color cycle colors, here we use a pre-animated loop which stores the values. // 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 ColorAnimator(_pixelColor, Color.FromArgb(255, 255, 255), 6, EasingType.Quadratic, EasingMode.EaseIn);
pixelColorAnimator.QueueDestinationLeg(pixelColor, 6, EasingType.Quadratic, EasingMode.EaseOut); pixelColorAnimator.QueueDestinationLeg(_pixelColor, 6, EasingType.Quadratic, EasingMode.EaseOut);
do { do {
colorFlow.Add(pixelColorAnimator.Current); _colorFlow.Add(pixelColorAnimator.Current);
pixelColorAnimator.Next(); pixelColorAnimator.Next();
} while (pixelColorAnimator.hasNext); } while (pixelColorAnimator.HasNext);
// color animation for the background // color animation for the background
backgroundAnimation = new ColorAnimator(BackColor, backColor, FramesForMillis(5000), EasingType.Linear, EasingMode.EaseIn); _backgroundAnimation = new ColorAnimator(BackColor, _backColor, FramesForMillis(5000), EasingType.Linear, EasingMode.EaseIn);
} }
/// <summary> /// <summary>
@ -211,7 +211,7 @@ namespace Greenshot {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void LinkLabelClicked(object sender, LinkLabelLinkClickedEventArgs e) { private void LinkLabelClicked(object sender, LinkLabelLinkClickedEventArgs e) {
LinkLabel linkLabel = sender as LinkLabel; LinkLabel linkLabel = sender as LinkLabel;
if (linkLabel != null) { if (linkLabel != null) {
try { try {
@ -227,63 +227,63 @@ namespace Greenshot {
/// Called from the AnimatingForm, for every frame /// Called from the AnimatingForm, for every frame
/// </summary> /// </summary>
protected override void Animate() { protected override void Animate() {
if (gBitmap == null) { if (_bitmap == null) {
return; return;
} }
if (!isTerminalServerSession) { if (!IsTerminalServerSession) {
// Color cycle // Color cycle
if (waitFrames != 0) { if (_waitFrames != 0) {
waitFrames--; _waitFrames--;
// Check if there is something else to do, if not we return so we don't occupy the CPU // Check if there is something else to do, if not we return so we don't occupy the CPU
if (!hasAnimationsLeft) { if (!_hasAnimationsLeft) {
return; return;
} }
} else if (scrollCount < (pixelColors.Count + colorFlow.Count)) { } else if (_scrollCount < _pixelColors.Count + _colorFlow.Count) {
// Scroll colors, the scrollCount is the amount of pixels + the amount of colors to cycle. // Scroll colors, the scrollCount is the amount of pixels + the amount of colors to cycle.
for (int index = pixelColors.Count - 1; index > 0; index--) { for (int index = _pixelColors.Count - 1; index > 0; index--) {
pixelColors[index] = pixelColors[index - 1]; _pixelColors[index] = _pixelColors[index - 1];
} }
// Keep adding from the colors to cycle until there is nothing left // Keep adding from the colors to cycle until there is nothing left
if (colorIndex < colorFlow.Count) { if (_colorIndex < _colorFlow.Count) {
pixelColors[0] = colorFlow[colorIndex++]; _pixelColors[0] = _colorFlow[_colorIndex++];
} }
scrollCount++; _scrollCount++;
} else { } else {
// Reset values, wait X time for the next one // Reset values, wait X time for the next one
waitFrames = FramesForMillis(3000 + rand.Next(35000)); _waitFrames = FramesForMillis(3000 + _rand.Next(35000));
colorIndex = 0; _colorIndex = 0;
scrollCount = 0; _scrollCount = 0;
// Check if there is something else to do, if not we return so we don't occupy the CPU // Check if there is something else to do, if not we return so we don't occupy the CPU
if (!hasAnimationsLeft) { if (!_hasAnimationsLeft) {
return; return;
} }
} }
} else if (!hasAnimationsLeft) { } else if (!_hasAnimationsLeft) {
return; return;
} }
// Draw the "G" // Draw the "G"
using (Graphics graphics = Graphics.FromImage(gBitmap)) { using (Graphics graphics = Graphics.FromImage(_bitmap)) {
graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBilinear; graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.Clear(backgroundAnimation.Next()); graphics.Clear(_backgroundAnimation.Next());
graphics.TranslateTransform(2, -2); graphics.TranslateTransform(2, -2);
graphics.RotateTransform(20); graphics.RotateTransform(20);
using (SolidBrush brush = new SolidBrush(pixelColor)) { using (SolidBrush brush = new SolidBrush(_pixelColor)) {
int index = 0; int index = 0;
// We asume there is nothing to animate in the next Animate loop // We asume there is nothing to animate in the next Animate loop
hasAnimationsLeft = false; _hasAnimationsLeft = false;
// Pixels of the G // Pixels of the G
foreach (RectangleAnimator pixel in pixels) { foreach (RectangleAnimator pixel in _pixels) {
brush.Color = pixelColors[index++]; brush.Color = _pixelColors[index++];
graphics.FillEllipse(brush, pixel.Current); graphics.FillEllipse(brush, pixel.Current);
// If a pixel still has frames left, the hasAnimationsLeft will be true // If a pixel still has frames left, the hasAnimationsLeft will be true
hasAnimationsLeft = hasAnimationsLeft | pixel.hasNext; _hasAnimationsLeft = _hasAnimationsLeft | pixel.HasNext;
pixel.Next(); pixel.Next();
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -38,7 +38,7 @@ namespace Greenshot.Forms {
textBoxDescription.Text = bugText; textBoxDescription.Text = bugText;
} }
void LinkLblBugsLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { private void LinkLblBugsLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
openLink((LinkLabel)sender); openLink((LinkLabel)sender);
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -40,10 +40,10 @@ namespace Greenshot.Forms {
/// <summary> /// <summary>
/// The capture form is used to select a part of the capture /// The capture form is used to select a part of the capture
/// </summary> /// </summary>
public partial class CaptureForm : AnimatingForm { public sealed partial class CaptureForm : AnimatingForm {
private enum FixMode {None, Initiated, Horizontal, Vertical}; private enum FixMode {None, Initiated, Horizontal, Vertical};
private static readonly ILog LOG = LogManager.GetLogger(typeof(CaptureForm)); private static readonly ILog Log = LogManager.GetLogger(typeof(CaptureForm));
private static readonly CoreConfiguration Conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration Conf = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly Brush GreenOverlayBrush = new SolidBrush(Color.FromArgb(50, Color.MediumSeaGreen)); 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 Pen(Color.FromArgb(50, Color.Black));
@ -61,9 +61,9 @@ namespace Greenshot.Forms {
private int _mX; private int _mX;
private int _mY; private int _mY;
private Point _mouseMovePos = Point.Empty; private Point _mouseMovePos = Point.Empty;
private Point _cursorPos = Point.Empty; private Point _cursorPos;
private CaptureMode _captureMode = CaptureMode.None; private CaptureMode _captureMode;
private readonly List<WindowDetails> _windows = new List<WindowDetails>(); private readonly List<WindowDetails> _windows;
private WindowDetails _selectedCaptureWindow; private WindowDetails _selectedCaptureWindow;
private bool _mouseDown; private bool _mouseDown;
private Rectangle _captureRect = Rectangle.Empty; private Rectangle _captureRect = Rectangle.Empty;
@ -73,34 +73,23 @@ namespace Greenshot.Forms {
private RectangleAnimator _windowAnimator; private RectangleAnimator _windowAnimator;
private RectangleAnimator _zoomAnimator; private RectangleAnimator _zoomAnimator;
private readonly bool _isZoomerTransparent = Conf.ZoomerOpacity < 1; private readonly bool _isZoomerTransparent = Conf.ZoomerOpacity < 1;
private bool _isCtrlPressed = false; private bool _isCtrlPressed;
private bool _showDebugInfo;
/// <summary> /// <summary>
/// Property to access the selected capture rectangle /// Property to access the selected capture rectangle
/// </summary> /// </summary>
public Rectangle CaptureRectangle { public Rectangle CaptureRectangle => _captureRect;
get {
return _captureRect;
}
}
/// <summary> /// <summary>
/// Property to access the used capture mode /// Property to access the used capture mode
/// </summary> /// </summary>
public CaptureMode UsedCaptureMode { public CaptureMode UsedCaptureMode => _captureMode;
get {
return _captureMode;
}
}
/// <summary> /// <summary>
/// Get the selected window /// Get the selected window
/// </summary> /// </summary>
public WindowDetails SelectedCaptureWindow { public WindowDetails SelectedCaptureWindow => _selectedCaptureWindow;
get {
return _selectedCaptureWindow;
}
}
/// <summary> /// <summary>
/// This should prevent childs to draw backgrounds /// This should prevent childs to draw backgrounds
@ -108,19 +97,19 @@ namespace Greenshot.Forms {
protected override CreateParams CreateParams { protected override CreateParams CreateParams {
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get { get {
CreateParams cp = base.CreateParams; CreateParams createParams = base.CreateParams;
cp.ExStyle |= 0x02000000; createParams.ExStyle |= 0x02000000;
return cp; return createParams;
} }
} }
private void ClosedHandler(object sender, EventArgs e) { private void ClosedHandler(object sender, EventArgs e) {
_currentForm = null; _currentForm = null;
LOG.Debug("Remove CaptureForm from currentForm"); Log.Debug("Remove CaptureForm from currentForm");
} }
private void ClosingHandler(object sender, EventArgs e) { private void ClosingHandler(object sender, EventArgs e) {
LOG.Debug("Closing captureform"); Log.Debug("Closing captureform");
WindowDetails.UnregisterIgnoreHandle(Handle); WindowDetails.UnregisterIgnoreHandle(Handle);
} }
@ -131,7 +120,7 @@ namespace Greenshot.Forms {
/// <param name="windows"></param> /// <param name="windows"></param>
public CaptureForm(ICapture capture, List<WindowDetails> windows) { public CaptureForm(ICapture capture, List<WindowDetails> windows) {
if (_currentForm != null) { if (_currentForm != null) {
LOG.Warn("Found currentForm, Closing already opened CaptureForm"); Log.Warn("Found currentForm, Closing already opened CaptureForm");
_currentForm.Close(); _currentForm.Close();
_currentForm = null; _currentForm = null;
Application.DoEvents(); Application.DoEvents();
@ -153,7 +142,7 @@ namespace Greenshot.Forms {
// //
InitializeComponent(); InitializeComponent();
// Only double-buffer when we are not in a TerminalServerSession // Only double-buffer when we are not in a TerminalServerSession
DoubleBuffered = !isTerminalServerSession; DoubleBuffered = !IsTerminalServerSession;
Text = "Greenshot capture form"; Text = "Greenshot capture form";
// Make sure we never capture the captureform // Make sure we never capture the captureform
@ -184,18 +173,21 @@ namespace Greenshot.Forms {
/// <summary> /// <summary>
/// Create an animation for the zoomer, depending on if it's active or not. /// Create an animation for the zoomer, depending on if it's active or not.
/// </summary> /// </summary>
void InitializeZoomer(bool isOn) { private void InitializeZoomer(bool isOn) {
if (isOn) { if (isOn) {
// Initialize the zoom with a invalid position // Initialize the zoom with a invalid position
_zoomAnimator = new RectangleAnimator(Rectangle.Empty, new Rectangle(int.MaxValue, int.MaxValue, 0, 0), FramesForMillis(1000), EasingType.Quintic, EasingMode.EaseOut); _zoomAnimator = new RectangleAnimator(Rectangle.Empty, new Rectangle(int.MaxValue, int.MaxValue, 0, 0), FramesForMillis(1000), EasingType.Quintic, EasingMode.EaseOut);
VerifyZoomAnimation(_cursorPos, false); VerifyZoomAnimation(_cursorPos, false);
} else if (_zoomAnimator != null) { }
_zoomAnimator.ChangeDestination(new Rectangle(Point.Empty, Size.Empty), FramesForMillis(1000)); else
{
_zoomAnimator?.ChangeDestination(new Rectangle(Point.Empty, Size.Empty), FramesForMillis(1000));
} }
} }
#region key handling #region key handling
void CaptureFormKeyUp(object sender, KeyEventArgs e) {
private void CaptureFormKeyUp(object sender, KeyEventArgs e) {
switch(e.KeyCode) { switch(e.KeyCode) {
case Keys.ShiftKey: case Keys.ShiftKey:
_fixMode = FixMode.None; _fixMode = FixMode.None;
@ -211,7 +203,7 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void CaptureFormKeyDown(object sender, KeyEventArgs e) { private void CaptureFormKeyDown(object sender, KeyEventArgs e) {
int step = _isCtrlPressed ? 10 : 1; int step = _isCtrlPressed ? 10 : 1;
switch (e.KeyCode) { switch (e.KeyCode) {
@ -263,6 +255,14 @@ namespace Greenshot.Forms {
Invalidate(); Invalidate();
} }
break; break;
case Keys.D:
if (_captureMode == CaptureMode.Window)
{
// Toggle debug
_showDebugInfo = !_showDebugInfo;
Invalidate();
}
break;
case Keys.Space: case Keys.Space:
// Toggle capture mode // Toggle capture mode
switch (_captureMode) { switch (_captureMode) {
@ -300,6 +300,10 @@ namespace Greenshot.Forms {
HandleMouseUp(); HandleMouseUp();
} }
break; break;
case Keys.F:
ToFront = !ToFront;
TopMost = !TopMost;
break;
} }
} }
#endregion #endregion
@ -310,7 +314,7 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void OnMouseDown(object sender, MouseEventArgs e) { private void OnMouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) { if (e.Button == MouseButtons.Left) {
HandleMouseDown(); HandleMouseDown();
} }
@ -351,7 +355,7 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void OnMouseUp(object sender, MouseEventArgs e) { private void OnMouseUp(object sender, MouseEventArgs e) {
if (_mouseDown) { if (_mouseDown) {
HandleMouseUp(); HandleMouseUp();
} }
@ -383,7 +387,7 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void OnMouseMove(object sender, MouseEventArgs e) { private void OnMouseMove(object sender, MouseEventArgs e) {
// Make sure the mouse coordinates are fixed, when pressing shift // Make sure the mouse coordinates are fixed, when pressing shift
_mouseMovePos = FixMouseCoordinates(User32.GetCursorLocation()); _mouseMovePos = FixMouseCoordinates(User32.GetCursorLocation());
_mouseMovePos = WindowCapture.GetLocationRelativeToScreenBounds(_mouseMovePos); _mouseMovePos = WindowCapture.GetLocationRelativeToScreenBounds(_mouseMovePos);
@ -394,11 +398,11 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
/// <param name="animator"></param> /// <param name="animator"></param>
/// <returns></returns> /// <returns></returns>
bool isAnimating(IAnimator animator) { private bool IsAnimating(IAnimator animator) {
if (animator == null) { if (animator == null) {
return false; return false;
} }
return animator.hasNext; return animator.HasNext;
} }
/// <summary> /// <summary>
@ -408,7 +412,7 @@ namespace Greenshot.Forms {
Point lastPos = _cursorPos; Point lastPos = _cursorPos;
_cursorPos = _mouseMovePos; _cursorPos = _mouseMovePos;
if (_selectedCaptureWindow != null && lastPos.Equals(_cursorPos) && !isAnimating(_zoomAnimator) && !isAnimating(_windowAnimator)) { if (_selectedCaptureWindow != null && lastPos.Equals(_cursorPos) && !IsAnimating(_zoomAnimator) && !IsAnimating(_windowAnimator)) {
return; return;
} }
@ -431,18 +435,16 @@ namespace Greenshot.Forms {
Point cursorPosition = Cursor.Position; Point cursorPosition = Cursor.Position;
_selectedCaptureWindow = null; _selectedCaptureWindow = null;
lock (_windows) { lock (_windows) {
foreach (WindowDetails window in _windows) { foreach (var window in _windows) {
if (window.Contains(cursorPosition)) { if (!window.Contains(cursorPosition))
{
continue;
}
// Only go over the children if we are in window mode // Only go over the children if we are in window mode
if (CaptureMode.Window == _captureMode) { _selectedCaptureWindow = CaptureMode.Window == _captureMode ? window.FindChildUnderPoint(cursorPosition) : window;
_selectedCaptureWindow = window.FindChildUnderPoint(cursorPosition);
} else {
_selectedCaptureWindow = window;
}
break; break;
} }
} }
}
if (_selectedCaptureWindow != null && !_selectedCaptureWindow.Equals(lastWindow)) { if (_selectedCaptureWindow != null && !_selectedCaptureWindow.Equals(lastWindow)) {
_capture.CaptureDetails.Title = _selectedCaptureWindow.Text; _capture.CaptureDetails.Title = _selectedCaptureWindow.Text;
@ -486,7 +488,7 @@ namespace Greenshot.Forms {
invalidateRectangle = new Rectangle(x1,y1, x2-x1, y2-y1); invalidateRectangle = new Rectangle(x1,y1, x2-x1, y2-y1);
Invalidate(invalidateRectangle); Invalidate(invalidateRectangle);
} else if (_captureMode != CaptureMode.Window) { } else if (_captureMode != CaptureMode.Window) {
if (!isTerminalServerSession) { if (!IsTerminalServerSession) {
Rectangle allScreenBounds = WindowCapture.GetScreenBounds(); Rectangle allScreenBounds = WindowCapture.GetScreenBounds();
allScreenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(allScreenBounds.Location); allScreenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(allScreenBounds.Location);
if (verticalMove) { if (verticalMove) {
@ -515,8 +517,8 @@ namespace Greenshot.Forms {
// always animate the Window area through to the last frame, so we see the fade-in/out untill the end // always animate the Window area through to the last frame, so we see the fade-in/out untill the end
// Using a safety "offset" to make sure the text is invalidated too // Using a safety "offset" to make sure the text is invalidated too
const int safetySize = 30; const int safetySize = 30;
// Check if the // Check if the animation needs to be drawn
if (isAnimating(_windowAnimator)) { if (IsAnimating(_windowAnimator)) {
invalidateRectangle = _windowAnimator.Current; invalidateRectangle = _windowAnimator.Current;
invalidateRectangle.Inflate(safetySize, safetySize); invalidateRectangle.Inflate(safetySize, safetySize);
Invalidate(invalidateRectangle); Invalidate(invalidateRectangle);
@ -524,12 +526,12 @@ namespace Greenshot.Forms {
invalidateRectangle.Inflate(safetySize, safetySize); invalidateRectangle.Inflate(safetySize, safetySize);
Invalidate(invalidateRectangle); Invalidate(invalidateRectangle);
// Check if this was the last of the windows animations in the normal region capture. // Check if this was the last of the windows animations in the normal region capture.
if (_captureMode != CaptureMode.Window && !isAnimating(_windowAnimator)) { if (_captureMode != CaptureMode.Window && !IsAnimating(_windowAnimator)) {
Invalidate(); Invalidate();
} }
} }
if (_zoomAnimator != null && (isAnimating(_zoomAnimator) || _captureMode != CaptureMode.Window)) { if (_zoomAnimator != null && (IsAnimating(_zoomAnimator) || _captureMode != CaptureMode.Window)) {
// Make sure we invalidate the old zoom area // Make sure we invalidate the old zoom area
invalidateRectangle = _zoomAnimator.Current; invalidateRectangle = _zoomAnimator.Current;
invalidateRectangle.Offset(lastPos); invalidateRectangle.Offset(lastPos);
@ -540,11 +542,7 @@ namespace Greenshot.Forms {
} }
// The following logic is not needed, next always returns the current if there are no frames left // The following logic is not needed, next always returns the current if there are no frames left
// but it makes more sense if we want to change something in the logic // but it makes more sense if we want to change something in the logic
if (isAnimating(_zoomAnimator)) { invalidateRectangle = IsAnimating(_zoomAnimator) ? _zoomAnimator.Next() : _zoomAnimator.Current;
invalidateRectangle = _zoomAnimator.Next();
} else {
invalidateRectangle = _zoomAnimator.Current;
}
invalidateRectangle.Offset(_cursorPos); invalidateRectangle.Offset(_cursorPos);
Invalidate(invalidateRectangle); Invalidate(invalidateRectangle);
} }
@ -570,7 +568,7 @@ namespace Greenshot.Forms {
screenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(screenBounds.Location); screenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(screenBounds.Location);
int relativeZoomSize = Math.Min(screenBounds.Width, screenBounds.Height) / 5; int relativeZoomSize = Math.Min(screenBounds.Width, screenBounds.Height) / 5;
// Make sure the final size is a plural of 4, this makes it look better // Make sure the final size is a plural of 4, this makes it look better
relativeZoomSize = relativeZoomSize - (relativeZoomSize % 4); relativeZoomSize = relativeZoomSize - relativeZoomSize % 4;
Size zoomSize = new Size(relativeZoomSize, relativeZoomSize); Size zoomSize = new Size(relativeZoomSize, relativeZoomSize);
Point zoomOffset = new Point(20, 20); Point zoomOffset = new Point(20, 20);
@ -613,8 +611,10 @@ namespace Greenshot.Forms {
if (_isZoomerTransparent) { if (_isZoomerTransparent) {
//create a color matrix object to change the opacy //create a color matrix object to change the opacy
ColorMatrix opacyMatrix = new ColorMatrix(); ColorMatrix opacyMatrix = new ColorMatrix
opacyMatrix.Matrix33 = Conf.ZoomerOpacity; {
Matrix33 = Conf.ZoomerOpacity
};
attributes = new ImageAttributes(); attributes = new ImageAttributes();
attributes.SetColorMatrix(opacyMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); attributes.SetColorMatrix(opacyMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
} else { } else {
@ -652,9 +652,9 @@ namespace Greenshot.Forms {
// Calculate some values // Calculate some values
int pixelThickness = destinationRectangle.Width / sourceRectangle.Width; int pixelThickness = destinationRectangle.Width / sourceRectangle.Width;
int halfWidth = destinationRectangle.Width / 2; 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 halfHeight = destinationRectangle.Height / 2;
int halfHeightEnd = (destinationRectangle.Height / 2) - (pixelThickness / 2); int halfHeightEnd = destinationRectangle.Height / 2 - pixelThickness / 2;
int drawAtHeight = destinationRectangle.Y + halfHeight; int drawAtHeight = destinationRectangle.Y + halfHeight;
int drawAtWidth = destinationRectangle.X + halfWidth; int drawAtWidth = destinationRectangle.X + halfWidth;
@ -673,8 +673,8 @@ namespace Greenshot.Forms {
graphics.DrawLine(pen, destinationRectangle.X + halfWidthEnd + 2 * padding, drawAtHeight, destinationRectangle.X + destinationRectangle.Width - padding, drawAtHeight); graphics.DrawLine(pen, destinationRectangle.X + halfWidthEnd + 2 * padding, drawAtHeight, destinationRectangle.X + destinationRectangle.Width - padding, drawAtHeight);
// Fix offset for drawing the white rectangle around the crosshair-lines // Fix offset for drawing the white rectangle around the crosshair-lines
drawAtHeight -= (pixelThickness / 2); drawAtHeight -= pixelThickness / 2;
drawAtWidth -= (pixelThickness / 2); drawAtWidth -= pixelThickness / 2;
// Fix off by one error with the DrawRectangle // Fix off by one error with the DrawRectangle
pixelThickness -= 1; pixelThickness -= 1;
// Change the color and the pen width // Change the color and the pen width
@ -689,9 +689,7 @@ namespace Greenshot.Forms {
// Horizontal middle + 1 to right // 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);
} }
if (attributes != null) { attributes?.Dispose();
attributes.Dispose();
}
} }
/// <summary> /// <summary>
@ -699,7 +697,7 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void OnPaint(object sender, PaintEventArgs e) { private void OnPaint(object sender, PaintEventArgs e) {
Graphics graphics = e.Graphics; Graphics graphics = e.Graphics;
Rectangle clipRectangle = e.ClipRectangle; Rectangle clipRectangle = e.ClipRectangle;
//graphics.BitBlt((Bitmap)buffer, Point.Empty); //graphics.BitBlt((Bitmap)buffer, Point.Empty);
@ -709,17 +707,10 @@ namespace Greenshot.Forms {
graphics.DrawIcon(_capture.Cursor, _capture.CursorLocation.X, _capture.CursorLocation.Y); graphics.DrawIcon(_capture.Cursor, _capture.CursorLocation.X, _capture.CursorLocation.Y);
} }
if (_mouseDown || _captureMode == CaptureMode.Window || isAnimating(_windowAnimator)) { if (_mouseDown || _captureMode == CaptureMode.Window || IsAnimating(_windowAnimator)) {
_captureRect.Intersect(new Rectangle(Point.Empty, _capture.ScreenBounds.Size)); // crop what is outside the screen _captureRect.Intersect(new Rectangle(Point.Empty, _capture.ScreenBounds.Size)); // crop what is outside the screen
Rectangle fixedRect; var fixedRect = IsAnimating(_windowAnimator) ? _windowAnimator.Current : _captureRect;
//if (captureMode == CaptureMode.Window) {
if (isAnimating(_windowAnimator)) {
// Use the animator
fixedRect = _windowAnimator.Current;
} else {
fixedRect = _captureRect;
}
// TODO: enable when the screen capture code works reliable // TODO: enable when the screen capture code works reliable
//if (capture.CaptureDetails.CaptureMode == CaptureMode.Video) { //if (capture.CaptureDetails.CaptureMode == CaptureMode.Video) {
@ -762,7 +753,7 @@ namespace Greenshot.Forms {
graphics.DrawPath(rulerPen, p); graphics.DrawPath(rulerPen, p);
graphics.DrawString(captureWidth, rulerFont, rulerPen.Brush, fixedRect.X + (fixedRect.Width / 2 - hSpace / 2) + 3, fixedRect.Y - dist - 7); 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.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.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.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); graphics.DrawLine(rulerPen, fixedRect.X + fixedRect.Width, fixedRect.Y - dist - 3, fixedRect.X + fixedRect.Width, fixedRect.Y - dist + 3);
} }
@ -780,7 +771,7 @@ namespace Greenshot.Forms {
graphics.DrawPath(rulerPen, 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.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.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, 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.X - dist + 3, fixedRect.Y);
graphics.DrawLine(rulerPen, fixedRect.X - dist - 3, fixedRect.Y + fixedRect.Height, fixedRect.X - dist + 3, fixedRect.Y + fixedRect.Height); graphics.DrawLine(rulerPen, fixedRect.X - dist - 3, fixedRect.Y + fixedRect.Height, fixedRect.X - dist + 3, fixedRect.Y + fixedRect.Height);
} }
@ -797,7 +788,7 @@ namespace Greenshot.Forms {
string sizeText; string sizeText;
if (_captureMode == CaptureMode.Region) { if (_captureMode == CaptureMode.Region) {
// correct the GUI width to real width for the shown size // correct the GUI width to real width for the shown size
sizeText = (_captureRect.Width + 1) + " x " + (_captureRect.Height + 1); sizeText = _captureRect.Width + 1 + " x " + (_captureRect.Height + 1);
} else { } else {
sizeText = _captureRect.Width + " x " + _captureRect.Height; sizeText = _captureRect.Width + " x " + _captureRect.Height;
} }
@ -806,7 +797,7 @@ namespace Greenshot.Forms {
SizeF extent = graphics.MeasureString( sizeText, sizeFont ); SizeF extent = graphics.MeasureString( sizeText, sizeFont );
float hRatio = _captureRect.Height / (extent.Height * 2); float hRatio = _captureRect.Height / (extent.Height * 2);
float wRatio = _captureRect.Width / (extent.Width * 2); float wRatio = _captureRect.Width / (extent.Width * 2);
float ratio = ( hRatio < wRatio ? hRatio : wRatio ); float ratio = hRatio < wRatio ? hRatio : wRatio;
float newSize = sizeFont.Size * ratio; float newSize = sizeFont.Size * ratio;
if ( newSize >= 4 ) { if ( newSize >= 4 ) {
@ -816,13 +807,20 @@ namespace Greenshot.Forms {
} }
// Draw the size. // Draw the size.
using (Font newSizeFont = new Font(FontFamily.GenericSansSerif, newSize, FontStyle.Bold)) { 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)); PointF sizeLocation = new PointF(fixedRect.X + _captureRect.Width / 2 - extent.Width / 2, fixedRect.Y + _captureRect.Height / 2 - newSizeFont.GetHeight() / 2);
graphics.DrawString(sizeText, newSizeFont, Brushes.LightSeaGreen, sizeLocation); 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);
graphics.DrawString(title, sizeFont, Brushes.DarkOrange, debugLocation);
}
} }
} }
} }
} else { } else {
if (!isTerminalServerSession) { if (!IsTerminalServerSession) {
using (Pen pen = new Pen(Color.LightSeaGreen)) { using (Pen pen = new Pen(Color.LightSeaGreen)) {
pen.DashStyle = DashStyle.Dot; pen.DashStyle = DashStyle.Dot;
Rectangle screenBounds = _capture.ScreenBounds; Rectangle screenBounds = _capture.ScreenBounds;
@ -848,11 +846,11 @@ namespace Greenshot.Forms {
} }
// Zoom // Zoom
if (_zoomAnimator != null && (isAnimating(_zoomAnimator) || _captureMode != CaptureMode.Window)) { if (_zoomAnimator != null && (IsAnimating(_zoomAnimator) || _captureMode != CaptureMode.Window)) {
const int zoomSourceWidth = 25; const int zoomSourceWidth = 25;
const int zoomSourceHeight = 25; const int zoomSourceHeight = 25;
Rectangle sourceRectangle = new Rectangle(_cursorPos.X - (zoomSourceWidth / 2), _cursorPos.Y - (zoomSourceHeight / 2), zoomSourceWidth, zoomSourceHeight); Rectangle sourceRectangle = new Rectangle(_cursorPos.X - zoomSourceWidth / 2, _cursorPos.Y - zoomSourceHeight / 2, zoomSourceWidth, zoomSourceHeight);
Rectangle destinationRectangle = _zoomAnimator.Current; Rectangle destinationRectangle = _zoomAnimator.Current;
destinationRectangle.Offset(_cursorPos); destinationRectangle.Offset(_cursorPos);

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -144,7 +144,7 @@ namespace Greenshot {
this.textBoxRed.TabIndex = 2; this.textBoxRed.TabIndex = 2;
this.textBoxRed.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.textBoxRed.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.textBoxRed.Click += new System.EventHandler(this.TextBoxGotFocus); this.textBoxRed.Click += new System.EventHandler(this.TextBoxGotFocus);
this.textBoxRed.TextChanged += new System.EventHandler(this.TextBoxRGBTextChanged); this.textBoxRed.TextChanged += new System.EventHandler(this.TextBoxRgbTextChanged);
this.textBoxRed.GotFocus += new System.EventHandler(this.TextBoxGotFocus); this.textBoxRed.GotFocus += new System.EventHandler(this.TextBoxGotFocus);
this.textBoxRed.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown); this.textBoxRed.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown);
// //
@ -156,7 +156,7 @@ namespace Greenshot {
this.textBoxGreen.TabIndex = 3; this.textBoxGreen.TabIndex = 3;
this.textBoxGreen.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.textBoxGreen.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.textBoxGreen.Click += new System.EventHandler(this.TextBoxGotFocus); this.textBoxGreen.Click += new System.EventHandler(this.TextBoxGotFocus);
this.textBoxGreen.TextChanged += new System.EventHandler(this.TextBoxRGBTextChanged); this.textBoxGreen.TextChanged += new System.EventHandler(this.TextBoxRgbTextChanged);
this.textBoxGreen.GotFocus += new System.EventHandler(this.TextBoxGotFocus); this.textBoxGreen.GotFocus += new System.EventHandler(this.TextBoxGotFocus);
this.textBoxGreen.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown); this.textBoxGreen.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown);
// //
@ -168,7 +168,7 @@ namespace Greenshot {
this.textBoxBlue.TabIndex = 4; this.textBoxBlue.TabIndex = 4;
this.textBoxBlue.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.textBoxBlue.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.textBoxBlue.Click += new System.EventHandler(this.TextBoxGotFocus); this.textBoxBlue.Click += new System.EventHandler(this.TextBoxGotFocus);
this.textBoxBlue.TextChanged += new System.EventHandler(this.TextBoxRGBTextChanged); this.textBoxBlue.TextChanged += new System.EventHandler(this.TextBoxRgbTextChanged);
this.textBoxBlue.GotFocus += new System.EventHandler(this.TextBoxGotFocus); this.textBoxBlue.GotFocus += new System.EventHandler(this.TextBoxGotFocus);
this.textBoxBlue.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown); this.textBoxBlue.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown);
// //
@ -189,7 +189,7 @@ namespace Greenshot {
this.textBoxAlpha.TabIndex = 5; this.textBoxAlpha.TabIndex = 5;
this.textBoxAlpha.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.textBoxAlpha.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.textBoxAlpha.Click += new System.EventHandler(this.TextBoxGotFocus); this.textBoxAlpha.Click += new System.EventHandler(this.TextBoxGotFocus);
this.textBoxAlpha.TextChanged += new System.EventHandler(this.TextBoxRGBTextChanged); this.textBoxAlpha.TextChanged += new System.EventHandler(this.TextBoxRgbTextChanged);
this.textBoxAlpha.GotFocus += new System.EventHandler(this.TextBoxGotFocus); this.textBoxAlpha.GotFocus += new System.EventHandler(this.TextBoxGotFocus);
this.textBoxAlpha.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown); this.textBoxAlpha.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown);
// //

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -34,8 +34,8 @@ namespace Greenshot {
/// Description of ColorDialog. /// Description of ColorDialog.
/// </summary> /// </summary>
public partial class ColorDialog : BaseForm { public partial class ColorDialog : BaseForm {
private static ColorDialog uniqueInstance; private static ColorDialog _uniqueInstance;
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>(); private static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>();
private ColorDialog() { private ColorDialog() {
SuspendLayout(); SuspendLayout();
@ -47,17 +47,15 @@ namespace Greenshot {
UpdateRecentColorsButtonRow(); UpdateRecentColorsButtonRow();
} }
public static ColorDialog GetInstance() { public static ColorDialog GetInstance()
if (uniqueInstance == null) { {
uniqueInstance = new ColorDialog(); return _uniqueInstance ?? (_uniqueInstance = new ColorDialog());
}
return uniqueInstance;
} }
private readonly List<Button> _colorButtons = new List<Button>(); private readonly List<Button> _colorButtons = new List<Button>();
private readonly List<Button> _recentColorButtons = new List<Button>(); private readonly List<Button> _recentColorButtons = new List<Button>();
private readonly ToolTip _toolTip = new ToolTip(); private readonly ToolTip _toolTip = new ToolTip();
private bool _updateInProgress = false; private bool _updateInProgress;
public Color Color { public Color Color {
get { return colorPanel.BackColor; } get { return colorPanel.BackColor; }
@ -108,13 +106,15 @@ namespace Greenshot {
} }
private Button CreateColorButton(Color color, int x, int y, int w, int h) { private Button CreateColorButton(Color color, int x, int y, int w, int h) {
Button b = new Button(); Button b = new Button
b.BackColor = color; {
BackColor = color,
FlatStyle = FlatStyle.Flat,
Location = new Point(x, y),
Size = new Size(w, h),
TabStop = false
};
b.FlatAppearance.BorderSize = 0; b.FlatAppearance.BorderSize = 0;
b.FlatStyle = FlatStyle.Flat;
b.Location = new Point(x, y);
b.Size = new Size(w, h);
b.TabStop = false;
b.Click += ColorButtonClick; b.Click += ColorButtonClick;
_toolTip.SetToolTip(b, ColorTranslator.ToHtml(color) + " | R:" + color.R + ", G:" + color.G + ", B:" + color.B); _toolTip.SetToolTip(b, ColorTranslator.ToHtml(color) + " | R:" + color.R + ", G:" + color.G + ", B:" + color.B);
return b; return b;
@ -133,8 +133,8 @@ namespace Greenshot {
#region update user interface #region update user interface
private void UpdateRecentColorsButtonRow() { private void UpdateRecentColorsButtonRow() {
for (int i = 0; i < editorConfiguration.RecentColors.Count && i < 12; i++) { for (int i = 0; i < EditorConfig.RecentColors.Count && i < 12; i++) {
_recentColorButtons[i].BackColor = editorConfiguration.RecentColors[i]; _recentColorButtons[i].BackColor = EditorConfig.RecentColors[i];
_recentColorButtons[i].Enabled = true; _recentColorButtons[i].Enabled = true;
} }
} }
@ -155,30 +155,31 @@ namespace Greenshot {
} }
private void AddToRecentColors(Color c) { private void AddToRecentColors(Color c) {
editorConfiguration.RecentColors.Remove(c); EditorConfig.RecentColors.Remove(c);
editorConfiguration.RecentColors.Insert(0, c); EditorConfig.RecentColors.Insert(0, c);
if (editorConfiguration.RecentColors.Count > 12) { if (EditorConfig.RecentColors.Count > 12) {
editorConfiguration.RecentColors.RemoveRange(12, editorConfiguration.RecentColors.Count - 12); EditorConfig.RecentColors.RemoveRange(12, EditorConfig.RecentColors.Count - 12);
} }
UpdateRecentColorsButtonRow(); UpdateRecentColorsButtonRow();
} }
#endregion #endregion
#region textbox event handlers #region textbox event handlers
void TextBoxHexadecimalTextChanged(object sender, EventArgs e) {
private void TextBoxHexadecimalTextChanged(object sender, EventArgs e) {
if (_updateInProgress) { if (_updateInProgress) {
return; return;
} }
TextBox textBox = (TextBox)sender; TextBox textBox = (TextBox)sender;
string text = textBox.Text.Replace("#", ""); string text = textBox.Text.Replace("#", "");
int i = 0; int i;
Color c; Color c;
if (Int32.TryParse(text, NumberStyles.AllowHexSpecifier, Thread.CurrentThread.CurrentCulture, out i)) { if (int.TryParse(text, NumberStyles.AllowHexSpecifier, Thread.CurrentThread.CurrentCulture, out i)) {
c = Color.FromArgb(i); c = Color.FromArgb(i);
} else { } else {
KnownColor knownColor; try
try { {
knownColor = (KnownColor)Enum.Parse(typeof(KnownColor), text, true); var knownColor = (KnownColor)Enum.Parse(typeof(KnownColor), text, true);
c = Color.FromKnownColor(knownColor); c = Color.FromKnownColor(knownColor);
} catch (Exception) { } catch (Exception) {
return; return;
@ -188,7 +189,7 @@ namespace Greenshot {
PreviewColor(opaqueColor, textBox); PreviewColor(opaqueColor, textBox);
} }
void TextBoxRGBTextChanged(object sender, EventArgs e) { private void TextBoxRgbTextChanged(object sender, EventArgs e) {
if (_updateInProgress) { if (_updateInProgress) {
return; return;
} }
@ -196,11 +197,11 @@ namespace Greenshot {
PreviewColor(Color.FromArgb(GetColorPartIntFromString(textBoxAlpha.Text), GetColorPartIntFromString(textBoxRed.Text), GetColorPartIntFromString(textBoxGreen.Text), GetColorPartIntFromString(textBoxBlue.Text)), textBox); PreviewColor(Color.FromArgb(GetColorPartIntFromString(textBoxAlpha.Text), GetColorPartIntFromString(textBoxRed.Text), GetColorPartIntFromString(textBoxGreen.Text), GetColorPartIntFromString(textBoxBlue.Text)), textBox);
} }
void TextBoxGotFocus(object sender, EventArgs e) { private void TextBoxGotFocus(object sender, EventArgs e) {
textBoxHtmlColor.SelectAll(); textBoxHtmlColor.SelectAll();
} }
void TextBoxKeyDown(object sender, KeyEventArgs e) { private void TextBoxKeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter) { if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter) {
AddToRecentColors(colorPanel.BackColor); AddToRecentColors(colorPanel.BackColor);
} }
@ -208,15 +209,17 @@ namespace Greenshot {
#endregion #endregion
#region button event handlers #region button event handlers
void ColorButtonClick(object sender, EventArgs e) {
private void ColorButtonClick(object sender, EventArgs e) {
Button b = (Button)sender; Button b = (Button)sender;
PreviewColor(b.BackColor, b); PreviewColor(b.BackColor, b);
} }
void BtnTransparentClick(object sender, EventArgs e) { private void BtnTransparentClick(object sender, EventArgs e) {
ColorButtonClick(sender, e); ColorButtonClick(sender, e);
} }
void BtnApplyClick(object sender, EventArgs e) {
private void BtnApplyClick(object sender, EventArgs e) {
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
Hide(); Hide();
AddToRecentColors(colorPanel.BackColor); AddToRecentColors(colorPanel.BackColor);
@ -225,17 +228,23 @@ namespace Greenshot {
#region helper functions #region helper functions
private int GetColorPartIntFromString(string s) { private int GetColorPartIntFromString(string s) {
int ret = 0; int ret;
Int32.TryParse(s, out ret); int.TryParse(s, out ret);
if (ret < 0) ret = 0; if (ret < 0)
else if (ret > 255) ret = 255; {
ret = 0;
}
else if (ret > 255)
{
ret = 255;
}
return ret; return ret;
} }
#endregion #endregion
private void PipetteUsed(object sender, PipetteUsedArgs e) { private void PipetteUsed(object sender, PipetteUsedArgs e) {
Color = e.color; Color = e.Color;
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,15 +21,14 @@
using System; using System;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.Core; using GreenshotPlugin.Effects;
using GreenshotPlugin.Core;
namespace Greenshot.Forms { namespace Greenshot.Forms {
public partial class DropShadowSettingsForm : BaseForm { public partial class DropShadowSettingsForm : BaseForm {
private DropShadowEffect effect; private readonly DropShadowEffect _effect;
public DropShadowSettingsForm(DropShadowEffect effect) { public DropShadowSettingsForm(DropShadowEffect effect) {
this.effect = effect; _effect = effect;
InitializeComponent(); InitializeComponent();
ShowSettings(); ShowSettings();
} }
@ -38,22 +37,17 @@ namespace Greenshot.Forms {
/// Apply the settings from the effect to the view /// Apply the settings from the effect to the view
/// </summary> /// </summary>
private void ShowSettings() { private void ShowSettings() {
trackBar1.Value = (int)(effect.Darkness * 40); trackBar1.Value = (int)(_effect.Darkness * 40);
offsetX.Value = effect.ShadowOffset.X; offsetX.Value = _effect.ShadowOffset.X;
offsetY.Value = effect.ShadowOffset.Y; offsetY.Value = _effect.ShadowOffset.Y;
thickness.Value = effect.ShadowSize; thickness.Value = _effect.ShadowSize;
} }
private void ButtonOK_Click(object sender, EventArgs e) { private void ButtonOK_Click(object sender, EventArgs e) {
effect.Darkness = (float)trackBar1.Value / (float)40; _effect.Darkness = trackBar1.Value / (float)40;
effect.ShadowOffset = new Point((int)offsetX.Value, (int)offsetY.Value); _effect.ShadowOffset = new Point((int)offsetX.Value, (int)offsetY.Value);
effect.ShadowSize = (int)thickness.Value; _effect.ShadowSize = (int)thickness.Value;
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
} }
private void ButtonReset_Click(object sender, EventArgs e) {
effect.Reset();
ShowSettings();
}
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -152,6 +152,8 @@ namespace Greenshot {
this.btnLineColor = new Greenshot.Controls.ToolStripColorButton(); this.btnLineColor = new Greenshot.Controls.ToolStripColorButton();
this.lineThicknessLabel = new GreenshotPlugin.Controls.GreenshotToolStripLabel(); this.lineThicknessLabel = new GreenshotPlugin.Controls.GreenshotToolStripLabel();
this.lineThicknessUpDown = new Greenshot.Controls.ToolStripNumericUpDown(); this.lineThicknessUpDown = new Greenshot.Controls.ToolStripNumericUpDown();
this.counterLabel = new GreenshotPlugin.Controls.GreenshotToolStripLabel();
this.counterUpDown = new Greenshot.Controls.ToolStripNumericUpDown();
this.fontFamilyComboBox = new Greenshot.Controls.FontFamilyComboBox(); this.fontFamilyComboBox = new Greenshot.Controls.FontFamilyComboBox();
this.fontSizeLabel = new GreenshotPlugin.Controls.GreenshotToolStripLabel(); this.fontSizeLabel = new GreenshotPlugin.Controls.GreenshotToolStripLabel();
this.fontSizeUpDown = new Greenshot.Controls.ToolStripNumericUpDown(); this.fontSizeUpDown = new Greenshot.Controls.ToolStripNumericUpDown();
@ -464,13 +466,13 @@ namespace Greenshot {
// //
this.addDropshadowToolStripMenuItem.LanguageKey = "editor_image_shadow"; this.addDropshadowToolStripMenuItem.LanguageKey = "editor_image_shadow";
this.addDropshadowToolStripMenuItem.Name = "addDropshadowToolStripMenuItem"; this.addDropshadowToolStripMenuItem.Name = "addDropshadowToolStripMenuItem";
this.addDropshadowToolStripMenuItem.Click += new System.EventHandler(this.AddDropshadowToolStripMenuItemClick); this.addDropshadowToolStripMenuItem.MouseUp += AddDropshadowToolStripMenuItemMouseUp;
// //
// tornEdgesToolStripMenuItem // tornEdgesToolStripMenuItem
// //
this.tornEdgesToolStripMenuItem.LanguageKey = "editor_torn_edge"; this.tornEdgesToolStripMenuItem.LanguageKey = "editor_torn_edge";
this.tornEdgesToolStripMenuItem.Name = "tornEdgesToolStripMenuItem"; this.tornEdgesToolStripMenuItem.Name = "tornEdgesToolStripMenuItem";
this.tornEdgesToolStripMenuItem.Click += new System.EventHandler(this.TornEdgesToolStripMenuItemClick); this.tornEdgesToolStripMenuItem.MouseUp += TornEdgesToolStripMenuItemMouseUp;
// //
// grayscaleToolStripMenuItem // grayscaleToolStripMenuItem
// //
@ -1022,7 +1024,7 @@ namespace Greenshot {
this.propertiesToolStrip.Renderer = new CustomToolStripProfessionalRenderer(); this.propertiesToolStrip.Renderer = new CustomToolStripProfessionalRenderer();
this.propertiesToolStrip.BackColor = System.Drawing.SystemColors.Control; this.propertiesToolStrip.BackColor = System.Drawing.SystemColors.Control;
this.propertiesToolStrip.OverflowButton.DropDown.BackColor = System.Drawing.SystemColors.Control; this.propertiesToolStrip.OverflowButton.DropDown.BackColor = System.Drawing.SystemColors.Control;
this.propertiesToolStrip.Paint += propertiesToolStrip_Paint; this.propertiesToolStrip.Paint += PropertiesToolStrip_Paint;
this.propertiesToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.propertiesToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.obfuscateModeButton, this.obfuscateModeButton,
this.highlightModeButton, this.highlightModeButton,
@ -1053,7 +1055,9 @@ namespace Greenshot {
this.toolStripSeparator, this.toolStripSeparator,
this.toolStripSeparator10, this.toolStripSeparator10,
this.btnConfirm, this.btnConfirm,
this.btnCancel}); this.btnCancel,
this.counterLabel,
this.counterUpDown});
// //
// obfuscateModeButton // obfuscateModeButton
// //
@ -1143,6 +1147,23 @@ namespace Greenshot {
this.btnLineColor.Name = "btnLineColor"; this.btnLineColor.Name = "btnLineColor";
this.btnLineColor.SelectedColor = System.Drawing.Color.FromArgb(((int)(((byte)(203)))), ((int)(((byte)(222)))), ((int)(((byte)(250))))); this.btnLineColor.SelectedColor = System.Drawing.Color.FromArgb(((int)(((byte)(203)))), ((int)(((byte)(222)))), ((int)(((byte)(250)))));
// //
// counterLabel
//
this.counterLabel.LanguageKey = "editor_counter_startvalue";
this.counterLabel.Name = "counterLabel";
//
// counterUpDown
//
this.counterUpDown.DecimalPlaces = 0;
this.counterUpDown.Increment = 1;
this.counterUpDown.Maximum = 100;
this.counterUpDown.Minimum = 0;
this.counterUpDown.Name = "counterUpDown";
this.counterUpDown.Text = "1";
this.counterUpDown.Value = 1;
this.counterUpDown.GotFocus += new System.EventHandler(this.ToolBarFocusableElementGotFocus);
this.counterUpDown.LostFocus += new System.EventHandler(this.ToolBarFocusableElementLostFocus);
//
// lineThicknessLabel // lineThicknessLabel
// //
this.lineThicknessLabel.LanguageKey = "editor_thickness"; this.lineThicknessLabel.LanguageKey = "editor_thickness";
@ -1691,6 +1712,8 @@ namespace Greenshot {
private Greenshot.Controls.ToolStripEx propertiesToolStrip; private Greenshot.Controls.ToolStripEx propertiesToolStrip;
private GreenshotPlugin.Controls.GreenshotToolStripLabel lineThicknessLabel; private GreenshotPlugin.Controls.GreenshotToolStripLabel lineThicknessLabel;
private Greenshot.Controls.ToolStripNumericUpDown lineThicknessUpDown; private Greenshot.Controls.ToolStripNumericUpDown lineThicknessUpDown;
private GreenshotPlugin.Controls.GreenshotToolStripLabel counterLabel;
private Greenshot.Controls.ToolStripNumericUpDown counterUpDown;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator14; private System.Windows.Forms.ToolStripSeparator toolStripSeparator14;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator15; private System.Windows.Forms.ToolStripSeparator toolStripSeparator15;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator16; private System.Windows.Forms.ToolStripSeparator toolStripSeparator16;

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -29,9 +29,9 @@ namespace Greenshot.Forms {
/// Description of LanguageDialog. /// Description of LanguageDialog.
/// </summary> /// </summary>
public partial class LanguageDialog : Form { public partial class LanguageDialog : Form {
private static ILog LOG = LogManager.GetLogger(typeof(LanguageDialog)); private static readonly ILog LOG = LogManager.GetLogger(typeof(LanguageDialog));
private static LanguageDialog uniqueInstance; private static LanguageDialog uniqueInstance;
private bool properOkPressed = false; private bool properOkPressed;
private LanguageDialog() { private LanguageDialog() {
// //
@ -79,7 +79,7 @@ namespace Greenshot.Forms {
} }
} }
void BtnOKClick(object sender, EventArgs e) { private void BtnOKClick(object sender, EventArgs e) {
properOkPressed = true; properOkPressed = true;
// Fix for Bug #3431100 // Fix for Bug #3431100
Language.CurrentLanguage = SelectedLanguage; Language.CurrentLanguage = SelectedLanguage;

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -162,7 +162,7 @@ namespace Greenshot {
// //
this.contextmenu_captureiefromlist.Name = "contextmenu_captureiefromlist"; this.contextmenu_captureiefromlist.Name = "contextmenu_captureiefromlist";
this.contextmenu_captureiefromlist.Size = new System.Drawing.Size(170, 22); this.contextmenu_captureiefromlist.Size = new System.Drawing.Size(170, 22);
this.contextmenu_captureiefromlist.DropDownOpening += new System.EventHandler(this.CaptureIEMenuDropDownOpening); this.contextmenu_captureiefromlist.DropDownOpening += new System.EventHandler(this.CaptureIeMenuDropDownOpening);
// //
// toolStripOtherSourcesSeparator // toolStripOtherSourcesSeparator
// //

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -25,9 +25,8 @@ using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Linq;
using System.Reflection; using System.Reflection;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
@ -43,6 +42,7 @@ using GreenshotPlugin.Controls;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.IniFile; using Greenshot.IniFile;
using Greenshot.Destinations; using Greenshot.Destinations;
using Greenshot.Drawing;
using log4net; using log4net;
using Timer = System.Timers.Timer; using Timer = System.Timers.Timer;
@ -52,19 +52,18 @@ namespace Greenshot {
/// </summary> /// </summary>
public partial class MainForm : BaseForm { public partial class MainForm : BaseForm {
private static ILog LOG; private static ILog LOG;
private static Mutex _applicationMutex; private static ResourceMutex _applicationMutex;
private static CoreConfiguration _conf; private static CoreConfiguration _conf;
public static string LogFileLocation = null; public static string LogFileLocation;
public static void Start(string[] args) { public static void Start(string[] arguments) {
bool isAlreadyRunning = false; var filesToOpen = new List<string>();
List<string> filesToOpen = new List<string>();
// Set the Thread name, is better than "1" // Set the Thread name, is better than "1"
Thread.CurrentThread.Name = Application.ProductName; Thread.CurrentThread.Name = Application.ProductName;
// Init Log4NET // Init Log4NET
LogFileLocation = LogHelper.InitializeLog4NET(); LogFileLocation = LogHelper.InitializeLog4Net();
// Get logger // Get logger
LOG = LogManager.GetLogger(typeof(MainForm)); LOG = LogManager.GetLogger(typeof(MainForm));
@ -82,49 +81,21 @@ namespace Greenshot {
try { try {
// Fix for Bug 2495900, Multi-user Environment // Fix for Bug 2495900, Multi-user Environment
// check whether there's an local instance running already // check whether there's an local instance running already
_applicationMutex = ResourceMutex.Create("F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", "Greenshot", false);
try { var isAlreadyRunning = !_applicationMutex.IsLocked;
// Added Mutex Security, hopefully this prevents the UnauthorizedAccessException more gracefully
// See an example in Bug #3131534
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
MutexSecurity mutexsecurity = new MutexSecurity();
mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));
bool created; if (arguments.Length > 0 && LOG.IsDebugEnabled) {
// 1) Create Mutex
_applicationMutex = new Mutex(false, @"Local\F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", out created, mutexsecurity);
// 2) Get the right to it, this returns false if it's already locked
if (!_applicationMutex.WaitOne(0, false)) {
LOG.Debug("Greenshot seems already to be running!");
isAlreadyRunning = true;
// Clean up
_applicationMutex.Close();
_applicationMutex = null;
}
} catch (AbandonedMutexException e) {
// Another Greenshot instance didn't cleanup correctly!
// we can ignore the exception, it happend on the "waitone" but still the mutex belongs to us
LOG.Warn("Greenshot didn't cleanup correctly!", e);
} catch (UnauthorizedAccessException e) {
LOG.Warn("Greenshot is most likely already running for a different user in the same session, can't create mutex due to error: ", e);
isAlreadyRunning = true;
} catch (Exception e) {
LOG.Warn("Problem obtaining the Mutex, assuming it was already taken!", e);
isAlreadyRunning = true;
}
if (args.Length > 0 && LOG.IsDebugEnabled) {
StringBuilder argumentString = new StringBuilder(); StringBuilder argumentString = new StringBuilder();
for(int argumentNr = 0; argumentNr < args.Length; argumentNr++) { foreach (string argument in arguments)
argumentString.Append("[").Append(args[argumentNr]).Append("] "); {
argumentString.Append("[").Append(argument).Append("] ");
} }
LOG.Debug("Greenshot arguments: " + argumentString); LOG.Debug("Greenshot arguments: " + argumentString);
} }
for(int argumentNr = 0; argumentNr < args.Length; argumentNr++) { for(int argumentNr = 0; argumentNr < arguments.Length; argumentNr++) {
string argument = args[argumentNr]; string argument = arguments[argumentNr];
// Help // Help
if (argument.ToLower().Equals("/help") || argument.ToLower().Equals("/h") || argument.ToLower().Equals("/?")) { if (argument.ToLower().Equals("/help") || argument.ToLower().Equals("/h") || argument.ToLower().Equals("/?")) {
// Try to attach to the console // Try to attach to the console
@ -133,7 +104,7 @@ namespace Greenshot {
if (!attachedToConsole) { if (!attachedToConsole) {
Kernel32.AllocConsole(); Kernel32.AllocConsole();
} }
StringBuilder helpOutput = new StringBuilder(); var helpOutput = new StringBuilder();
helpOutput.AppendLine(); helpOutput.AppendLine();
helpOutput.AppendLine("Greenshot commandline options:"); helpOutput.AppendLine("Greenshot commandline options:");
helpOutput.AppendLine(); helpOutput.AppendLine();
@ -202,14 +173,14 @@ namespace Greenshot {
// Language // Language
if (argument.ToLower().Equals("/language")) { if (argument.ToLower().Equals("/language")) {
_conf.Language = args[++argumentNr]; _conf.Language = arguments[++argumentNr];
IniConfig.Save(); IniConfig.Save();
continue; continue;
} }
// Setting the INI-directory // Setting the INI-directory
if (argument.ToLower().Equals("/inidirectory")) { if (argument.ToLower().Equals("/inidirectory")) {
IniConfig.IniDirectory = args[++argumentNr]; IniConfig.IniDirectory = arguments[++argumentNr];
continue; continue;
} }
@ -258,7 +229,7 @@ namespace Greenshot {
using (Form dummyForm = new Form()) { using (Form dummyForm = new Form()) {
dummyForm.Icon = GreenshotResources.getGreenshotIcon(); dummyForm.Icon = GreenshotResources.getGreenshotIcon();
dummyForm.ShowInTaskbar = true; dummyForm.ShowInTaskbar = true;
dummyForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; dummyForm.FormBorderStyle = FormBorderStyle.None;
dummyForm.Location = new Point(int.MinValue, int.MinValue); dummyForm.Location = new Point(int.MinValue, int.MinValue);
dummyForm.Load += delegate { dummyForm.Size = Size.Empty; }; dummyForm.Load += delegate { dummyForm.Size = Size.Empty; };
dummyForm.Show(); dummyForm.Show();
@ -316,7 +287,7 @@ namespace Greenshot {
// Remove the application mutex // Remove the application mutex
if (_applicationMutex != null) { if (_applicationMutex != null) {
try { try {
_applicationMutex.ReleaseMutex(); _applicationMutex.Dispose();
_applicationMutex = null; _applicationMutex = null;
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error("Error releasing Mutex!", ex); LOG.Error("Error releasing Mutex!", ex);
@ -325,11 +296,7 @@ namespace Greenshot {
} }
private static MainForm _instance; private static MainForm _instance;
public static MainForm Instance { public static MainForm Instance => _instance;
get {
return _instance;
}
}
private readonly CopyData _copyData; private readonly CopyData _copyData;
@ -342,15 +309,14 @@ namespace Greenshot {
// Timer for the double click test // Timer for the double click test
private readonly Timer _doubleClickTimer = new Timer(); private readonly Timer _doubleClickTimer = new Timer();
public NotifyIcon NotifyIcon { public NotifyIcon NotifyIcon => notifyIcon;
get {
return notifyIcon;
}
}
public MainForm(CopyDataTransport dataTransport) { public MainForm(CopyDataTransport dataTransport) {
_instance = this; _instance = this;
// Factory for surface objects
ImageHelper.SurfaceFactory = () => new Surface();
// //
// The InitializeComponent() call is required for Windows Forms designer support. // The InitializeComponent() call is required for Windows Forms designer support.
// //
@ -367,12 +333,12 @@ namespace Greenshot {
contextmenu_settings.Visible = !_conf.DisableSettings; contextmenu_settings.Visible = !_conf.DisableSettings;
// Make sure all hotkeys pass this window! // Make sure all hotkeys pass this window!
HotkeyControl.RegisterHotkeyHWND(Handle); HotkeyControl.RegisterHotkeyHwnd(Handle);
RegisterHotkeys(); RegisterHotkeys();
new ToolTip(); new ToolTip();
UpdateUI(); UpdateUi();
// This forces the registration of all destinations inside Greenshot itself. // This forces the registration of all destinations inside Greenshot itself.
DestinationHelper.GetAllDestinations(); DestinationHelper.GetAllDestinations();
@ -478,7 +444,7 @@ namespace Greenshot {
IniConfig.Reload(); IniConfig.Reload();
Invoke((MethodInvoker) delegate { Invoke((MethodInvoker) delegate {
// Even update language when needed // Even update language when needed
UpdateUI(); UpdateUi();
// Update the hotkey // Update the hotkey
// Make sure the current hotkeys are disabled // Make sure the current hotkeys are disabled
HotkeyControl.UnregisterHotkeys(); HotkeyControl.UnregisterHotkeys();
@ -506,9 +472,10 @@ namespace Greenshot {
} }
} }
public ContextMenuStrip MainMenu { /// <summary>
get {return contextMenu;} /// Main context menu
} /// </summary>
public ContextMenuStrip MainMenu => contextMenu;
protected override void WndProc(ref Message m) { protected override void WndProc(ref Message m) {
if (HotkeyControl.HandleMessages(ref m)) { if (HotkeyControl.HandleMessages(ref m)) {
@ -581,7 +548,7 @@ namespace Greenshot {
contextMenu.ImageScalingSize = coreConfiguration.IconSize; contextMenu.ImageScalingSize = coreConfiguration.IconSize;
string ieExePath = PluginUtils.GetExePath("iexplore.exe"); string ieExePath = PluginUtils.GetExePath("iexplore.exe");
if (!string.IsNullOrEmpty(ieExePath)) { if (!string.IsNullOrEmpty(ieExePath)) {
this.contextmenu_captureie.Image = PluginUtils.GetCachedExeIcon(ieExePath, 0); contextmenu_captureie.Image = PluginUtils.GetCachedExeIcon(ieExePath, 0);
} }
} }
} }
@ -637,6 +604,31 @@ namespace Greenshot {
return success || ignoreFailedRegistration; return success || ignoreFailedRegistration;
} }
/// <summary>
/// Check if OneDrive is blocking hotkeys
/// </summary>
/// <returns>true if onedrive has hotkeys turned on</returns>
private static bool IsOneDriveBlockingHotkey()
{
if (!Environment.OSVersion.IsWindows10())
{
return false;
}
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var oneDriveSettingsPath = Path.Combine(localAppData, @"Microsoft\OneDrive\settings\Personal");
if (!Directory.Exists(oneDriveSettingsPath))
{
return false;
}
var oneDriveSettingsFile = Directory.GetFiles(oneDriveSettingsPath, "*_screenshot.dat").FirstOrDefault();
if (!File.Exists(oneDriveSettingsFile))
{
return false;
}
var screenshotSetting = File.ReadAllLines(oneDriveSettingsFile).Skip(1).Take(1).First();
return "2".Equals(screenshotSetting);
}
/// <summary> /// <summary>
/// Displays a dialog for the user to choose how to handle hotkey registration failures: /// Displays a dialog for the user to choose how to handle hotkey registration failures:
/// retry (allowing to shut down the conflicting application before), /// retry (allowing to shut down the conflicting application before),
@ -647,7 +639,9 @@ namespace Greenshot {
/// <returns></returns> /// <returns></returns>
private static bool HandleFailedHotkeyRegistration(string failedKeys) { private static bool HandleFailedHotkeyRegistration(string failedKeys) {
bool success = false; bool success = false;
DialogResult dr = MessageBox.Show(Instance, Language.GetFormattedString(LangKey.warning_hotkeys, failedKeys), Language.GetString(LangKey.warning), MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation); var warningTitle = Language.GetString(LangKey.warning);
var message = string.Format(Language.GetString(LangKey.warning_hotkeys), failedKeys, IsOneDriveBlockingHotkey() ? " (OneDrive)": "");
DialogResult dr = MessageBox.Show(Instance, message, warningTitle, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation);
if (dr == DialogResult.Retry) { if (dr == DialogResult.Retry) {
LOG.DebugFormat("Re-trying to register hotkeys"); LOG.DebugFormat("Re-trying to register hotkeys");
HotkeyControl.UnregisterHotkeys(); HotkeyControl.UnregisterHotkeys();
@ -661,7 +655,7 @@ namespace Greenshot {
} }
#endregion #endregion
public void UpdateUI() { public void UpdateUi() {
// As the form is never loaded, call ApplyLanguage ourselves // As the form is never loaded, call ApplyLanguage ourselves
ApplyLanguage(); ApplyLanguage();
@ -675,26 +669,30 @@ namespace Greenshot {
#region mainform events #region mainform events
void MainFormFormClosing(object sender, FormClosingEventArgs e) {
private void MainFormFormClosing(object sender, FormClosingEventArgs e) {
LOG.DebugFormat("Mainform closing, reason: {0}", e.CloseReason); LOG.DebugFormat("Mainform closing, reason: {0}", e.CloseReason);
_instance = null; _instance = null;
Exit(); Exit();
} }
void MainFormActivated(object sender, EventArgs e) { private void MainFormActivated(object sender, EventArgs e) {
Hide(); Hide();
ShowInTaskbar = false; ShowInTaskbar = false;
} }
#endregion #endregion
#region key handlers #region key handlers
void CaptureRegion() {
private void CaptureRegion() {
CaptureHelper.CaptureRegion(true); CaptureHelper.CaptureRegion(true);
} }
void CaptureFile() { private void CaptureFile() {
var openFileDialog = new OpenFileDialog(); var openFileDialog = new OpenFileDialog
openFileDialog.Filter = "Image files (*.greenshot, *.png, *.jpg, *.gif, *.bmp, *.ico, *.tiff, *.wmf)|*.greenshot; *.png; *.jpg; *.jpeg; *.gif; *.bmp; *.ico; *.tiff; *.tif; *.wmf"; {
Filter = "Image files (*.greenshot, *.png, *.jpg, *.gif, *.bmp, *.ico, *.tiff, *.wmf)|*.greenshot; *.png; *.jpg; *.jpeg; *.gif; *.bmp; *.ico; *.tiff; *.tif; *.wmf"
};
if (openFileDialog.ShowDialog() == DialogResult.OK) { if (openFileDialog.ShowDialog() == DialogResult.OK) {
if (File.Exists(openFileDialog.FileName)) { if (File.Exists(openFileDialog.FileName)) {
CaptureHelper.CaptureFile(openFileDialog.FileName); CaptureHelper.CaptureFile(openFileDialog.FileName);
@ -702,21 +700,21 @@ namespace Greenshot {
} }
} }
void CaptureFullScreen() { private void CaptureFullScreen() {
CaptureHelper.CaptureFullscreen(true, _conf.ScreenCaptureMode); CaptureHelper.CaptureFullscreen(true, _conf.ScreenCaptureMode);
} }
void CaptureLastRegion() { private void CaptureLastRegion() {
CaptureHelper.CaptureLastRegion(true); CaptureHelper.CaptureLastRegion(true);
} }
void CaptureIE() { private void CaptureIE() {
if (_conf.IECapture) { if (_conf.IECapture) {
CaptureHelper.CaptureIE(true, null); CaptureHelper.CaptureIe(true, null);
} }
} }
void CaptureWindow() { private void CaptureWindow() {
if (_conf.CaptureWindowsInteractive) { if (_conf.CaptureWindowsInteractive) {
CaptureHelper.CaptureWindowInteractive(true); CaptureHelper.CaptureWindowInteractive(true);
} else { } else {
@ -727,13 +725,14 @@ namespace Greenshot {
#region contextmenu #region contextmenu
void ContextMenuOpening(object sender, CancelEventArgs e) {
private void ContextMenuOpening(object sender, CancelEventArgs e) {
contextmenu_captureclipboard.Enabled = ClipboardHelper.ContainsImage(); contextmenu_captureclipboard.Enabled = ClipboardHelper.ContainsImage();
contextmenu_capturelastregion.Enabled = coreConfiguration.LastCapturedRegion != Rectangle.Empty; contextmenu_capturelastregion.Enabled = coreConfiguration.LastCapturedRegion != Rectangle.Empty;
// IE context menu code // IE context menu code
try { try {
if (_conf.IECapture && IECaptureHelper.IsIERunning()) { if (_conf.IECapture && IeCaptureHelper.IsIeRunning()) {
contextmenu_captureie.Enabled = true; contextmenu_captureie.Enabled = true;
contextmenu_captureiefromlist.Enabled = true; contextmenu_captureiefromlist.Enabled = true;
} else { } else {
@ -763,7 +762,7 @@ namespace Greenshot {
} }
} }
void ContextMenuClosing(object sender, EventArgs e) { private void ContextMenuClosing(object sender, EventArgs e) {
contextmenu_captureiefromlist.DropDownItems.Clear(); contextmenu_captureiefromlist.DropDownItems.Clear();
contextmenu_capturewindowfromlist.DropDownItems.Clear(); contextmenu_capturewindowfromlist.DropDownItems.Clear();
CleanupThumbnail(); CleanupThumbnail();
@ -772,12 +771,12 @@ namespace Greenshot {
/// <summary> /// <summary>
/// Build a selectable list of IE tabs when we enter the menu item /// Build a selectable list of IE tabs when we enter the menu item
/// </summary> /// </summary>
void CaptureIEMenuDropDownOpening(object sender, EventArgs e) { private void CaptureIeMenuDropDownOpening(object sender, EventArgs e) {
if (!_conf.IECapture) { if (!_conf.IECapture) {
return; return;
} }
try { try {
List<KeyValuePair<WindowDetails, string>> tabs = IECaptureHelper.GetBrowserTabs(); List<KeyValuePair<WindowDetails, string>> tabs = IeCaptureHelper.GetBrowserTabs();
contextmenu_captureiefromlist.DropDownItems.Clear(); contextmenu_captureiefromlist.DropDownItems.Clear();
if (tabs.Count > 0) { if (tabs.Count > 0) {
contextmenu_captureie.Enabled = true; contextmenu_captureie.Enabled = true;
@ -792,12 +791,12 @@ namespace Greenshot {
if (title.Length > _conf.MaxMenuItemLength) { if (title.Length > _conf.MaxMenuItemLength) {
title = title.Substring(0, Math.Min(title.Length, _conf.MaxMenuItemLength)); title = title.Substring(0, Math.Min(title.Length, _conf.MaxMenuItemLength));
} }
ToolStripItem captureIETabItem = contextmenu_captureiefromlist.DropDownItems.Add(title); var captureIeTabItem = contextmenu_captureiefromlist.DropDownItems.Add(title);
int index = counter.ContainsKey(tabData.Key) ? counter[tabData.Key] : 0; int index = counter.ContainsKey(tabData.Key) ? counter[tabData.Key] : 0;
captureIETabItem.Image = tabData.Key.DisplayIcon; captureIeTabItem.Image = tabData.Key.DisplayIcon;
captureIETabItem.Tag = new KeyValuePair<WindowDetails, int>(tabData.Key, index++); captureIeTabItem.Tag = new KeyValuePair<WindowDetails, int>(tabData.Key, index++);
captureIETabItem.Click += Contextmenu_captureiefromlist_Click; captureIeTabItem.Click += Contextmenu_captureiefromlist_Click;
contextmenu_captureiefromlist.DropDownItems.Add(captureIETabItem); contextmenu_captureiefromlist.DropDownItems.Add(captureIeTabItem);
if (counter.ContainsKey(tabData.Key)) { if (counter.ContainsKey(tabData.Key)) {
counter[tabData.Key] = index; counter[tabData.Key] = index;
} else { } else {
@ -822,10 +821,9 @@ namespace Greenshot {
ToolStripMenuItem captureScreenMenuItem = (ToolStripMenuItem)sender; ToolStripMenuItem captureScreenMenuItem = (ToolStripMenuItem)sender;
captureScreenMenuItem.DropDownItems.Clear(); captureScreenMenuItem.DropDownItems.Clear();
if (Screen.AllScreens.Length > 1) { if (Screen.AllScreens.Length > 1) {
ToolStripMenuItem captureScreenItem;
Rectangle allScreensBounds = WindowCapture.GetScreenBounds(); Rectangle allScreensBounds = WindowCapture.GetScreenBounds();
captureScreenItem = new ToolStripMenuItem(Language.GetString(LangKey.contextmenu_capturefullscreen_all)); var captureScreenItem = new ToolStripMenuItem(Language.GetString(LangKey.contextmenu_capturefullscreen_all));
captureScreenItem.Click += delegate { captureScreenItem.Click += delegate {
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)delegate {
CaptureHelper.CaptureFullscreen(false, ScreenCaptureMode.FullScreen); CaptureHelper.CaptureFullscreen(false, ScreenCaptureMode.FullScreen);
@ -892,26 +890,26 @@ namespace Greenshot {
} }
} }
private void HideThumbnailOnLeave(object sender, EventArgs e) { private void HideThumbnailOnLeave(object sender, EventArgs e)
if (_thumbnailForm != null) { {
_thumbnailForm.Hide(); _thumbnailForm?.Hide();
}
} }
private void CleanupThumbnail() { private void CleanupThumbnail() {
if (_thumbnailForm != null) { if (_thumbnailForm == null)
{
return;
}
_thumbnailForm.Close(); _thumbnailForm.Close();
_thumbnailForm = null; _thumbnailForm = null;
} }
}
public void AddCaptureWindowMenuItems(ToolStripMenuItem menuItem, EventHandler eventHandler) { public void AddCaptureWindowMenuItems(ToolStripMenuItem menuItem, EventHandler eventHandler) {
menuItem.DropDownItems.Clear(); menuItem.DropDownItems.Clear();
// check if thumbnailPreview is enabled and DWM is enabled // check if thumbnailPreview is enabled and DWM is enabled
bool thumbnailPreview = _conf.ThumnailPreview && DWM.isDWMEnabled(); bool thumbnailPreview = _conf.ThumnailPreview && DWM.IsDwmEnabled();
List<WindowDetails> windows = WindowDetails.GetTopLevelWindows(); foreach(WindowDetails window in WindowDetails.GetTopLevelWindows()) {
foreach(WindowDetails window in windows) {
string title = window.Text; string title = window.Text;
if (title != null) { if (title != null) {
@ -931,43 +929,39 @@ namespace Greenshot {
} }
} }
void CaptureAreaToolStripMenuItemClick(object sender, EventArgs e) { private void CaptureAreaToolStripMenuItemClick(object sender, EventArgs e) {
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)delegate {
CaptureHelper.CaptureRegion(false); CaptureHelper.CaptureRegion(false);
}); });
} }
void CaptureClipboardToolStripMenuItemClick(object sender, EventArgs e) { private void CaptureClipboardToolStripMenuItemClick(object sender, EventArgs e) {
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)CaptureHelper.CaptureClipboard);
CaptureHelper.CaptureClipboard();
});
} }
void OpenFileToolStripMenuItemClick(object sender, EventArgs e) { private void OpenFileToolStripMenuItemClick(object sender, EventArgs e) {
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)CaptureFile);
CaptureFile();
});
} }
void CaptureFullScreenToolStripMenuItemClick(object sender, EventArgs e) { private void CaptureFullScreenToolStripMenuItemClick(object sender, EventArgs e) {
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)delegate {
CaptureHelper.CaptureFullscreen(false, _conf.ScreenCaptureMode); CaptureHelper.CaptureFullscreen(false, _conf.ScreenCaptureMode);
}); });
} }
void Contextmenu_capturelastregionClick(object sender, EventArgs e) { private void Contextmenu_capturelastregionClick(object sender, EventArgs e) {
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)delegate {
CaptureHelper.CaptureLastRegion(false); CaptureHelper.CaptureLastRegion(false);
}); });
} }
void Contextmenu_capturewindow_Click(object sender,EventArgs e) { private void Contextmenu_capturewindow_Click(object sender,EventArgs e) {
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)delegate {
CaptureHelper.CaptureWindowInteractive(false); CaptureHelper.CaptureWindowInteractive(false);
}); });
} }
void Contextmenu_capturewindowfromlist_Click(object sender,EventArgs e) { private void Contextmenu_capturewindowfromlist_Click(object sender,EventArgs e) {
ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender; ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)delegate {
try { try {
@ -979,11 +973,11 @@ namespace Greenshot {
}); });
} }
void Contextmenu_captureie_Click(object sender, EventArgs e) { private void Contextmenu_captureie_Click(object sender, EventArgs e) {
CaptureIE(); CaptureIE();
} }
void Contextmenu_captureiefromlist_Click(object sender, EventArgs e) { private void Contextmenu_captureiefromlist_Click(object sender, EventArgs e) {
if (!_conf.IECapture) { if (!_conf.IECapture) {
LOG.InfoFormat("IE Capture is disabled."); LOG.InfoFormat("IE Capture is disabled.");
return; return;
@ -996,12 +990,12 @@ namespace Greenshot {
ieWindowToCapture.Restore(); ieWindowToCapture.Restore();
} }
try { try {
IECaptureHelper.ActivateIETab(ieWindowToCapture, tabData.Value); IeCaptureHelper.ActivateIeTab(ieWindowToCapture, tabData.Value);
} catch (Exception exception) { } catch (Exception exception) {
LOG.Error(exception); LOG.Error(exception);
} }
try { try {
CaptureHelper.CaptureIE(false, ieWindowToCapture); CaptureHelper.CaptureIe(false, ieWindowToCapture);
} catch (Exception exception) { } catch (Exception exception) {
LOG.Error(exception); LOG.Error(exception);
} }
@ -1013,9 +1007,9 @@ namespace Greenshot {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void Contextmenu_donateClick(object sender, EventArgs e) { private void Contextmenu_donateClick(object sender, EventArgs e) {
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)delegate {
Process.Start("http://getgreenshot.org/support/"); Process.Start("http://getgreenshot.org/support/?version=" + Assembly.GetEntryAssembly().GetName().Version);
}); });
} }
@ -1024,10 +1018,8 @@ namespace Greenshot {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void Contextmenu_settingsClick(object sender, EventArgs e) { private void Contextmenu_settingsClick(object sender, EventArgs e) {
BeginInvoke((MethodInvoker)delegate { BeginInvoke((MethodInvoker)ShowSetting);
ShowSetting();
});
} }
/// <summary> /// <summary>
@ -1054,7 +1046,7 @@ namespace Greenshot {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void Contextmenu_aboutClick(object sender, EventArgs e) { private void Contextmenu_aboutClick(object sender, EventArgs e) {
ShowAbout(); ShowAbout();
} }
@ -1077,7 +1069,7 @@ namespace Greenshot {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void Contextmenu_helpClick(object sender, EventArgs e) { private void Contextmenu_helpClick(object sender, EventArgs e) {
HelpFileLoader.LoadHelp(); HelpFileLoader.LoadHelp();
} }
@ -1086,7 +1078,7 @@ namespace Greenshot {
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
void Contextmenu_exitClick(object sender, EventArgs e) { private void Contextmenu_exitClick(object sender, EventArgs e) {
Exit(); Exit();
} }
@ -1110,10 +1102,12 @@ namespace Greenshot {
// Only add if the value is not fixed // Only add if the value is not fixed
if (!_conf.Values["CaptureMousepointer"].IsFixed) { if (!_conf.Values["CaptureMousepointer"].IsFixed) {
// For the capture mousecursor option // For the capture mousecursor option
ToolStripMenuSelectListItem captureMouseItem = new ToolStripMenuSelectListItem(); ToolStripMenuSelectListItem captureMouseItem = new ToolStripMenuSelectListItem
captureMouseItem.Text = Language.GetString("settings_capture_mousepointer"); {
captureMouseItem.Checked = _conf.CaptureMousepointer; Text = Language.GetString("settings_capture_mousepointer"),
captureMouseItem.CheckOnClick = true; Checked = _conf.CaptureMousepointer,
CheckOnClick = true
};
captureMouseItem.CheckStateChanged += CheckStateChangedHandler; captureMouseItem.CheckStateChanged += CheckStateChangedHandler;
contextmenu_quicksettings.DropDownItems.Add(captureMouseItem); contextmenu_quicksettings.DropDownItems.Add(captureMouseItem);
@ -1121,10 +1115,12 @@ namespace Greenshot {
ToolStripMenuSelectList selectList; ToolStripMenuSelectList selectList;
if (!_conf.Values["Destinations"].IsFixed) { if (!_conf.Values["Destinations"].IsFixed) {
// screenshot destination // screenshot destination
selectList = new ToolStripMenuSelectList("destinations", true); selectList = new ToolStripMenuSelectList("destinations", true)
selectList.Text = Language.GetString(LangKey.settings_destination); {
Text = Language.GetString(LangKey.settings_destination)
};
// Working with IDestination: // Working with IDestination:
foreach (IDestination destination in DestinationHelper.GetAllDestinations()) { foreach (var destination in DestinationHelper.GetAllDestinations()) {
selectList.AddItem(destination.Description, destination, _conf.OutputDestinations.Contains(destination.Designation)); selectList.AddItem(destination.Description, destination, _conf.OutputDestinations.Contains(destination.Designation));
} }
selectList.CheckedChanged += QuickSettingDestinationChanged; selectList.CheckedChanged += QuickSettingDestinationChanged;
@ -1133,19 +1129,23 @@ namespace Greenshot {
if (!_conf.Values["WindowCaptureMode"].IsFixed) { if (!_conf.Values["WindowCaptureMode"].IsFixed) {
// Capture Modes // Capture Modes
selectList = new ToolStripMenuSelectList("capturemodes", false); selectList = new ToolStripMenuSelectList("capturemodes", false)
selectList.Text = Language.GetString(LangKey.settings_window_capture_mode); {
Text = Language.GetString(LangKey.settings_window_capture_mode)
};
string enumTypeName = typeof(WindowCaptureMode).Name; string enumTypeName = typeof(WindowCaptureMode).Name;
foreach (WindowCaptureMode captureMode in Enum.GetValues(typeof(WindowCaptureMode))) { foreach (WindowCaptureMode captureMode in Enum.GetValues(typeof(WindowCaptureMode))) {
selectList.AddItem(Language.GetString(enumTypeName + "." + captureMode.ToString()), captureMode, _conf.WindowCaptureMode == captureMode); selectList.AddItem(Language.GetString(enumTypeName + "." + captureMode), captureMode, _conf.WindowCaptureMode == captureMode);
} }
selectList.CheckedChanged += QuickSettingCaptureModeChanged; selectList.CheckedChanged += QuickSettingCaptureModeChanged;
contextmenu_quicksettings.DropDownItems.Add(selectList); contextmenu_quicksettings.DropDownItems.Add(selectList);
} }
// print options // print options
selectList = new ToolStripMenuSelectList("printoptions",true); selectList = new ToolStripMenuSelectList("printoptions", true)
selectList.Text = Language.GetString(LangKey.settings_printoptions); {
Text = Language.GetString(LangKey.settings_printoptions)
};
IniValue iniValue; IniValue iniValue;
foreach(string propertyName in _conf.Values.Keys) { foreach(string propertyName in _conf.Values.Keys) {
@ -1162,8 +1162,10 @@ namespace Greenshot {
} }
// effects // effects
selectList = new ToolStripMenuSelectList("effects",true); selectList = new ToolStripMenuSelectList("effects", true)
selectList.Text = Language.GetString(LangKey.settings_visualization); {
Text = Language.GetString(LangKey.settings_visualization)
};
iniValue = _conf.Values["PlayCameraSound"]; iniValue = _conf.Values["PlayCameraSound"];
if (!iniValue.IsFixed) { if (!iniValue.IsFixed) {
@ -1179,7 +1181,7 @@ namespace Greenshot {
} }
} }
void QuickSettingCaptureModeChanged(object sender, EventArgs e) { private void QuickSettingCaptureModeChanged(object sender, EventArgs e) {
ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item; ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item;
WindowCaptureMode windowsCaptureMode = (WindowCaptureMode)item.Data; WindowCaptureMode windowsCaptureMode = (WindowCaptureMode)item.Data;
if (item.Checked) { if (item.Checked) {
@ -1187,7 +1189,7 @@ namespace Greenshot {
} }
} }
void QuickSettingBoolItemChanged(object sender, EventArgs e) { private void QuickSettingBoolItemChanged(object sender, EventArgs e) {
ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item; ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item;
IniValue iniValue = item.Data as IniValue; IniValue iniValue = item.Data as IniValue;
if (iniValue != null) { if (iniValue != null) {
@ -1196,7 +1198,7 @@ namespace Greenshot {
} }
} }
void QuickSettingDestinationChanged(object sender, EventArgs e) { private void QuickSettingDestinationChanged(object sender, EventArgs e) {
ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item; ToolStripMenuSelectListItem item = ((ItemCheckedChangedEventArgs)e).Item;
IDestination selectedDestination = (IDestination)item.Data; IDestination selectedDestination = (IDestination)item.Data;
if (item.Checked) { if (item.Checked) {
@ -1305,8 +1307,8 @@ namespace Greenshot {
private void NotifyIconClick(ClickActions clickAction) { private void NotifyIconClick(ClickActions clickAction) {
switch (clickAction) { switch (clickAction) {
case ClickActions.OPEN_LAST_IN_EXPLORER: case ClickActions.OPEN_LAST_IN_EXPLORER:
string path = null; string path = _conf.OutputFileAsFullpath;
if (!string.IsNullOrEmpty(_conf.OutputFileAsFullpath)) { if (!File.Exists(path)) {
string lastFilePath = Path.GetDirectoryName(_conf.OutputFileAsFullpath); string lastFilePath = Path.GetDirectoryName(_conf.OutputFileAsFullpath);
if (!string.IsNullOrEmpty(lastFilePath) && Directory.Exists(lastFilePath)) { if (!string.IsNullOrEmpty(lastFilePath) && Directory.Exists(lastFilePath)) {
path = lastFilePath; path = lastFilePath;
@ -1321,7 +1323,22 @@ namespace Greenshot {
if (path != null) { if (path != null) {
try { try {
using (Process.Start(path)) {} // Check if path is a directory
if (Directory.Exists(path))
{
using (Process.Start(path))
{
}
}
// Check if path is a file
else if (File.Exists(path))
{
// Start the explorer process and select the file
using (var explorer = Process.Start("explorer.exe", $"/select,\"{path}\""))
{
explorer?.WaitForInputIdle(500);
}
}
} catch (Exception ex) { } catch (Exception ex) {
// Make sure we show what we tried to open in the exception // Make sure we show what we tried to open in the exception
ex.Data.Add("path", path); ex.Data.Add("path", path);
@ -1383,7 +1400,7 @@ namespace Greenshot {
// Close all open forms (except this), use a separate List to make sure we don't get a "InvalidOperationException: Collection was modified" // Close all open forms (except this), use a separate List to make sure we don't get a "InvalidOperationException: Collection was modified"
List<Form> formsToClose = new List<Form>(); List<Form> formsToClose = new List<Form>();
foreach(Form form in Application.OpenForms) { foreach(Form form in Application.OpenForms) {
if (form.Handle != Handle && !form.GetType().Equals(typeof(ImageEditorForm))) { if (form.Handle != Handle && form.GetType() != typeof(ImageEditorForm)) {
formsToClose.Add(form); formsToClose.Add(form);
} }
} }
@ -1459,9 +1476,11 @@ namespace Greenshot {
if (UpdateHelper.IsUpdateCheckNeeded()) { if (UpdateHelper.IsUpdateCheckNeeded()) {
LOG.Debug("BackgroundWorkerTimerTick checking for update"); LOG.Debug("BackgroundWorkerTimerTick checking for update");
// Start update check in the background // Start update check in the background
Thread backgroundTask = new Thread (UpdateHelper.CheckAndAskForUpdate); var backgroundTask = new Thread(UpdateHelper.CheckAndAskForUpdate)
backgroundTask.Name = "Update check"; {
backgroundTask.IsBackground = true; Name = "Update check",
IsBackground = true
};
backgroundTask.Start(); backgroundTask.Start();
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -85,8 +85,8 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
/// <param name="screenCoordinates">Point with the coordinates</param> /// <param name="screenCoordinates">Point with the coordinates</param>
/// <returns>Color at the specified screenCoordinates</returns> /// <returns>Color at the specified screenCoordinates</returns>
static private Color GetPixelColor(Point screenCoordinates) { private static Color GetPixelColor(Point screenCoordinates) {
using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.fromDesktop()) { using (SafeWindowDcHandle screenDC = SafeWindowDcHandle.FromDesktop()) {
try { try {
uint pixel = GDI32.GetPixel(screenDC, screenCoordinates.X, screenCoordinates.Y); uint pixel = GDI32.GetPixel(screenDC, 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);

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,7 +21,6 @@
using System; using System;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.IniFile; using Greenshot.IniFile;
using GreenshotPlugin.Core;
namespace Greenshot.Forms { namespace Greenshot.Forms {
/// <summary> /// <summary>
@ -37,7 +36,7 @@ namespace Greenshot.Forms {
} }
void Button_okClick(object sender, EventArgs e) { private void Button_okClick(object sender, EventArgs e) {
// update config // update config
coreConfiguration.OutputPrintPromptOptions = !checkbox_dontaskagain.Checked; coreConfiguration.OutputPrintPromptOptions = !checkbox_dontaskagain.Checked;
IniConfig.Save(); IniConfig.Save();

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,137 +21,130 @@
using System; using System;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.Core;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using GreenshotPlugin.Effects;
namespace Greenshot.Forms { namespace Greenshot.Forms {
/// <summary> /// <summary>
/// A form to set the resize settings /// A form to set the resize settings
/// </summary> /// </summary>
public partial class ResizeSettingsForm : BaseForm { public partial class ResizeSettingsForm : BaseForm {
private ResizeEffect effect; private readonly ResizeEffect _effect;
private string value_pixel; private readonly string _valuePercent;
private string value_percent; private double _newWidth, _newHeight;
private double newWidth, newHeight;
public ResizeSettingsForm(ResizeEffect effect) { public ResizeSettingsForm(ResizeEffect effect) {
this.effect = effect; _effect = effect;
InitializeComponent(); InitializeComponent();
value_pixel = Language.GetString("editor_resize_pixel"); var valuePixel = Language.GetString("editor_resize_pixel");
value_percent = Language.GetString("editor_resize_percent"); _valuePercent = Language.GetString("editor_resize_percent");
combobox_width.Items.Add(value_pixel); combobox_width.Items.Add(valuePixel);
combobox_width.Items.Add(value_percent); combobox_width.Items.Add(_valuePercent);
combobox_width.SelectedItem = value_pixel; combobox_width.SelectedItem = valuePixel;
combobox_height.Items.Add(value_pixel); combobox_height.Items.Add(valuePixel);
combobox_height.Items.Add(value_percent); combobox_height.Items.Add(_valuePercent);
combobox_height.SelectedItem = value_pixel; combobox_height.SelectedItem = valuePixel;
textbox_width.Text = effect.Width.ToString(); textbox_width.Text = effect.Width.ToString();
textbox_height.Text = effect.Height.ToString(); textbox_height.Text = effect.Height.ToString();
newWidth = effect.Width; _newWidth = effect.Width;
newHeight = effect.Height; _newHeight = effect.Height;
combobox_width.SelectedIndexChanged += new System.EventHandler(this.combobox_SelectedIndexChanged); combobox_width.SelectedIndexChanged += combobox_SelectedIndexChanged;
combobox_height.SelectedIndexChanged += new System.EventHandler(this.combobox_SelectedIndexChanged); combobox_height.SelectedIndexChanged += combobox_SelectedIndexChanged;
checkbox_aspectratio.Checked = effect.MaintainAspectRatio; checkbox_aspectratio.Checked = effect.MaintainAspectRatio;
} }
private void buttonOK_Click(object sender, EventArgs e) { private void buttonOK_Click(object sender, EventArgs e) {
if (newWidth != effect.Width || newHeight != effect.Height) { if (_newWidth != _effect.Width || _newHeight != _effect.Height) {
effect.Width = (int)newWidth; _effect.Width = (int)_newWidth;
effect.Height = (int)newHeight; _effect.Height = (int)_newHeight;
effect.MaintainAspectRatio = checkbox_aspectratio.Checked; _effect.MaintainAspectRatio = checkbox_aspectratio.Checked;
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
} }
} }
private bool validate(object sender) { private static bool Validate(object sender) {
TextBox textbox = sender as TextBox; TextBox textbox = sender as TextBox;
if (textbox != null) { if (textbox != null) {
double numberEntered; double numberEntered;
if (!double.TryParse(textbox.Text, out numberEntered)) { if (!double.TryParse(textbox.Text, out numberEntered)) {
textbox.BackColor = Color.Red; textbox.BackColor = Color.Red;
return false; return false;
} else {
textbox.BackColor = Color.White;
} }
textbox.BackColor = Color.White;
} }
return true; return true;
} }
private void displayWidth() { private void DisplayWidth() {
double displayValue; double displayValue;
if (value_percent.Equals(combobox_width.SelectedItem)) { if (_valuePercent.Equals(combobox_width.SelectedItem)) {
displayValue = ((double)newWidth / (double)effect.Width) * 100d; displayValue = _newWidth / _effect.Width * 100d;
} else { } else {
displayValue = newWidth; displayValue = _newWidth;
} }
textbox_width.Text = ((int)displayValue).ToString(); textbox_width.Text = ((int)displayValue).ToString();
} }
private void displayHeight() { private void DisplayHeight() {
double displayValue; double displayValue;
if (value_percent.Equals(combobox_height.SelectedItem)) { if (_valuePercent.Equals(combobox_height.SelectedItem)) {
displayValue = ((double)newHeight / (double)effect.Height) * 100d; displayValue = _newHeight / _effect.Height * 100d;
} else { } else {
displayValue = newHeight; displayValue = _newHeight;
} }
textbox_height.Text = ((int)displayValue).ToString(); textbox_height.Text = ((int)displayValue).ToString();
} }
private void textbox_KeyUp(object sender, KeyEventArgs e) { private void textbox_KeyUp(object sender, KeyEventArgs e) {
if (!validate(sender)) { if (!Validate(sender)) {
return; return;
} }
TextBox textbox = sender as TextBox; TextBox textbox = sender as TextBox;
if (textbox.Text.Length == 0) { if (string.IsNullOrEmpty(textbox?.Text)) {
return; return;
} }
bool isWidth = textbox == textbox_width; bool isWidth = textbox == textbox_width;
if (!checkbox_aspectratio.Checked) { if (!checkbox_aspectratio.Checked) {
if (isWidth) { if (isWidth) {
newWidth = double.Parse(textbox_width.Text); _newWidth = double.Parse(textbox_width.Text);
} else { } else {
newHeight = double.Parse(textbox_height.Text); _newHeight = double.Parse(textbox_height.Text);
} }
return; return;
} }
bool isPercent = false; var isPercent = _valuePercent.Equals(isWidth ? combobox_width.SelectedItem : combobox_height.SelectedItem);
if (isWidth) {
isPercent = value_percent.Equals(combobox_width.SelectedItem);
} else {
isPercent = value_percent.Equals(combobox_height.SelectedItem);
}
double percent; double percent;
if (isWidth) { if (isWidth) {
if (isPercent) { if (isPercent) {
percent = double.Parse(textbox_width.Text); percent = double.Parse(textbox_width.Text);
newWidth = ((double)effect.Width / 100d) * percent; _newWidth = _effect.Width / 100d * percent;
} else { } else {
newWidth = double.Parse(textbox_width.Text); _newWidth = double.Parse(textbox_width.Text);
percent = ((double)double.Parse(textbox_width.Text) / (double)effect.Width) * 100d; percent = double.Parse(textbox_width.Text) / _effect.Width * 100d;
} }
if (checkbox_aspectratio.Checked) { if (checkbox_aspectratio.Checked) {
newHeight = ((double)effect.Height / 100d) * percent; _newHeight = _effect.Height / 100d * percent;
displayHeight(); DisplayHeight();
} }
} else { } else {
if (isPercent) { if (isPercent) {
percent = double.Parse(textbox_height.Text); percent = double.Parse(textbox_height.Text);
newHeight = ((double)effect.Height / 100d) * percent; _newHeight = _effect.Height / 100d * percent;
} else { } else {
newHeight = double.Parse(textbox_height.Text); _newHeight = double.Parse(textbox_height.Text);
percent = ((double)double.Parse(textbox_height.Text) / (double)effect.Height) * 100d; percent = double.Parse(textbox_height.Text) / _effect.Height * 100d;
} }
if (checkbox_aspectratio.Checked) { if (checkbox_aspectratio.Checked) {
newWidth = ((double)effect.Width / 100d) * percent; _newWidth = _effect.Width / 100d * percent;
displayWidth(); DisplayWidth();
} }
} }
} }
private void textbox_Validating(object sender, System.ComponentModel.CancelEventArgs e) { private void textbox_Validating(object sender, System.ComponentModel.CancelEventArgs e) {
validate(sender); Validate(sender);
} }
/// <summary> /// <summary>
@ -160,11 +153,11 @@ namespace Greenshot.Forms {
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void combobox_SelectedIndexChanged(object sender, EventArgs e) { private void combobox_SelectedIndexChanged(object sender, EventArgs e) {
if (validate(textbox_width)) { if (Validate(textbox_width)) {
displayWidth(); DisplayWidth();
} }
if (validate(textbox_height)) { if (Validate(textbox_height)) {
displayHeight(); DisplayHeight();
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -506,6 +506,8 @@ namespace Greenshot {
this.numericUpDown_daysbetweencheck.Size = new System.Drawing.Size(57, 20); this.numericUpDown_daysbetweencheck.Size = new System.Drawing.Size(57, 20);
this.numericUpDown_daysbetweencheck.TabIndex = 8; this.numericUpDown_daysbetweencheck.TabIndex = 8;
this.numericUpDown_daysbetweencheck.ThousandsSeparator = true; this.numericUpDown_daysbetweencheck.ThousandsSeparator = true;
this.numericUpDown_daysbetweencheck.Minimum = 0;
this.numericUpDown_daysbetweencheck.Maximum = 365;
// //
// label_checkperiod // label_checkperiod
// //

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -43,10 +43,10 @@ namespace Greenshot {
/// Description of SettingsForm. /// Description of SettingsForm.
/// </summary> /// </summary>
public partial class SettingsForm : BaseForm { public partial class SettingsForm : BaseForm {
private static ILog LOG = LogManager.GetLogger(typeof(SettingsForm)); private static readonly ILog Log = LogManager.GetLogger(typeof(SettingsForm));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
private readonly ToolTip _toolTip = new ToolTip(); private readonly ToolTip _toolTip = new ToolTip();
private bool _inHotkey; private bool _inHotkey;
private int _daysbetweencheckPreviousValue;
public SettingsForm() { public SettingsForm() {
InitializeComponent(); InitializeComponent();
@ -59,11 +59,7 @@ namespace Greenshot {
base.OnLoad(e); base.OnLoad(e);
// Fix for Vista/XP differences // Fix for Vista/XP differences
if (Environment.OSVersion.Version.Major >= 6) { trackBarJpegQuality.BackColor = Environment.OSVersion.Version.Major >= 6 ? SystemColors.Window : SystemColors.Control;
trackBarJpegQuality.BackColor = SystemColors.Window;
} else {
trackBarJpegQuality.BackColor = SystemColors.Control;
}
// This makes it possible to still capture the settings screen // This makes it possible to still capture the settings screen
fullscreen_hotkeyControl.Enter += EnterHotkeyControl; fullscreen_hotkeyControl.Enter += EnterHotkeyControl;
@ -76,14 +72,49 @@ namespace Greenshot {
ie_hotkeyControl.Leave += LeaveHotkeyControl; ie_hotkeyControl.Leave += LeaveHotkeyControl;
lastregion_hotkeyControl.Enter += EnterHotkeyControl; lastregion_hotkeyControl.Enter += EnterHotkeyControl;
lastregion_hotkeyControl.Leave += LeaveHotkeyControl; lastregion_hotkeyControl.Leave += LeaveHotkeyControl;
// Changes for BUG-2077
numericUpDown_daysbetweencheck.ValueChanged += NumericUpDownDaysbetweencheckOnValueChanged;
_daysbetweencheckPreviousValue = (int) numericUpDown_daysbetweencheck.Value;
DisplayPluginTab(); DisplayPluginTab();
UpdateUI(); UpdateUi();
ExpertSettingsEnableState(false); ExpertSettingsEnableState(false);
DisplaySettings(); DisplaySettings();
CheckSettings(); CheckSettings();
} }
/// <summary>
/// This makes sure the check cannot be set to 1-6
/// </summary>
/// <param name="sender">object</param>
/// <param name="eventArgs">EventArgs</param>
private void NumericUpDownDaysbetweencheckOnValueChanged(object sender, EventArgs eventArgs)
{
int currentValue = (int)numericUpDown_daysbetweencheck.Value;
// 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;
}
}
if ((int)numericUpDown_daysbetweencheck.Value < 0)
{
numericUpDown_daysbetweencheck.Value = 0;
}
if ((int)numericUpDown_daysbetweencheck.Value > 365)
{
numericUpDown_daysbetweencheck.Value = 365;
}
_daysbetweencheckPreviousValue = (int)numericUpDown_daysbetweencheck.Value;
}
private void EnterHotkeyControl(object sender, EventArgs e) { private void EnterHotkeyControl(object sender, EventArgs e) {
HotkeyControl.UnregisterHotkeys(); HotkeyControl.UnregisterHotkeys();
_inHotkey = true; _inHotkey = true;
@ -114,10 +145,11 @@ namespace Greenshot {
/// with the items from the enumeration /// with the items from the enumeration
/// </summary> /// </summary>
/// <param name="comboBox">ComboBox to populate</param> /// <param name="comboBox">ComboBox to populate</param>
/// <param name="enumeration">Enum to populate with</param> /// <param name="availableValues"></param>
private void PopulateComboBox<ET>(ComboBox comboBox, ET[] availableValues, ET selectedValue) where ET : struct { /// <param name="selectedValue"></param>
private void PopulateComboBox<TEnum>(ComboBox comboBox, TEnum[] availableValues, TEnum selectedValue) where TEnum : struct {
comboBox.Items.Clear(); comboBox.Items.Clear();
foreach(ET enumValue in availableValues) { foreach(TEnum enumValue in availableValues) {
comboBox.Items.Add(Language.Translate(enumValue)); comboBox.Items.Add(Language.Translate(enumValue));
} }
comboBox.SelectedItem = Language.Translate(selectedValue); comboBox.SelectedItem = Language.Translate(selectedValue);
@ -129,13 +161,13 @@ namespace Greenshot {
/// </summary> /// </summary>
/// <param name="comboBox">Combobox to get the value from</param> /// <param name="comboBox">Combobox to get the value from</param>
/// <returns>The generics value of the combobox</returns> /// <returns>The generics value of the combobox</returns>
private ET GetSelected<ET>(ComboBox comboBox) { private TEnum GetSelected<TEnum>(ComboBox comboBox) {
string enumTypeName = typeof(ET).Name; string enumTypeName = typeof(TEnum).Name;
string selectedValue = comboBox.SelectedItem as string; string selectedValue = comboBox.SelectedItem as string;
ET[] availableValues = (ET[])Enum.GetValues(typeof(ET)); TEnum[] availableValues = (TEnum[])Enum.GetValues(typeof(TEnum));
ET returnValue = availableValues[0]; TEnum returnValue = availableValues[0];
foreach(ET enumValue in availableValues) { foreach(TEnum enumValue in availableValues) {
string translation = Language.GetString(enumTypeName + "." + enumValue.ToString()); string translation = Language.GetString(enumTypeName + "." + enumValue);
if (translation.Equals(selectedValue)) { if (translation.Equals(selectedValue)) {
returnValue = enumValue; returnValue = enumValue;
break; break;
@ -146,7 +178,7 @@ namespace Greenshot {
private void SetWindowCaptureMode(WindowCaptureMode selectedWindowCaptureMode) { private void SetWindowCaptureMode(WindowCaptureMode selectedWindowCaptureMode) {
WindowCaptureMode[] availableModes; WindowCaptureMode[] availableModes;
if (!DWM.isDWMEnabled()) { if (!DWM.IsDwmEnabled()) {
// Remove DWM from configuration, as DWM is disabled! // Remove DWM from configuration, as DWM is disabled!
if (coreConfiguration.WindowCaptureMode == WindowCaptureMode.Aero || coreConfiguration.WindowCaptureMode == WindowCaptureMode.AeroTransparent) { if (coreConfiguration.WindowCaptureMode == WindowCaptureMode.Aero || coreConfiguration.WindowCaptureMode == WindowCaptureMode.AeroTransparent) {
coreConfiguration.WindowCaptureMode = WindowCaptureMode.GDI; coreConfiguration.WindowCaptureMode = WindowCaptureMode.GDI;
@ -195,7 +227,7 @@ namespace Greenshot {
/// <summary> /// <summary>
/// Update the UI to reflect the language and other text settings /// Update the UI to reflect the language and other text settings
/// </summary> /// </summary>
private void UpdateUI() { private void UpdateUi() {
if (coreConfiguration.HideExpertSettings) { if (coreConfiguration.HideExpertSettings) {
tabcontrol.Controls.Remove(tab_expert); tabcontrol.Controls.Remove(tab_expert);
} }
@ -229,15 +261,14 @@ namespace Greenshot {
} }
private bool CheckFilenamePattern() { private bool CheckFilenamePattern() {
bool settingsOk = true;
string filename = FilenameHelper.GetFilenameFromPattern(textbox_screenshotname.Text, coreConfiguration.OutputFileFormat, null); string filename = FilenameHelper.GetFilenameFromPattern(textbox_screenshotname.Text, coreConfiguration.OutputFileFormat, null);
// we allow dynamically created subfolders, need to check for them, too // we allow dynamically created subfolders, need to check for them, too
string[] pathParts = filename.Split(Path.DirectorySeparatorChar); string[] pathParts = filename.Split(Path.DirectorySeparatorChar);
string filenamePart = pathParts[pathParts.Length-1]; string filenamePart = pathParts[pathParts.Length-1];
settingsOk = FilenameHelper.IsFilenameValid(filenamePart); var settingsOk = FilenameHelper.IsFilenameValid(filenamePart);
for (int i = 0; (settingsOk && i<pathParts.Length-1); i++) { for (int i = 0; settingsOk && i<pathParts.Length-1; i++) {
settingsOk = FilenameHelper.IsDirectoryNameValid(pathParts[i]); settingsOk = FilenameHelper.IsDirectoryNameValid(pathParts[i]);
} }
@ -247,10 +278,7 @@ namespace Greenshot {
} }
private bool CheckStorageLocationPath() { private bool CheckStorageLocationPath() {
bool settingsOk = true; bool settingsOk = Directory.Exists(FilenameHelper.FillVariables(textbox_storagelocation.Text, false));
if(!Directory.Exists(FilenameHelper.FillVariables(textbox_storagelocation.Text, false))) {
settingsOk = false;
}
DisplayTextBoxValidity(textbox_storagelocation, settingsOk); DisplayTextBoxValidity(textbox_storagelocation, settingsOk);
return settingsOk; return settingsOk;
} }
@ -258,11 +286,7 @@ namespace Greenshot {
private void DisplayTextBoxValidity(GreenshotTextBox textbox, bool valid) { private void DisplayTextBoxValidity(GreenshotTextBox textbox, bool valid) {
if (valid) { if (valid) {
// "Added" feature #3547158 // "Added" feature #3547158
if (Environment.OSVersion.Version.Major >= 6) { textbox.BackColor = Environment.OSVersion.Version.Major >= 6 ? SystemColors.Window : SystemColors.Control;
textbox.BackColor = SystemColors.Window;
} else {
textbox.BackColor = SystemColors.Control;
}
} else { } else {
textbox.BackColor = Color.Red; textbox.BackColor = Color.Red;
} }
@ -399,7 +423,7 @@ namespace Greenshot {
numericUpDown_daysbetweencheck.Value = coreConfiguration.UpdateCheckInterval; numericUpDown_daysbetweencheck.Value = coreConfiguration.UpdateCheckInterval;
numericUpDown_daysbetweencheck.Enabled = !coreConfiguration.Values["UpdateCheckInterval"].IsFixed; numericUpDown_daysbetweencheck.Enabled = !coreConfiguration.Values["UpdateCheckInterval"].IsFixed;
numericUpdownIconSize.Value = (coreConfiguration.IconSize.Width /16) * 16; numericUpdownIconSize.Value = coreConfiguration.IconSize.Width /16 * 16;
CheckDestinationSettings(); CheckDestinationSettings();
} }
@ -444,7 +468,6 @@ namespace Greenshot {
coreConfiguration.DWMBackgroundColor = colorButton_window_background.SelectedColor; coreConfiguration.DWMBackgroundColor = colorButton_window_background.SelectedColor;
coreConfiguration.UpdateCheckInterval = (int)numericUpDown_daysbetweencheck.Value; coreConfiguration.UpdateCheckInterval = (int)numericUpDown_daysbetweencheck.Value;
Size previousValue = coreConfiguration.IconSize;
coreConfiguration.IconSize = new Size((int)numericUpdownIconSize.Value, (int)numericUpdownIconSize.Value); coreConfiguration.IconSize = new Size((int)numericUpdownIconSize.Value, (int)numericUpdownIconSize.Value);
try { try {
@ -464,15 +487,15 @@ namespace Greenshot {
} }
} }
} catch (Exception e) { } catch (Exception e) {
LOG.Warn("Problem checking registry, ignoring for now: ", e); Log.Warn("Problem checking registry, ignoring for now: ", e);
} }
} }
void Settings_cancelClick(object sender, EventArgs e) { private void Settings_cancelClick(object sender, EventArgs e) {
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
} }
void Settings_okayClick(object sender, EventArgs e) { private void Settings_okayClick(object sender, EventArgs e) {
if (CheckSettings()) { if (CheckSettings()) {
HotkeyControl.UnregisterHotkeys(); HotkeyControl.UnregisterHotkeys();
SaveSettings(); SaveSettings();
@ -480,14 +503,14 @@ namespace Greenshot {
MainForm.RegisterHotkeys(); MainForm.RegisterHotkeys();
// Make sure the current language & settings are reflected in the Main-context menu // Make sure the current language & settings are reflected in the Main-context menu
MainForm.Instance.UpdateUI(); MainForm.Instance.UpdateUi();
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
} else { } else {
tabcontrol.SelectTab(tab_output); tabcontrol.SelectTab(tab_output);
} }
} }
void BrowseClick(object sender, EventArgs e) { private void BrowseClick(object sender, EventArgs e) {
// Get the storage location and replace the environment variables // Get the storage location and replace the environment variables
folderBrowserDialog1.SelectedPath = FilenameHelper.FillVariables(textbox_storagelocation.Text, false); folderBrowserDialog1.SelectedPath = FilenameHelper.FillVariables(textbox_storagelocation.Text, false);
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
@ -498,36 +521,36 @@ namespace Greenshot {
} }
} }
void TrackBarJpegQualityScroll(object sender, EventArgs e) { private void TrackBarJpegQualityScroll(object sender, EventArgs e) {
textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(CultureInfo.InvariantCulture); textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(CultureInfo.InvariantCulture);
} }
void BtnPatternHelpClick(object sender, EventArgs e) { private void BtnPatternHelpClick(object sender, EventArgs e) {
string filenamepatternText = Language.GetString(LangKey.settings_message_filenamepattern); string filenamepatternText = Language.GetString(LangKey.settings_message_filenamepattern);
// Convert %NUM% to ${NUM} for old language files! // 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)); MessageBox.Show(filenamepatternText, Language.GetString(LangKey.settings_filenamepattern));
} }
void Listview_pluginsSelectedIndexChanged(object sender, EventArgs e) { private void Listview_pluginsSelectedIndexChanged(object sender, EventArgs e) {
button_pluginconfigure.Enabled = PluginHelper.Instance.isSelectedItemConfigurable(listview_plugins); button_pluginconfigure.Enabled = PluginHelper.Instance.IsSelectedItemConfigurable(listview_plugins);
} }
void Button_pluginconfigureClick(object sender, EventArgs e) { private void Button_pluginconfigureClick(object sender, EventArgs e) {
PluginHelper.Instance.ConfigureSelectedItem(listview_plugins); PluginHelper.Instance.ConfigureSelectedItem(listview_plugins);
} }
void Combobox_languageSelectedIndexChanged(object sender, EventArgs e) { private void Combobox_languageSelectedIndexChanged(object sender, EventArgs e) {
// Get the combobox values BEFORE changing the language // Get the combobox values BEFORE changing the language
//EmailFormat selectedEmailFormat = GetSelected<EmailFormat>(combobox_emailformat); //EmailFormat selectedEmailFormat = GetSelected<EmailFormat>(combobox_emailformat);
WindowCaptureMode selectedWindowCaptureMode = GetSelected<WindowCaptureMode>(combobox_window_capture_mode); WindowCaptureMode selectedWindowCaptureMode = GetSelected<WindowCaptureMode>(combobox_window_capture_mode);
if (combobox_language.SelectedItem != null) { if (combobox_language.SelectedItem != null) {
LOG.Debug("Setting language to: " + (string)combobox_language.SelectedValue); Log.Debug("Setting language to: " + (string)combobox_language.SelectedValue);
Language.CurrentLanguage = (string)combobox_language.SelectedValue; Language.CurrentLanguage = (string)combobox_language.SelectedValue;
} }
// Reflect language changes to the settings form // Reflect language changes to the settings form
UpdateUI(); UpdateUi();
// Reflect Language changes form // Reflect Language changes form
ApplyLanguage(); ApplyLanguage();
@ -537,7 +560,7 @@ namespace Greenshot {
SetWindowCaptureMode(selectedWindowCaptureMode); SetWindowCaptureMode(selectedWindowCaptureMode);
} }
void Combobox_window_capture_modeSelectedIndexChanged(object sender, EventArgs e) { private void Combobox_window_capture_modeSelectedIndexChanged(object sender, EventArgs e) {
int windowsVersion = Environment.OSVersion.Version.Major; int windowsVersion = Environment.OSVersion.Version.Major;
WindowCaptureMode mode = GetSelected<WindowCaptureMode>(combobox_window_capture_mode); WindowCaptureMode mode = GetSelected<WindowCaptureMode>(combobox_window_capture_mode);
if (windowsVersion >= 6) { if (windowsVersion >= 6) {
@ -553,7 +576,7 @@ namespace Greenshot {
/// <summary> /// <summary>
/// Check the destination settings /// Check the destination settings
/// </summary> /// </summary>
void CheckDestinationSettings() { private void CheckDestinationSettings() {
bool clipboardDestinationChecked = false; bool clipboardDestinationChecked = false;
bool pickerSelected = checkbox_picker.Checked; bool pickerSelected = checkbox_picker.Checked;
bool destinationsEnabled = true; bool destinationsEnabled = true;
@ -588,7 +611,7 @@ namespace Greenshot {
} }
} }
void DestinationsCheckStateChanged(object sender, EventArgs e) { private void DestinationsCheckStateChanged(object sender, EventArgs e) {
CheckDestinationSettings(); CheckDestinationSettings();
} }
@ -652,7 +675,7 @@ namespace Greenshot {
return 1; return 1;
} }
if (firstDestination != null && firstDestination.Priority == secondDestination.Priority) { if (firstDestination != null && firstDestination.Priority == secondDestination.Priority) {
return firstDestination.Description.CompareTo(secondDestination.Description); return string.Compare(firstDestination.Description, secondDestination.Description, StringComparison.Ordinal);
} }
if (firstDestination != null) { if (firstDestination != null) {
return firstDestination.Priority - secondDestination.Priority; return firstDestination.Priority - secondDestination.Priority;

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -31,11 +31,11 @@ namespace Greenshot.Forms {
/// <summary> /// <summary>
/// the ToolStripMenuSelectList makes it possible to have a single or multi-check menu /// the ToolStripMenuSelectList makes it possible to have a single or multi-check menu
/// </summary> /// </summary>
public class ToolStripMenuSelectList : ToolStripMenuItem { public sealed class ToolStripMenuSelectList : ToolStripMenuItem {
private static CoreConfiguration coreConfiguration = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private bool multiCheckAllowed = false; private readonly bool _multiCheckAllowed;
private bool updateInProgress = false; private bool _updateInProgress;
private static Image defaultImage; private static Image _defaultImage;
/// <summary> /// <summary>
/// Occurs when one of the list's child element's Checked state changes. /// Occurs when one of the list's child element's Checked state changes.
@ -49,14 +49,12 @@ namespace Greenshot.Forms {
public ToolStripMenuSelectList(object identifier, bool allowMultiCheck) { public ToolStripMenuSelectList(object identifier, bool allowMultiCheck) {
Identifier = identifier; Identifier = identifier;
CheckOnClick = false; CheckOnClick = false;
multiCheckAllowed = allowMultiCheck; _multiCheckAllowed = allowMultiCheck;
if (defaultImage == null || defaultImage.Size != coreConfiguration.IconSize) { if (_defaultImage == null || _defaultImage.Size != CoreConfig.IconSize) {
if (defaultImage != null) { _defaultImage?.Dispose();
defaultImage.Dispose(); _defaultImage = ImageHelper.CreateEmpty(CoreConfig.IconSize.Width, CoreConfig.IconSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb, Color.Transparent, 96f, 96f);
} }
defaultImage = ImageHelper.CreateEmpty(coreConfiguration.IconSize.Width, coreConfiguration.IconSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb, Color.Transparent, 96f, 96f); Image = _defaultImage;
}
Image = defaultImage;
} }
public ToolStripMenuSelectList() : this(null,false) {} public ToolStripMenuSelectList() : this(null,false) {}
public ToolStripMenuSelectList(object identifier) : this(identifier,false) {} public ToolStripMenuSelectList(object identifier) : this(identifier,false) {}
@ -70,7 +68,7 @@ namespace Greenshot.Forms {
IEnumerator items = DropDownItems.GetEnumerator(); IEnumerator items = DropDownItems.GetEnumerator();
while (items.MoveNext()) { while (items.MoveNext()) {
ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current; ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current;
if (tsmi.Checked) { if (tsmi != null && tsmi.Checked) {
return tsmi; return tsmi;
} }
} }
@ -80,9 +78,9 @@ namespace Greenshot.Forms {
IEnumerator items = DropDownItems.GetEnumerator(); IEnumerator items = DropDownItems.GetEnumerator();
while (items.MoveNext()) { while (items.MoveNext()) {
ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current; ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current;
if (!multiCheckAllowed && !tsmi.Equals(value)) { if (tsmi != null && !_multiCheckAllowed && !tsmi.Equals(value)) {
tsmi.Checked = false; tsmi.Checked = false;
} else if (tsmi.Equals(value)) { } else if (tsmi != null && tsmi.Equals(value)) {
tsmi.Checked = true; tsmi.Checked = true;
} }
} }
@ -98,30 +96,31 @@ namespace Greenshot.Forms {
IEnumerator items = DropDownItems.GetEnumerator(); IEnumerator items = DropDownItems.GetEnumerator();
while(items.MoveNext()) { while(items.MoveNext()) {
ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current; ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current;
if (tsmi.Checked) { if (tsmi != null && tsmi.Checked) {
sel.Add(tsmi); sel.Add(tsmi);
} }
} }
return sel.ToArray(); return sel.ToArray();
} }
set { set {
if (!multiCheckAllowed) { if (!_multiCheckAllowed) {
throw new ArgumentException("Writing to checkedItems is only allowed in multi-check mode. Either set allowMultiCheck to true or use set SelectedItem instead of SelectedItems."); throw new ArgumentException("Writing to checkedItems is only allowed in multi-check mode. Either set allowMultiCheck to true or use set SelectedItem instead of SelectedItems.");
} }
IEnumerator items = DropDownItems.GetEnumerator(); IEnumerator items = DropDownItems.GetEnumerator();
IEnumerator sel = value.GetEnumerator(); IEnumerator sel = value.GetEnumerator();
while (items.MoveNext()) { while (items.MoveNext()) {
ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current; var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem)items.Current;
while (sel.MoveNext()) { if (toolStripMenuSelectListItem == null)
if (tsmi.Equals(sel.Current)) { {
tsmi.Checked = true; continue;
} else {
tsmi.Checked = false;
} }
if (!multiCheckAllowed && !tsmi.Equals(sel.Current)) { while (sel.MoveNext())
tsmi.Checked = false; {
} else if (tsmi.Equals(value)) { toolStripMenuSelectListItem.Checked = toolStripMenuSelectListItem.Equals(sel.Current);
tsmi.Checked = true; if (!_multiCheckAllowed && !toolStripMenuSelectListItem.Equals(sel.Current)) {
toolStripMenuSelectListItem.Checked = false;
} else if (toolStripMenuSelectListItem.Equals(value)) {
toolStripMenuSelectListItem.Checked = true;
} }
} }
} }
@ -129,19 +128,17 @@ namespace Greenshot.Forms {
} }
private void ItemCheckStateChanged(object sender, EventArgs e) { private void ItemCheckStateChanged(object sender, EventArgs e) {
if (updateInProgress) { if (_updateInProgress) {
return; return;
} }
ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)sender; var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem)sender;
updateInProgress = true; _updateInProgress = true;
if (tsmi.Checked && !multiCheckAllowed) { if (toolStripMenuSelectListItem.Checked && !_multiCheckAllowed) {
UncheckAll(); UncheckAll();
tsmi.Checked = true; toolStripMenuSelectListItem.Checked = true;
}
updateInProgress = false;
if (CheckedChanged != null) {
CheckedChanged(this, new ItemCheckedChangedEventArgs(tsmi));
} }
_updateInProgress = false;
CheckedChanged?.Invoke(this, new ItemCheckedChangedEventArgs(toolStripMenuSelectListItem));
} }
/// <summary> /// <summary>
@ -151,26 +148,28 @@ namespace Greenshot.Forms {
/// <param name="image">the icon to be displayed</param> /// <param name="image">the icon to be displayed</param>
/// <param name="data">the data to be returned when an item is queried</param> /// <param name="data">the data to be returned when an item is queried</param>
/// <param name="isChecked">whether the item is initially checked</param> /// <param name="isChecked">whether the item is initially checked</param>
public void AddItem(string label, Image image, Object data, bool isChecked) { public void AddItem(string label, Image image, object data, bool isChecked) {
ToolStripMenuSelectListItem newItem = new ToolStripMenuSelectListItem(); var toolStripMenuSelectListItem = new ToolStripMenuSelectListItem
newItem.Text = label; {
Text = label
};
if (image == null) { if (image == null) {
image = defaultImage; image = _defaultImage;
} }
newItem.DisplayStyle = ToolStripItemDisplayStyle.Text; toolStripMenuSelectListItem.DisplayStyle = ToolStripItemDisplayStyle.Text;
newItem.Image = image; toolStripMenuSelectListItem.Image = image;
newItem.CheckOnClick = true; toolStripMenuSelectListItem.CheckOnClick = true;
newItem.CheckStateChanged += ItemCheckStateChanged; toolStripMenuSelectListItem.CheckStateChanged += ItemCheckStateChanged;
newItem.Data = data; toolStripMenuSelectListItem.Data = data;
if (isChecked) { if (isChecked) {
if (!multiCheckAllowed) { if (!_multiCheckAllowed) {
updateInProgress = true; _updateInProgress = true;
UncheckAll(); UncheckAll();
updateInProgress = false; _updateInProgress = false;
} }
newItem.Checked = isChecked; toolStripMenuSelectListItem.Checked = true;
} }
DropDownItems.Add(newItem); DropDownItems.Add(toolStripMenuSelectListItem);
} }
/// <summary> /// <summary>
@ -187,7 +186,7 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
/// <param name="label">the label to be displayed</param> /// <param name="label">the label to be displayed</param>
/// <param name="data">the data to be returned when an item is queried</param> /// <param name="data">the data to be returned when an item is queried</param>
public void AddItem(string label, Object data) { public void AddItem(string label, object data) {
AddItem(label, null, data, false); AddItem(label, null, data, false);
} }
@ -200,12 +199,11 @@ namespace Greenshot.Forms {
} }
// <summary> /// <summary>
/// adds an item to the select list /// adds an item to the select list
/// </summary> /// </summary>
/// <param name="label">the label to be displayed</param> /// <param name="label">the label to be displayed</param>
/// <param name="image">the icon to be displayed</param> /// <param name="image">the icon to be displayed</param>
/// <param name="selected">whether the item is initially selected</param>
/// <param name="isChecked">whether the item is initially checked</param> /// <param name="isChecked">whether the item is initially checked</param>
public void AddItem(string label, Image image, bool isChecked) { public void AddItem(string label, Image image, bool isChecked) {
AddItem(label, image, null, isChecked); AddItem(label, image, null, isChecked);
@ -217,7 +215,7 @@ namespace Greenshot.Forms {
/// <param name="label">the label to be displayed</param> /// <param name="label">the label to be displayed</param>
/// <param name="data">the data to be returned when an item is queried</param> /// <param name="data">the data to be returned when an item is queried</param>
/// <param name="isChecked">whether the item is initially checked</param> /// <param name="isChecked">whether the item is initially checked</param>
public void AddItem(string label, Object data, bool isChecked) { public void AddItem(string label, object data, bool isChecked) {
AddItem(label, null, data, isChecked); AddItem(label, null, data, isChecked);
} }
@ -235,8 +233,13 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
public void UncheckAll() { public void UncheckAll() {
IEnumerator items = DropDownItems.GetEnumerator(); IEnumerator items = DropDownItems.GetEnumerator();
while (items.MoveNext()) { while (items.MoveNext())
((ToolStripMenuSelectListItem)items.Current).Checked = false; {
var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem)items.Current;
if (toolStripMenuSelectListItem != null)
{
toolStripMenuSelectListItem.Checked = false;
}
} }
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,50 +21,44 @@
using System; using System;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.Core; using GreenshotPlugin.Effects;
using GreenshotPlugin.Core;
namespace Greenshot.Forms { namespace Greenshot.Forms {
public partial class TornEdgeSettingsForm : BaseForm { public partial class TornEdgeSettingsForm : BaseForm {
private TornEdgeEffect effect; private readonly TornEdgeEffect _effect;
public TornEdgeSettingsForm(TornEdgeEffect effect) { public TornEdgeSettingsForm(TornEdgeEffect effect) {
this.effect = effect; _effect = effect;
InitializeComponent(); InitializeComponent();
ShowSettings(); ShowSettings();
} }
private void ShowSettings() { private void ShowSettings() {
shadowCheckbox.Checked = effect.GenerateShadow; shadowCheckbox.Checked = _effect.GenerateShadow;
// Fix to prevent BUG-1753 // 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; offsetX.Value = _effect.ShadowOffset.X;
offsetY.Value = effect.ShadowOffset.Y; offsetY.Value = _effect.ShadowOffset.Y;
toothsize.Value = effect.ToothHeight; toothsize.Value = _effect.ToothHeight;
verticaltoothrange.Value = effect.VerticalToothRange; verticaltoothrange.Value = _effect.VerticalToothRange;
horizontaltoothrange.Value = effect.HorizontalToothRange; horizontaltoothrange.Value = _effect.HorizontalToothRange;
top.Checked = effect.Edges[0]; top.Checked = _effect.Edges[0];
right.Checked = effect.Edges[1]; right.Checked = _effect.Edges[1];
bottom.Checked = effect.Edges[2]; bottom.Checked = _effect.Edges[2];
left.Checked = effect.Edges[3]; left.Checked = _effect.Edges[3];
} }
private void ButtonOK_Click(object sender, EventArgs e) { private void ButtonOK_Click(object sender, EventArgs e) {
effect.Darkness = (float)shadowDarkness.Value / (float)40; _effect.Darkness = shadowDarkness.Value / (float)40;
effect.ShadowOffset = new Point((int)offsetX.Value, (int)offsetY.Value); _effect.ShadowOffset = new Point((int)offsetX.Value, (int)offsetY.Value);
effect.ShadowSize = (int)thickness.Value; _effect.ShadowSize = (int)thickness.Value;
effect.ToothHeight = (int)toothsize.Value; _effect.ToothHeight = (int)toothsize.Value;
effect.VerticalToothRange = (int)verticaltoothrange.Value; _effect.VerticalToothRange = (int)verticaltoothrange.Value;
effect.HorizontalToothRange = (int)horizontaltoothrange.Value; _effect.HorizontalToothRange = (int)horizontaltoothrange.Value;
effect.Edges = new bool[] { top.Checked, right.Checked, bottom.Checked, left.Checked }; _effect.Edges = new[] { top.Checked, right.Checked, bottom.Checked, left.Checked };
effect.GenerateShadow = shadowCheckbox.Checked; _effect.GenerateShadow = shadowCheckbox.Checked;
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
} }
private void ButtonReset_Click(object sender, EventArgs e) {
effect.Reset();
ShowSettings();
}
private void ShadowCheckbox_CheckedChanged(object sender, EventArgs e) { private void ShadowCheckbox_CheckedChanged(object sender, EventArgs e) {
thickness.Enabled = shadowCheckbox.Checked; thickness.Enabled = shadowCheckbox.Checked;
offsetX.Enabled = shadowCheckbox.Checked; offsetX.Enabled = shadowCheckbox.Checked;

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