From 7c7fd67b2aa45a0552c15a7a59fc353a76133369 Mon Sep 17 00:00:00 2001 From: Robin Date: Mon, 5 Sep 2016 23:37:40 +0200 Subject: [PATCH] Added LinqBridge and did some code cleanup. --- Greenshot/Drawing/DrawableContainerList.cs | 35 ++--- Greenshot/Greenshot.csproj | 4 + Greenshot/Helpers/MailHelper.cs | 75 +++++------ Greenshot/packages.config | 1 + .../releases/innosetup/setup.iss.template | 3 +- GreenshotConfluencePlugin/Confluence.cs | 65 ++++------ GreenshotConfluencePlugin/ConfluenceUtils.cs | 3 +- .../Forms/ConfluenceSearch.xaml.cs | 69 +++++----- .../Forms/ConfluenceTreePicker.xaml.cs | 120 ++++++++--------- .../Forms/ConfluenceUpload.xaml.cs | 7 +- GreenshotPlugin/Core/AccessibleHelper.cs | 13 +- GreenshotPlugin/Core/ClipboardHelper.cs | 51 ++++---- GreenshotPlugin/Core/IEHelper.cs | 39 ++---- GreenshotPlugin/Core/ImageHelper.cs | 3 +- GreenshotPlugin/Core/ImageOutput.cs | 122 +++++++++--------- GreenshotPlugin/Core/WindowCapture.cs | 18 +-- GreenshotPlugin/GreenshotPlugin.csproj | 7 + .../Interfaces/Plugin/PluginInterfaces.cs | 29 ++--- GreenshotPlugin/packages.config | 4 + build.ps1 | 2 + 20 files changed, 327 insertions(+), 343 deletions(-) create mode 100644 GreenshotPlugin/packages.config diff --git a/Greenshot/Drawing/DrawableContainerList.cs b/Greenshot/Drawing/DrawableContainerList.cs index 8758c4885..3b0808ad3 100644 --- a/Greenshot/Drawing/DrawableContainerList.cs +++ b/Greenshot/Drawing/DrawableContainerList.cs @@ -40,7 +40,7 @@ namespace Greenshot.Drawing { [Serializable] public class DrawableContainerList : List, IDrawableContainerList { - private static readonly ComponentResourceManager editorFormResources = new ComponentResourceManager(typeof(ImageEditorForm)); + private static readonly ComponentResourceManager EditorFormResources = new ComponentResourceManager(typeof(ImageEditorForm)); public Guid ParentID { get; @@ -50,8 +50,8 @@ namespace Greenshot.Drawing { public DrawableContainerList() { } - public DrawableContainerList(Guid parentID) { - ParentID = parentID; + public DrawableContainerList(Guid parentId) { + ParentID = parentId; } public EditStatus Status { @@ -327,10 +327,11 @@ namespace Greenshot.Drawing { /// Pulls one or several elements up to the topmost level(s) in hierarchy (z-index). /// /// of elements to pull to top - public void PullElementsToTop(IDrawableContainerList elements) { + public void PullElementsToTop(IDrawableContainerList elements) + { var dcs = ToArray(); - for(int i=0; i /// Indicates whether the given list of elements can be pushed down, /// i.e. whether there is at least one unselected element lower in hierarchy @@ -462,27 +463,31 @@ namespace Greenshot.Drawing { menu.Items.Add(item); // Copy - item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)); - item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); + item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)) + { + Image = (Image) EditorFormResources.GetObject("copyToolStripMenuItem.Image") + }; item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this); }; menu.Items.Add(item); // Cut - item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)); - item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image"))); + item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)) + { + Image = (Image) EditorFormResources.GetObject("btnCut.Image") + }; item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this); - surface.RemoveElements(this, true); + surface.RemoveElements(this); }; menu.Items.Add(item); // Delete 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 { - surface.RemoveElements(this, true); + surface.RemoveElements(this); }; menu.Items.Add(item); @@ -552,7 +557,7 @@ namespace Greenshot.Drawing { } #region IDisposable Support - private bool _disposedValue = false; // To detect redundant calls + private bool _disposedValue; // To detect redundant calls protected virtual void Dispose(bool disposing) { diff --git a/Greenshot/Greenshot.csproj b/Greenshot/Greenshot.csproj index 30d5a0210..40ba04d9c 100644 --- a/Greenshot/Greenshot.csproj +++ b/Greenshot/Greenshot.csproj @@ -22,6 +22,10 @@ + + ..\packages\LinqBridge.1.3.0\lib\net20\LinqBridge.dll + True + Lib\log4net.dll diff --git a/Greenshot/Helpers/MailHelper.cs b/Greenshot/Helpers/MailHelper.cs index efda5cb30..c2e5a190c 100644 --- a/Greenshot/Helpers/MailHelper.cs +++ b/Greenshot/Helpers/MailHelper.cs @@ -135,7 +135,6 @@ namespace Greenshot.Helpers { private string _subject; private string _body; private RecipientCollection _recipientCollection; - private readonly List _files; private readonly ManualResetEvent _manualResetEvent; #endregion Member Variables @@ -146,7 +145,7 @@ namespace Greenshot.Helpers { /// Creates a blank mail message. /// public MapiMailMessage() { - _files = new List(); + Files = new List(); _recipientCollection = new RecipientCollection(); _manualResetEvent = new ManualResetEvent(false); } @@ -206,11 +205,7 @@ namespace Greenshot.Helpers { /// /// Gets the file list for this mail message. /// - public List Files { - get { - return _files; - } - } + public List Files { get; } #endregion Public Properties @@ -255,9 +250,9 @@ namespace Greenshot.Helpers { /// Sends the mail message. /// private void _ShowMail() { - MAPIHelperInterop.MapiMessage message = new MAPIHelperInterop.MapiMessage(); + var message = new MapiHelperInterop.MapiMessage(); - using (RecipientCollection.InteropRecipientCollection interopRecipients = _recipientCollection.GetInteropRepresentation()) { + using (var interopRecipients = _recipientCollection.GetInteropRepresentation()) { message.Subject = _subject; message.NoteText = _body; @@ -265,7 +260,7 @@ namespace Greenshot.Helpers { message.RecipientCount = _recipientCollection.Count; // Check if we need to add attachments - if (_files.Count > 0) { + if (Files.Count > 0) { // Add attachments message.Files = _AllocAttachments(out message.FileCount); } @@ -275,25 +270,29 @@ namespace Greenshot.Helpers { const int MAPI_DIALOG = 0x8; //const int MAPI_LOGON_UI = 0x1; - int error = MAPIHelperInterop.MAPISendMail(IntPtr.Zero, IntPtr.Zero, message, MAPI_DIALOG, 0); + int error = MapiHelperInterop.MAPISendMail(IntPtr.Zero, IntPtr.Zero, message, MAPI_DIALOG, 0); - if (_files.Count > 0) { + if (Files.Count > 0) { // Deallocate the files _DeallocFiles(message); } MAPI_CODES errorCode = (MAPI_CODES)Enum.ToObject(typeof(MAPI_CODES), error); // Check for error - if (errorCode != MAPI_CODES.SUCCESS && errorCode != MAPI_CODES.USER_ABORT) { - string errorText = GetMapiError(errorCode); - LOG.Error("Error sending MAPI Email. Error: " + errorText + " (code = " + errorCode + ")."); - MessageBox.Show(errorText, "Mail (MAPI) destination", MessageBoxButtons.OK, MessageBoxIcon.Error); - // Recover from bad settings, show again - if (errorCode == MAPI_CODES.INVALID_RECIPS) { - _recipientCollection = new RecipientCollection(); - _ShowMail(); - } + if (errorCode == MAPI_CODES.SUCCESS || errorCode == MAPI_CODES.USER_ABORT) + { + return; } + string errorText = GetMapiError(errorCode); + LOG.Error("Error sending MAPI Email. Error: " + errorText + " (code = " + errorCode + ")."); + MessageBox.Show(errorText, "Mail (MAPI) destination", MessageBoxButtons.OK, MessageBoxIcon.Error); + // Recover from bad settings, show again + if (errorCode != MAPI_CODES.INVALID_RECIPS) + { + return; + } + _recipientCollection = new RecipientCollection(); + _ShowMail(); } } @@ -301,7 +300,7 @@ namespace Greenshot.Helpers { /// Deallocates the files in a message. /// /// The message to deallocate the files from. - private void _DeallocFiles(MAPIHelperInterop.MapiMessage message) { + private void _DeallocFiles(MapiHelperInterop.MapiMessage message) { if (message.Files != IntPtr.Zero) { Type fileDescType = typeof(MapiFileDescriptor); int fsize = Marshal.SizeOf(fileDescType); @@ -325,29 +324,31 @@ namespace Greenshot.Helpers { /// private IntPtr _AllocAttachments(out int fileCount) { fileCount = 0; - if (_files == null) { + if (Files == null) { return IntPtr.Zero; } - if ((_files.Count <= 0) || (_files.Count > 100)) { + if ((Files.Count <= 0) || (Files.Count > 100)) { return IntPtr.Zero; } Type atype = typeof(MapiFileDescriptor); int asize = Marshal.SizeOf(atype); - IntPtr ptra = Marshal.AllocHGlobal(_files.Count * asize); + IntPtr ptra = Marshal.AllocHGlobal(Files.Count * asize); - MapiFileDescriptor mfd = new MapiFileDescriptor(); - mfd.position = -1; + MapiFileDescriptor mfd = new MapiFileDescriptor + { + position = -1 + }; IntPtr runptr = ptra; - for (int i = 0; i < _files.Count; i++) { - string path = _files[i] as string; + for (int i = 0; i < Files.Count; i++) { + string path = Files[i]; mfd.name = Path.GetFileName(path); mfd.path = path; Marshal.StructureToPtr(mfd, runptr, false); runptr = new IntPtr(runptr.ToInt64() + asize); } - fileCount = _files.Count; + fileCount = Files.Count; return ptra; } @@ -480,13 +481,13 @@ namespace Greenshot.Helpers { /// /// Internal class for calling MAPI APIs /// - internal class MAPIHelperInterop { + internal class MapiHelperInterop { #region Constructors /// /// Private constructor. /// - private MAPIHelperInterop() { + private MapiHelperInterop() { // Intenationally blank } @@ -599,8 +600,8 @@ namespace Greenshot.Helpers { /// Returns an interop representation of a recepient. /// /// - internal MapiMailMessage.MAPIHelperInterop.MapiRecipDesc GetInteropRepresentation() { - MapiMailMessage.MAPIHelperInterop.MapiRecipDesc interop = new MapiMailMessage.MAPIHelperInterop.MapiRecipDesc(); + internal MapiMailMessage.MapiHelperInterop.MapiRecipDesc GetInteropRepresentation() { + MapiMailMessage.MapiHelperInterop.MapiRecipDesc interop = new MapiMailMessage.MapiHelperInterop.MapiRecipDesc(); if (DisplayName == null) { interop.Name = Address; @@ -699,13 +700,13 @@ namespace Greenshot.Helpers { } // allocate enough memory to hold all recipients - int size = Marshal.SizeOf(typeof(MapiMailMessage.MAPIHelperInterop.MapiRecipDesc)); + int size = Marshal.SizeOf(typeof(MapiMailMessage.MapiHelperInterop.MapiRecipDesc)); _handle = Marshal.AllocHGlobal(_count * size); // place all interop recipients into the memory just allocated IntPtr ptr = _handle; foreach (Recipient native in outer) { - MapiMailMessage.MAPIHelperInterop.MapiRecipDesc interop = native.GetInteropRepresentation(); + MapiMailMessage.MapiHelperInterop.MapiRecipDesc interop = native.GetInteropRepresentation(); // stick it in the memory block Marshal.StructureToPtr(interop, ptr, false); @@ -732,7 +733,7 @@ namespace Greenshot.Helpers { /// public void Dispose() { if (_handle != IntPtr.Zero) { - Type type = typeof(MapiMailMessage.MAPIHelperInterop.MapiRecipDesc); + Type type = typeof(MapiMailMessage.MapiHelperInterop.MapiRecipDesc); int size = Marshal.SizeOf(type); // destroy all the structures in the memory area diff --git a/Greenshot/packages.config b/Greenshot/packages.config index a9672879a..12343fb16 100644 --- a/Greenshot/packages.config +++ b/Greenshot/packages.config @@ -1,4 +1,5 @@  + \ No newline at end of file diff --git a/Greenshot/releases/innosetup/setup.iss.template b/Greenshot/releases/innosetup/setup.iss.template index 479f94f5c..8b6194c13 100644 --- a/Greenshot/releases/innosetup/setup.iss.template +++ b/Greenshot/releases/innosetup/setup.iss.template @@ -18,7 +18,8 @@ Source: ..\..\bin\Release\Greenshot.exe; DestDir: {app}; Components: greenshot; Source: ..\..\bin\Release\GreenshotPlugin.dll; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion Source: ..\..\bin\Release\Greenshot.exe.config; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion Source: ..\..\bin\Release\log4net.dll; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion -Source: ..\..\log4net.xml; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion +Source: ..\..\log4net.xml; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion +Source: ..\..\LinqBridge.dll; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion Source: ..\..\bin\Release\checksum.MD5; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion ;Source: ..\greenshot-defaults.ini; DestDir: {app}; Flags: overwritereadonly ignoreversion replacesameversion Source: ..\additional_files\installer.txt; DestDir: {app}; Components: greenshot; Flags: overwritereadonly recursesubdirs ignoreversion replacesameversion diff --git a/GreenshotConfluencePlugin/Confluence.cs b/GreenshotConfluencePlugin/Confluence.cs index 1711970d1..714d3d20e 100644 --- a/GreenshotConfluencePlugin/Confluence.cs +++ b/GreenshotConfluencePlugin/Confluence.cs @@ -94,8 +94,8 @@ namespace Confluence { public class ConfluenceConnector : IDisposable { private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ConfluenceConnector)); private const string AuthFailedExceptionName = "com.atlassian.confluence.rpc.AuthenticationFailedException"; - private const string V2Failed = "AXIS"; - private static readonly ConfluenceConfiguration Config = IniConfig.GetIniSection(); + private const string V2Failed = "AXIS"; + private static readonly ConfluenceConfiguration Config = IniConfig.GetIniSection(); private string _credentials; private DateTime _loggedInTime = DateTime.Now; private bool _loggedIn; @@ -123,17 +123,17 @@ namespace Confluence { public ConfluenceConnector(string url, int timeout) { _timeout = timeout; - Init(url); + Init(url); } - private void Init(string url) { - _url = url; - _confluence = new ConfluenceSoapServiceService - { - Url = url, - Proxy = NetworkHelper.CreateProxy(new Uri(url)) - }; - } + private void Init(string url) { + _url = url; + _confluence = new ConfluenceSoapServiceService + { + Url = url, + Proxy = NetworkHelper.CreateProxy(new Uri(url)) + }; + } ~ConfluenceConnector() { Dispose(false); @@ -149,11 +149,11 @@ namespace Confluence { _loggedInTime = DateTime.Now; _loggedIn = true; } catch (Exception e) { - // Check if confluence-v2 caused an error, use v1 instead - if (e.Message.Contains(V2Failed) && _url.Contains("v2")) { - Init(_url.Replace("v2", "v1")); - return DoLogin(user, password); - } + // Check if confluence-v2 caused an error, use v1 instead + if (e.Message.Contains(V2Failed) && _url.Contains("v2")) { + Init(_url.Replace("v2", "v1")); + return DoLogin(user, password); + } // check if auth failed if (e.Message.Contains(AuthFailedExceptionName)) { return false; @@ -173,7 +173,7 @@ namespace Confluence { try { // Get the system name, so the user knows where to login to string systemName = _url.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX1,""); - systemName = systemName.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX2, ""); + systemName = systemName.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX2, ""); CredentialsDialog dialog = new CredentialsDialog(systemName) { Name = null @@ -274,49 +274,40 @@ namespace Confluence { return new Page(page); } - public List GetSpaceSummaries() { + public IEnumerable GetSpaceSummaries() { CheckCredentials(); RemoteSpaceSummary [] spaces = _confluence.getSpaces(_credentials); - List returnSpaces = new List(); foreach(RemoteSpaceSummary space in spaces) { - returnSpaces.Add(new Space(space)); + yield return new Space(space); } - returnSpaces.Sort((x, y) => string.CompareOrdinal(x.Name, y.Name)); - return returnSpaces; } - public List GetPageChildren(Page parentPage) { + public IEnumerable GetPageChildren(Page parentPage) { CheckCredentials(); List returnPages = new List(); RemotePageSummary[] pages = _confluence.getChildren(_credentials, parentPage.Id); foreach(RemotePageSummary page in pages) { - returnPages.Add(new Page(page)); + yield return new Page(page); } - returnPages.Sort((x, y) => string.CompareOrdinal(x.Title, y.Title)); - return returnPages; } - public List GetPageSummaries(Space space) { + public IEnumerable GetPageSummaries(Space space) { CheckCredentials(); - List returnPages = new List(); RemotePageSummary[] pages = _confluence.getPages(_credentials, space.Key); foreach(RemotePageSummary page in pages) { - returnPages.Add(new Page(page)); + yield return new Page(page); } - returnPages.Sort((x, y) => string.CompareOrdinal(x.Title, y.Title)); - return returnPages; } - public List SearchPages(string query, string space) { + public IEnumerable SearchPages(string query, string space) { CheckCredentials(); - List results = new List(); - foreach(RemoteSearchResult searchResult in _confluence.search(_credentials, query, 20)) { + foreach(var searchResult in _confluence.search(_credentials, query, 20)) { Log.DebugFormat("Got result of type {0}", searchResult.type); - if ("page".Equals(searchResult.type)) { - results.Add(new Page(searchResult, space)); + if ("page".Equals(searchResult.type)) + { + yield return new Page(searchResult, space); } } - return results; } } } diff --git a/GreenshotConfluencePlugin/ConfluenceUtils.cs b/GreenshotConfluencePlugin/ConfluenceUtils.cs index eef3501a3..64a8b9a3e 100644 --- a/GreenshotConfluencePlugin/ConfluenceUtils.cs +++ b/GreenshotConfluencePlugin/ConfluenceUtils.cs @@ -20,6 +20,7 @@ */ using System; using System.Collections.Generic; +using System.Linq; using System.Text.RegularExpressions; using System.Windows.Automation; @@ -140,7 +141,7 @@ namespace GreenshotConfluencePlugin { } } - foreach(string url in IEHelper.GetIEUrls()) { + foreach(string url in IEHelper.GetIEUrls().Distinct()) { urls.Add(url); } diff --git a/GreenshotConfluencePlugin/Forms/ConfluenceSearch.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluenceSearch.xaml.cs index f1bf0d34a..815222ef7 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluenceSearch.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluenceSearch.xaml.cs @@ -21,77 +21,68 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Linq; using System.Windows; using Greenshot.IniFile; namespace GreenshotConfluencePlugin { - public partial class ConfluenceSearch : System.Windows.Controls.Page { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceSearch)); - private static readonly ConfluenceConfiguration config = IniConfig.GetIniSection(); - private readonly ConfluenceUpload confluenceUpload; + public partial class ConfluenceSearch + { + private static readonly ConfluenceConfiguration ConfluenceConfig = IniConfig.GetIniSection(); + private readonly ConfluenceUpload _confluenceUpload; - public List Spaces { - get { - return confluenceUpload.Spaces; - } - } + public IEnumerable Spaces => _confluenceUpload.Spaces; - private readonly ObservableCollection pages = new ObservableCollection(); - public ObservableCollection Pages { - get { - return pages; - } - } + public ObservableCollection Pages { get; } = new ObservableCollection(); public ConfluenceSearch(ConfluenceUpload confluenceUpload) { - this.confluenceUpload = confluenceUpload; + _confluenceUpload = confluenceUpload; DataContext = this; InitializeComponent(); - if (config.SearchSpaceKey == null) { - SpaceComboBox.SelectedItem = Spaces[0]; + if (ConfluenceConfig.SearchSpaceKey == null) { + SpaceComboBox.SelectedItem = Spaces.FirstOrDefault(); } else { - foreach(Confluence.Space space in Spaces) { - if (space.Key.Equals(config.SearchSpaceKey)) { + foreach(var space in Spaces) { + if (space.Key.Equals(ConfluenceConfig.SearchSpaceKey)) { SpaceComboBox.SelectedItem = space; } } } } - void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { + private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { SelectionChanged(); } - - void SelectionChanged() { + + private void SelectionChanged() { if (PageListView.HasItems && PageListView.SelectedItems.Count > 0) { - confluenceUpload.SelectedPage = (Confluence.Page)PageListView.SelectedItem; + _confluenceUpload.SelectedPage = (Confluence.Page)PageListView.SelectedItem; } else { - confluenceUpload.SelectedPage = null; + _confluenceUpload.SelectedPage = null; } } - - void Search_Click(object sender, RoutedEventArgs e) { - doSearch(); + + private void Search_Click(object sender, RoutedEventArgs e) { + DoSearch(); } - void doSearch() { + private void DoSearch() { string spaceKey = (string)SpaceComboBox.SelectedValue; - config.SearchSpaceKey = spaceKey; - List searchResult = ConfluencePlugin.ConfluenceConnector.SearchPages(searchText.Text, spaceKey); - pages.Clear(); - foreach(Confluence.Page page in searchResult) { - pages.Add(page); + ConfluenceConfig.SearchSpaceKey = spaceKey; + Pages.Clear(); + foreach(var page in ConfluencePlugin.ConfluenceConnector.SearchPages(searchText.Text, spaceKey).OrderBy(p => p.Title)) { + Pages.Add(page); } } - void SearchText_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { + private void SearchText_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == System.Windows.Input.Key.Return && Search.IsEnabled) { - doSearch(); - e.Handled = true; + DoSearch(); + e.Handled = true; } } - - void Page_Loaded(object sender, RoutedEventArgs e) { + + private void Page_Loaded(object sender, RoutedEventArgs e) { SelectionChanged(); } diff --git a/GreenshotConfluencePlugin/Forms/ConfluenceTreePicker.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluenceTreePicker.xaml.cs index 066f40334..6d3768973 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluenceTreePicker.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluenceTreePicker.xaml.cs @@ -18,8 +18,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + using System; -using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Windows; using System.Windows.Controls; @@ -32,96 +33,99 @@ namespace GreenshotConfluencePlugin { /// /// Interaction logic for ConfluenceTreePicker.xaml /// - public partial class ConfluenceTreePicker : System.Windows.Controls.Page { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceTreePicker)); - private readonly ConfluenceConnector confluenceConnector; - private readonly ConfluenceUpload confluenceUpload; - private bool isInitDone = false; + public partial class ConfluenceTreePicker + { + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ConfluenceTreePicker)); + private readonly ConfluenceConnector _confluenceConnector; + private readonly ConfluenceUpload _confluenceUpload; + private bool _isInitDone; public ConfluenceTreePicker(ConfluenceUpload confluenceUpload) { - confluenceConnector = ConfluencePlugin.ConfluenceConnector; - this.confluenceUpload = confluenceUpload; + _confluenceConnector = ConfluencePlugin.ConfluenceConnector; + _confluenceUpload = confluenceUpload; InitializeComponent(); } - void pageTreeViewItem_DoubleClick(object sender, MouseButtonEventArgs eventArgs) { - LOG.Debug("spaceTreeViewItem_MouseLeftButtonDown is called!"); + private void pageTreeViewItem_DoubleClick(object sender, MouseButtonEventArgs eventArgs) { + Log.Debug("spaceTreeViewItem_MouseLeftButtonDown is called!"); TreeViewItem clickedItem = eventArgs.Source as TreeViewItem; - if (clickedItem ==null) { - return; - } - Confluence.Page page = clickedItem.Tag as Confluence.Page; + Confluence.Page page = clickedItem?.Tag as Confluence.Page; if (page == null) { return; } - if (!clickedItem.HasItems) { - LOG.Debug("Loading pages for page: " + page.Title); - (new Thread(() => { - Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => {ShowBusy.Visibility = Visibility.Visible;})); - List pages = confluenceConnector.GetPageChildren(page); - Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => { - foreach(Confluence.Page childPage in pages) { - LOG.Debug("Adding page: " + childPage.Title); - TreeViewItem pageTreeViewItem = new TreeViewItem(); - pageTreeViewItem.Header = childPage.Title; - pageTreeViewItem.Tag = childPage; - clickedItem.Items.Add(pageTreeViewItem); - pageTreeViewItem.PreviewMouseDoubleClick += new MouseButtonEventHandler(pageTreeViewItem_DoubleClick); - pageTreeViewItem.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(pageTreeViewItem_Click); - } - ShowBusy.Visibility = Visibility.Collapsed; - })); - } - ) { Name = "Loading childpages for confluence page " + page.Title }).Start(); + if (clickedItem.HasItems) + { + return; } + Log.Debug("Loading pages for page: " + page.Title); + new Thread(() => { + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => {ShowBusy.Visibility = Visibility.Visible;})); + var pages = _confluenceConnector.GetPageChildren(page).OrderBy(p => p.Title); + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => { + foreach(var childPage in pages) { + Log.Debug("Adding page: " + childPage.Title); + var pageTreeViewItem = new TreeViewItem + { + Header = childPage.Title, + Tag = childPage + }; + clickedItem.Items.Add(pageTreeViewItem); + pageTreeViewItem.PreviewMouseDoubleClick += pageTreeViewItem_DoubleClick; + pageTreeViewItem.PreviewMouseLeftButtonDown += pageTreeViewItem_Click; + } + ShowBusy.Visibility = Visibility.Collapsed; + })); + }) { Name = "Loading childpages for confluence page " + page.Title }.Start(); } - - void pageTreeViewItem_Click(object sender, MouseButtonEventArgs eventArgs) { - LOG.Debug("pageTreeViewItem_PreviewMouseDoubleClick is called!"); + + private void pageTreeViewItem_Click(object sender, MouseButtonEventArgs eventArgs) { + Log.Debug("pageTreeViewItem_PreviewMouseDoubleClick is called!"); TreeViewItem clickedItem = eventArgs.Source as TreeViewItem; if (clickedItem ==null) { return; } Confluence.Page page = clickedItem.Tag as Confluence.Page; - confluenceUpload.SelectedPage = page; + _confluenceUpload.SelectedPage = page; if (page != null) { - LOG.Debug("Page selected: " + page.Title); + Log.Debug("Page selected: " + page.Title); } } - void Page_Loaded(object sender, RoutedEventArgs e) { - confluenceUpload.SelectedPage = null; - if (isInitDone) { + private void Page_Loaded(object sender, RoutedEventArgs e) { + _confluenceUpload.SelectedPage = null; + if (_isInitDone) { return; } ShowBusy.Visibility = Visibility.Visible; - (new Thread(() => { + new Thread(() => { Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => { - List spaces = confluenceUpload.Spaces; - foreach (Space space in spaces) { - TreeViewItem spaceTreeViewItem = new TreeViewItem(); - spaceTreeViewItem.Header = space.Name; - spaceTreeViewItem.Tag = space; - + foreach (Space space in _confluenceUpload.Spaces) { + TreeViewItem spaceTreeViewItem = new TreeViewItem + { + Header = space.Name, + Tag = space + }; + // Get homepage try { - Confluence.Page page = confluenceConnector.GetSpaceHomepage(space); - TreeViewItem pageTreeViewItem = new TreeViewItem(); - pageTreeViewItem.Header = page.Title; - pageTreeViewItem.Tag = page; - pageTreeViewItem.PreviewMouseDoubleClick += new MouseButtonEventHandler(pageTreeViewItem_DoubleClick); - pageTreeViewItem.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(pageTreeViewItem_Click); + Confluence.Page page = _confluenceConnector.GetSpaceHomepage(space); + TreeViewItem pageTreeViewItem = new TreeViewItem + { + Header = page.Title, + Tag = page + }; + pageTreeViewItem.PreviewMouseDoubleClick += pageTreeViewItem_DoubleClick; + pageTreeViewItem.PreviewMouseLeftButtonDown += pageTreeViewItem_Click; spaceTreeViewItem.Items.Add(pageTreeViewItem); ConfluenceTreeView.Items.Add(spaceTreeViewItem); } catch (Exception ex) { - LOG.Error("Can't get homepage for space : " + space.Name + " (" + ex.Message + ")"); + Log.Error("Can't get homepage for space : " + space.Name + " (" + ex.Message + ")"); } } ShowBusy.Visibility = Visibility.Collapsed; - isInitDone = true; + _isInitDone = true; })); - } - ) { Name = "Loading spaces for confluence"}).Start(); + }) { Name = "Loading spaces for confluence"}.Start(); } } } \ No newline at end of file diff --git a/GreenshotConfluencePlugin/Forms/ConfluenceUpload.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluenceUpload.xaml.cs index 8308dfe43..a9326887a 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluenceUpload.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluenceUpload.xaml.cs @@ -20,6 +20,7 @@ */ using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Windows; using System.Windows.Controls; @@ -88,8 +89,8 @@ namespace GreenshotConfluencePlugin { } private static DateTime _lastLoad = DateTime.Now; - private static List _spaces; - public List Spaces { + private static IList _spaces; + public IList Spaces { get { UpdateSpaces(); while (_spaces == null) { @@ -118,7 +119,7 @@ namespace GreenshotConfluencePlugin { // Check if load is needed if (_spaces == null) { (new Thread(() => { - _spaces = ConfluencePlugin.ConfluenceConnector.GetSpaceSummaries(); + _spaces = ConfluencePlugin.ConfluenceConnector.GetSpaceSummaries().OrderBy(s => s.Name).ToList(); _lastLoad = DateTime.Now; }) { Name = "Loading spaces for confluence"}).Start(); } diff --git a/GreenshotPlugin/Core/AccessibleHelper.cs b/GreenshotPlugin/Core/AccessibleHelper.cs index db890c16e..704ecd60e 100644 --- a/GreenshotPlugin/Core/AccessibleHelper.cs +++ b/GreenshotPlugin/Core/AccessibleHelper.cs @@ -165,7 +165,7 @@ namespace GreenshotPlugin.Core { } } } - return String.Empty; + return string.Empty; } } @@ -201,7 +201,7 @@ namespace GreenshotPlugin.Core { } } } - return String.Empty; + return string.Empty; } } @@ -217,6 +217,7 @@ namespace GreenshotPlugin.Core { } } + // TODO: Why again? if (captionList.Count > 0) { captionList.RemoveAt(captionList.Count - 1); } @@ -226,10 +227,8 @@ namespace GreenshotPlugin.Core { } - public List IETabUrls { + public IEnumerable IETabUrls { get { - var urlList = new List(); - foreach (Accessible accessor in Children) { foreach (var child in accessor.Children) { foreach (var tab in child.Children) { @@ -238,14 +237,12 @@ namespace GreenshotPlugin.Core { if (!string.IsNullOrEmpty(description)) { if (description.Contains(Environment.NewLine)) { var url = description.Substring(description.IndexOf(Environment.NewLine)).Trim(); - urlList.Add(url); + yield return url; } } } } } - - return urlList; } } diff --git a/GreenshotPlugin/Core/ClipboardHelper.cs b/GreenshotPlugin/Core/ClipboardHelper.cs index 84950c05c..93984853c 100644 --- a/GreenshotPlugin/Core/ClipboardHelper.cs +++ b/GreenshotPlugin/Core/ClipboardHelper.cs @@ -25,6 +25,7 @@ using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; +using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; @@ -257,8 +258,8 @@ EndSelection:<<<<<<<4 || dataObject.GetDataPresent(FORMAT_GIF)) { return true; } - List imageFiles = GetImageFilenames(dataObject); - if (imageFiles != null && imageFiles.Count > 0) { + var imageFiles = GetImageFilenames(dataObject); + if (imageFiles.Any()) { return true; } if (dataObject.GetDataPresent(FORMAT_FILECONTENTS)) { @@ -315,19 +316,16 @@ EndSelection:<<<<<<<4 yield return singleImage; } else { // check if files are supplied - List imageFiles = GetImageFilenames(dataObject); - if (imageFiles != null) { - foreach (string imageFile in imageFiles) { - Image returnImage = null; - try { - returnImage = ImageHelper.LoadImage(imageFile); - } catch (Exception streamImageEx) { - Log.Error("Problem retrieving Image from clipboard.", streamImageEx); - } - if (returnImage != null) { - Log.InfoFormat("Got image from clipboard with size {0} and format {1}", returnImage.Size, returnImage.PixelFormat); - yield return returnImage; - } + foreach (string imageFile in GetImageFilenames(dataObject)) { + Image returnImage = null; + try { + returnImage = ImageHelper.LoadImage(imageFile); + } catch (Exception streamImageEx) { + Log.Error("Problem retrieving Image from clipboard.", streamImageEx); + } + if (returnImage != null) { + Log.InfoFormat("Got image from clipboard with size {0} and format {1}", returnImage.Size, returnImage.PixelFormat); + yield return returnImage; } } } @@ -818,22 +816,21 @@ EndSelection:<<<<<<<4 /// /// IDataObject /// - public static List GetImageFilenames(IDataObject dataObject) { - List filenames = new List(); + public static IEnumerable GetImageFilenames(IDataObject dataObject) { string[] dropFileNames = (string[]) dataObject.GetData(DataFormats.FileDrop); - try { - if (dropFileNames != null && dropFileNames.Length > 0) { - foreach (string filename in dropFileNames) { - string ext = Path.GetExtension(filename).ToLower(); - if ((ext == ".jpg") || (ext == ".jpeg") || (ext == ".tiff") || (ext == ".gif") || (ext == ".png") || (ext == ".bmp") || (ext == ".ico") || (ext == ".wmf")) { - filenames.Add(filename); - } + if (dropFileNames != null && dropFileNames.Length > 0) { + foreach (string filename in dropFileNames) { + if (string.IsNullOrEmpty(filename)) + { + continue; + } + string ext = Path.GetExtension(filename).ToLower().Substring(1); + if (ImageHelper.StreamConverters.ContainsKey(ext)) + { + yield return filename; } } - } catch (Exception ex) { - Log.Warn("Ignoring an issue with getting the dropFilenames from the clipboard: ", ex); } - return filenames; } /// diff --git a/GreenshotPlugin/Core/IEHelper.cs b/GreenshotPlugin/Core/IEHelper.cs index 2f3a2ea2f..01a806422 100644 --- a/GreenshotPlugin/Core/IEHelper.cs +++ b/GreenshotPlugin/Core/IEHelper.cs @@ -36,11 +36,9 @@ namespace GreenshotPlugin.Core { int version = 7; // Seeing if IE 9 is used, here we need another offset! using (RegistryKey ieKey = Registry.LocalMachine.OpenSubKey(IE_KEY, false)) { - if (ieKey != null) { - object versionKey = ieKey.GetValue("Version"); - if (versionKey != null) { - int.TryParse(versionKey.ToString().Substring(0,1), out version); - } + object versionKey = ieKey?.GetValue("Version"); + if (versionKey != null) { + int.TryParse(versionKey.ToString().Substring(0,1), out version); } } return version; @@ -55,21 +53,15 @@ namespace GreenshotPlugin.Core { if (browserWindowDetails == null) { return null; } - WindowDetails tmpWD = browserWindowDetails; + WindowDetails tmpWd = browserWindowDetails; // Since IE 9 the TabBandClass is less deep! if (IEVersion() < 9) { - tmpWD = tmpWD.GetChild("CommandBarClass"); - if (tmpWD != null) { - tmpWD = tmpWD.GetChild("ReBarWindow32"); - } + tmpWd = tmpWd.GetChild("CommandBarClass"); + tmpWd = tmpWd?.GetChild("ReBarWindow32"); } - if (tmpWD != null) { - tmpWD = tmpWD.GetChild("TabBandClass"); - } - if (tmpWD != null) { - tmpWD = tmpWD.GetChild("DirectUIHWND"); - } - return tmpWD; + tmpWd = tmpWd?.GetChild("TabBandClass"); + tmpWd = tmpWd?.GetChild("DirectUIHWND"); + return tmpWd; } /// @@ -77,24 +69,17 @@ namespace GreenshotPlugin.Core { /// /// public static IEnumerable GetIEUrls() { - List urls = new List(); // Find the IE window foreach (WindowDetails ieWindow in WindowDetails.GetAllWindows("IEFrame")) { WindowDetails directUIWD = GetDirectUI(ieWindow); if (directUIWD != null) { Accessible ieAccessible = new Accessible(directUIWD.Handle); - List ieUrls = ieAccessible.IETabUrls; - if (ieUrls != null && ieUrls.Count > 0) { - foreach(string url in ieUrls) { - if (!urls.Contains(url)) { - urls.Add(url); - } - } + foreach(string url in ieAccessible.IETabUrls) + { + yield return url; } } } - - return urls; } } } diff --git a/GreenshotPlugin/Core/ImageHelper.cs b/GreenshotPlugin/Core/ImageHelper.cs index 9473464f8..e0193a71b 100644 --- a/GreenshotPlugin/Core/ImageHelper.cs +++ b/GreenshotPlugin/Core/ImageHelper.cs @@ -372,7 +372,7 @@ namespace GreenshotPlugin.Core { // Fixed lock problem Bug #3431881 using (Stream imageFileStream = File.OpenRead(filename)) { - fileImage = FromStream(imageFileStream); + fileImage = FromStream(imageFileStream, Path.GetExtension(filename)); } if (fileImage != null) { @@ -381,7 +381,6 @@ namespace GreenshotPlugin.Core { return fileImage; } - /// /// Based on: http://www.codeproject.com/KB/cs/IconExtractor.aspx /// And a hint from: http://www.codeproject.com/KB/cs/IconLib.aspx diff --git a/GreenshotPlugin/Core/ImageOutput.cs b/GreenshotPlugin/Core/ImageOutput.cs index 4ca912e11..3b1803e95 100644 --- a/GreenshotPlugin/Core/ImageOutput.cs +++ b/GreenshotPlugin/Core/ImageOutput.cs @@ -42,10 +42,10 @@ namespace GreenshotPlugin.Core { /// Description of ImageOutput. /// public static class ImageOutput { - private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageOutput)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog Log = LogManager.GetLogger(typeof(ImageOutput)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131; - private static readonly Cache tmpFileCache = new Cache(10 * 60 * 60, RemoveExpiredTmpFile); + private static readonly Cache TmpFileCache = new Cache(10 * 60 * 60, RemoveExpiredTmpFile); /// /// Creates a PropertyItem (Metadata) to store with the image. @@ -71,7 +71,7 @@ namespace GreenshotPlugin.Core { propertyItem.Value = byteString; propertyItem.Len = text.Length + 1; } catch (Exception e) { - LOG.WarnFormat("Error creating a PropertyItem: {0}", e.Message); + Log.WarnFormat("Error creating a PropertyItem: {0}", e.Message); } return propertyItem; } @@ -87,8 +87,8 @@ namespace GreenshotPlugin.Core { bool disposeImage = CreateImageFromSurface(surface, outputSettings, out imageToSave); SaveToStream(imageToSave, surface, stream, outputSettings); // cleanup if needed - if (disposeImage && imageToSave != null) { - imageToSave.Dispose(); + if (disposeImage) { + imageToSave?.Dispose(); } } @@ -133,13 +133,13 @@ namespace GreenshotPlugin.Core { if (!Environment.OSVersion.IsWindows7OrLater()) { useMemoryStream = true; - LOG.Warn("Using memorystream prevent an issue with saving to a non seekable stream."); + Log.Warn("Using memorystream prevent an issue with saving to a non seekable stream."); } } imageFormat = ImageFormat.Png; break; } - LOG.DebugFormat("Saving image to stream with Format {0} and PixelFormat {1}", imageFormat, imageToSave.PixelFormat); + Log.DebugFormat("Saving image to stream with Format {0} and PixelFormat {1}", imageFormat, imageToSave.PixelFormat); // Check if we want to use a memory stream, to prevent a issue which happens with Windows before "7". // The save is made to the targetStream, this is directed to either the MemoryStream or the original @@ -156,8 +156,10 @@ namespace GreenshotPlugin.Core { { if (imageCodec.FormatID == imageFormat.Guid) { - EncoderParameters parameters = new EncoderParameters(1); - parameters.Param[0] = new EncoderParameter(Encoder.Quality, outputSettings.JPGQuality); + EncoderParameters parameters = new EncoderParameters(1) + { + Param = {[0] = new EncoderParameter(Encoder.Quality, outputSettings.JPGQuality)} + }; // Removing transparency if it's not supported in the output if (Image.IsAlphaPixelFormat(imageToSave.PixelFormat)) { @@ -195,7 +197,7 @@ namespace GreenshotPlugin.Core { AddTag(imageToSave); // Added for OptiPNG bool processed = false; - if (Equals(imageFormat, ImageFormat.Png) && !string.IsNullOrEmpty(conf.OptimizePNGCommand)) { + if (Equals(imageFormat, ImageFormat.Png) && !string.IsNullOrEmpty(CoreConfig.OptimizePNGCommand)) { processed = ProcessPngImageExternally(imageToSave, targetStream); } if (!processed) { @@ -225,10 +227,10 @@ namespace GreenshotPlugin.Core { } } } - } finally { - if (memoryStream != null) { - memoryStream.Dispose(); - } + } + finally + { + memoryStream?.Dispose(); } } @@ -239,29 +241,29 @@ namespace GreenshotPlugin.Core { /// stream to write the processed image to /// private static bool ProcessPngImageExternally(Image imageToProcess, Stream targetStream) { - if (string.IsNullOrEmpty(conf.OptimizePNGCommand)) { + if (string.IsNullOrEmpty(CoreConfig.OptimizePNGCommand)) { return false; } - if (!File.Exists(conf.OptimizePNGCommand)) { - LOG.WarnFormat("Can't find 'OptimizePNGCommand' {0}", conf.OptimizePNGCommand); + if (!File.Exists(CoreConfig.OptimizePNGCommand)) { + Log.WarnFormat("Can't find 'OptimizePNGCommand' {0}", CoreConfig.OptimizePNGCommand); return false; } string tmpFileName = Path.Combine(Path.GetTempPath(),Path.GetRandomFileName() + ".png"); try { using (FileStream tmpStream = File.Create(tmpFileName)) { - LOG.DebugFormat("Writing png to tmp file: {0}", tmpFileName); + Log.DebugFormat("Writing png to tmp file: {0}", tmpFileName); imageToProcess.Save(tmpStream, ImageFormat.Png); - if (LOG.IsDebugEnabled) { - LOG.DebugFormat("File size before processing {0}", new FileInfo(tmpFileName).Length); + if (Log.IsDebugEnabled) { + Log.DebugFormat("File size before processing {0}", new FileInfo(tmpFileName).Length); } } - if (LOG.IsDebugEnabled) { - LOG.DebugFormat("Starting : {0}", conf.OptimizePNGCommand); + if (Log.IsDebugEnabled) { + Log.DebugFormat("Starting : {0}", CoreConfig.OptimizePNGCommand); } - ProcessStartInfo processStartInfo = new ProcessStartInfo(conf.OptimizePNGCommand) + ProcessStartInfo processStartInfo = new ProcessStartInfo(CoreConfig.OptimizePNGCommand) { - Arguments = string.Format(conf.OptimizePNGCommandArguments, tmpFileName), + Arguments = string.Format(CoreConfig.OptimizePNGCommandArguments, tmpFileName), CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, @@ -271,24 +273,24 @@ namespace GreenshotPlugin.Core { if (process != null) { process.WaitForExit(); if (process.ExitCode == 0) { - if (LOG.IsDebugEnabled) { - LOG.DebugFormat("File size after processing {0}", new FileInfo(tmpFileName).Length); - LOG.DebugFormat("Reading back tmp file: {0}", tmpFileName); + if (Log.IsDebugEnabled) { + Log.DebugFormat("File size after processing {0}", new FileInfo(tmpFileName).Length); + Log.DebugFormat("Reading back tmp file: {0}", tmpFileName); } byte[] processedImage = File.ReadAllBytes(tmpFileName); targetStream.Write(processedImage, 0, processedImage.Length); return true; } - LOG.ErrorFormat("Error while processing PNG image: {0}", process.ExitCode); - LOG.ErrorFormat("Output: {0}", process.StandardOutput.ReadToEnd()); - LOG.ErrorFormat("Error: {0}", process.StandardError.ReadToEnd()); + Log.ErrorFormat("Error while processing PNG image: {0}", process.ExitCode); + Log.ErrorFormat("Output: {0}", process.StandardOutput.ReadToEnd()); + Log.ErrorFormat("Error: {0}", process.StandardError.ReadToEnd()); } } } catch (Exception e) { - LOG.Error("Error while processing PNG image: ", e); + Log.Error("Error while processing PNG image: ", e); } finally { if (File.Exists(tmpFileName)) { - LOG.DebugFormat("Cleaning up tmp file: {0}", tmpFileName); + Log.DebugFormat("Cleaning up tmp file: {0}", tmpFileName); File.Delete(tmpFileName); } } @@ -334,20 +336,20 @@ namespace GreenshotPlugin.Core { } // check for color reduction, forced or automatically, only when the DisableReduceColors is false - if (outputSettings.DisableReduceColors || (!conf.OutputFileAutoReduceColors && !outputSettings.ReduceColors)) { + if (outputSettings.DisableReduceColors || (!CoreConfig.OutputFileAutoReduceColors && !outputSettings.ReduceColors)) { return disposeImage; } bool isAlpha = Image.IsAlphaPixelFormat(imageToSave.PixelFormat); - if (outputSettings.ReduceColors || (!isAlpha && conf.OutputFileAutoReduceColors)) { + if (outputSettings.ReduceColors || (!isAlpha && CoreConfig.OutputFileAutoReduceColors)) { using (var quantizer = new WuQuantizer((Bitmap)imageToSave)) { int colorCount = quantizer.GetColorCount(); - LOG.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount); + Log.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount); if (!outputSettings.ReduceColors && colorCount >= 256) { return disposeImage; } try { - LOG.Info("Reducing colors on bitmap to 256."); - tmpImage = quantizer.GetQuantizedImage(conf.OutputFileReduceColorsTo); + Log.Info("Reducing colors on bitmap to 256."); + tmpImage = quantizer.GetQuantizedImage(CoreConfig.OutputFileReduceColorsTo); if (disposeImage) { imageToSave.Dispose(); } @@ -355,11 +357,11 @@ namespace GreenshotPlugin.Core { // Make sure the "new" image is disposed disposeImage = true; } catch (Exception e) { - LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e); + Log.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e); } } } else if (isAlpha && !outputSettings.ReduceColors) { - LOG.Info("Skipping 'optional' color reduction as the image has alpha"); + Log.Info("Skipping 'optional' color reduction as the image has alpha"); } return disposeImage; } @@ -375,7 +377,7 @@ namespace GreenshotPlugin.Core { try { imageToSave.SetPropertyItem(softwareUsedPropertyItem); } catch (Exception) { - LOG.WarnFormat("Couldn't set property {0}", softwareUsedPropertyItem.Id); + Log.WarnFormat("Couldn't set property {0}", softwareUsedPropertyItem.Id); } } } @@ -390,13 +392,13 @@ namespace GreenshotPlugin.Core { if (string.IsNullOrEmpty(fullPath)) { return null; } - LOG.InfoFormat("Loading image from file {0}", fullPath); + Log.InfoFormat("Loading image from file {0}", fullPath); // Fixed lock problem Bug #3431881 using (Stream surfaceFileStream = File.OpenRead(fullPath)) { returnSurface = ImageHelper.LoadGreenshotSurface(surfaceFileStream, returnSurface); } if (returnSurface != null) { - LOG.InfoFormat("Information about file {0}: {1}x{2}-{3} Resolution {4}x{5}", fullPath, returnSurface.Image.Width, returnSurface.Image.Height, returnSurface.Image.PixelFormat, returnSurface.Image.HorizontalResolution, returnSurface.Image.VerticalResolution); + Log.InfoFormat("Information about file {0}: {1}x{2}-{3} Resolution {4}x{5}", fullPath, returnSurface.Image.Width, returnSurface.Image.Height, returnSurface.Image.PixelFormat, returnSurface.Image.HorizontalResolution, returnSurface.Image.VerticalResolution); } return returnSurface; } @@ -421,7 +423,7 @@ namespace GreenshotPlugin.Core { throwingException.Data.Add("fullPath", fullPath); throw throwingException; } - LOG.DebugFormat("Saving surface to {0}", fullPath); + Log.DebugFormat("Saving surface to {0}", fullPath); // Create the stream and call SaveToStream using (FileStream stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) { SaveToStream(surface, stream, outputSettings); @@ -444,7 +446,7 @@ namespace GreenshotPlugin.Core { try { format = (OutputFormat)Enum.Parse(typeof(OutputFormat), extension.ToLower()); } catch (ArgumentException ae) { - LOG.Warn("Couldn't parse extension: " + extension, ae); + Log.Warn("Couldn't parse extension: " + extension, ae); } return format; } @@ -466,12 +468,12 @@ namespace GreenshotPlugin.Core { try { string fileNameWithExtension = saveImageFileDialog.FileNameWithExtension; SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(FormatForFilename(fileNameWithExtension)); - if (conf.OutputFilePromptQuality) { + if (CoreConfig.OutputFilePromptQuality) { QualityDialog qualityDialog = new QualityDialog(outputSettings); qualityDialog.ShowDialog(); } // TODO: For now we always overwrite, should be changed - Save(surface, fileNameWithExtension, true, outputSettings, conf.OutputFileCopyPathToClipboard); + Save(surface, fileNameWithExtension, true, outputSettings, CoreConfig.OutputFileCopyPathToClipboard); returnValue = fileNameWithExtension; IniConfig.Save(); } catch (ExternalException) { @@ -492,8 +494,8 @@ namespace GreenshotPlugin.Core { /// /// Path to image file public static string SaveNamedTmpFile(ISurface surface, ICaptureDetails captureDetails, SurfaceOutputSettings outputSettings) { - string pattern = conf.OutputFileFilenamePattern; - if (pattern == null || string.IsNullOrEmpty(pattern.Trim())) { + string pattern = CoreConfig.OutputFileFilenamePattern; + if (string.IsNullOrEmpty(pattern?.Trim())) { pattern = "greenshot ${capturetime}"; } string filename = FilenameHelper.GetFilenameFromPattern(pattern, outputSettings.Format, captureDetails); @@ -503,13 +505,13 @@ namespace GreenshotPlugin.Core { filename = Regex.Replace(filename, @"_+", "_"); string tmpFile = Path.Combine(Path.GetTempPath(), filename); - LOG.Debug("Creating TMP File: " + tmpFile); + Log.Debug("Creating TMP File: " + tmpFile); // 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 try { Save(surface, tmpFile, true, outputSettings, false); - tmpFileCache.Add(tmpFile, tmpFile); + TmpFileCache.Add(tmpFile, tmpFile); } catch (Exception e) { // Show the problem MessageBox.Show(e.Message, "Error"); @@ -526,15 +528,15 @@ namespace GreenshotPlugin.Core { /// /// true if it worked public static bool DeleteNamedTmpFile(string tmpfile) { - LOG.Debug("Deleting TMP File: " + tmpfile); + Log.Debug("Deleting TMP File: " + tmpfile); try { if (File.Exists(tmpfile)) { File.Delete(tmpfile); - tmpFileCache.Remove(tmpfile); + TmpFileCache.Remove(tmpfile); } return true; } catch (Exception ex) { - LOG.Warn("Error deleting tmp file: ", ex); + Log.Warn("Error deleting tmp file: ", ex); } return false; } @@ -554,11 +556,11 @@ namespace GreenshotPlugin.Core { destinationPath = Path.GetTempPath(); } string tmpPath = Path.Combine(destinationPath, tmpFile); - LOG.Debug("Creating TMP File : " + tmpPath); + Log.Debug("Creating TMP File : " + tmpPath); try { Save(surface, tmpPath, true, outputSettings, false); - tmpFileCache.Add(tmpPath, tmpPath); + TmpFileCache.Add(tmpPath, tmpPath); } catch (Exception) { return null; } @@ -569,12 +571,12 @@ namespace GreenshotPlugin.Core { /// Cleanup all created tmpfiles /// public static void RemoveTmpFiles() { - foreach (string tmpFile in tmpFileCache.Elements) { + foreach (string tmpFile in TmpFileCache.Elements) { if (File.Exists(tmpFile)) { - LOG.DebugFormat("Removing old temp file {0}", tmpFile); + Log.DebugFormat("Removing old temp file {0}", tmpFile); File.Delete(tmpFile); } - tmpFileCache.Remove(tmpFile); + TmpFileCache.Remove(tmpFile); } } @@ -586,7 +588,7 @@ namespace GreenshotPlugin.Core { private static void RemoveExpiredTmpFile(string filekey, object filename) { string path = filename as string; if (path != null && File.Exists(path)) { - LOG.DebugFormat("Removing expired file {0}", path); + Log.DebugFormat("Removing expired file {0}", path); File.Delete(path); } } diff --git a/GreenshotPlugin/Core/WindowCapture.cs b/GreenshotPlugin/Core/WindowCapture.cs index 48f0e31ad..eae9ba0ec 100644 --- a/GreenshotPlugin/Core/WindowCapture.cs +++ b/GreenshotPlugin/Core/WindowCapture.cs @@ -80,30 +80,26 @@ namespace GreenshotPlugin.Core { set; } - private List _captureDestinations = new List(); - public List CaptureDestinations { - get {return _captureDestinations;} - set {_captureDestinations = value;} - } + public List CaptureDestinations { get; set; } = new List(); public void ClearDestinations() { - _captureDestinations.Clear(); + CaptureDestinations.Clear(); } public void RemoveDestination(IDestination destination) { - if (_captureDestinations.Contains(destination)) { - _captureDestinations.Remove(destination); + if (CaptureDestinations.Contains(destination)) { + CaptureDestinations.Remove(destination); } } public void AddDestination(IDestination captureDestination) { - if (!_captureDestinations.Contains(captureDestination)) { - _captureDestinations.Add(captureDestination); + if (!CaptureDestinations.Contains(captureDestination)) { + CaptureDestinations.Add(captureDestination); } } public bool HasDestination(string designation) { - foreach(IDestination destination in _captureDestinations) { + foreach(IDestination destination in CaptureDestinations) { if (designation.Equals(destination.Designation)) { return true; } diff --git a/GreenshotPlugin/GreenshotPlugin.csproj b/GreenshotPlugin/GreenshotPlugin.csproj index 5dbed379b..b26c5c405 100644 --- a/GreenshotPlugin/GreenshotPlugin.csproj +++ b/GreenshotPlugin/GreenshotPlugin.csproj @@ -24,6 +24,10 @@ + + ..\packages\LinqBridge.1.3.0\lib\net20\LinqBridge.dll + True + ..\Greenshot\Lib\log4net.dll @@ -223,4 +227,7 @@ + + + \ No newline at end of file diff --git a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs index c0956a359..c56cc6570 100644 --- a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs +++ b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs @@ -75,16 +75,15 @@ namespace Greenshot.Plugin { public delegate void HotKeyHandler(); public class SurfaceOutputSettings { - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - private bool reduceColors; - private bool disableReduceColors; - private readonly List effects = new List(); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); + private bool _reduceColors; + private bool _disableReduceColors; public SurfaceOutputSettings() { - disableReduceColors = false; - Format = conf.OutputFileFormat; - JPGQuality = conf.OutputFileJpegQuality; - ReduceColors = conf.OutputFileReduceColors; + _disableReduceColors = false; + Format = CoreConfig.OutputFileFormat; + JPGQuality = CoreConfig.OutputFileJpegQuality; + ReduceColors = CoreConfig.OutputFileReduceColors; } public SurfaceOutputSettings(OutputFormat format) : this() { @@ -121,11 +120,7 @@ namespace Greenshot.Plugin { set; } - public List Effects { - get { - return effects; - } - } + public List Effects { get; } = new List(); public bool ReduceColors { get { @@ -133,10 +128,10 @@ namespace Greenshot.Plugin { if (OutputFormat.gif.Equals(Format)) { return true; } - return reduceColors; + return _reduceColors; } set { - reduceColors = value; + _reduceColors = value; } } @@ -145,12 +140,12 @@ namespace Greenshot.Plugin { /// public bool DisableReduceColors { get { - return disableReduceColors; + return _disableReduceColors; } set { // Quantizing os needed when output format is gif as this has only 256 colors! if (!OutputFormat.gif.Equals(Format)) { - disableReduceColors = value; + _disableReduceColors = value; } } } diff --git a/GreenshotPlugin/packages.config b/GreenshotPlugin/packages.config new file mode 100644 index 000000000..6003a80e6 --- /dev/null +++ b/GreenshotPlugin/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/build.ps1 b/build.ps1 index e7aa2bf80..88bef73b7 100644 --- a/build.ps1 +++ b/build.ps1 @@ -135,6 +135,7 @@ Function PackagePortable { @( "$sourcebase\checksum.MD5", "$sourcebase\Greenshot.exe.config", "$sourcebase\GreenshotPlugin.dll", + "$sourcebase\LinqBridge.dll", "$sourcebase\log4net.dll", "$sourcebase\log4net-portable.xml", "$destbase\additional_files\*.txt" ) | foreach { Copy-Item $_ "$destbase\portabletmp\App\Greenshot\" } @@ -208,6 +209,7 @@ Function PackageZip { "$sourcebase\Greenshot.exe", "$sourcebase\Greenshot.exe.config", "$sourcebase\GreenshotPlugin.dll", + "$sourcebase\LinqBridge.dll", "$sourcebase\log4net.dll", "$destbase\additional_files\*.txt" ) | foreach { Copy-Item $_ "$destzip\" }