Added LinqBridge and did some code cleanup.

This commit is contained in:
Robin 2016-09-05 23:37:40 +02:00
parent fc192827f1
commit 7c7fd67b2a
20 changed files with 327 additions and 343 deletions

View file

@ -40,7 +40,7 @@ namespace Greenshot.Drawing {
[Serializable]
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 {
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).
/// </summary>
/// <param name="elements">of elements to pull to top</param>
public void PullElementsToTop(IDrawableContainerList elements) {
public void PullElementsToTop(IDrawableContainerList elements)
{
var dcs = ToArray();
for(int i=0; i<dcs.Length; i++) {
var dc = dcs[i];
foreach (var dc in dcs)
{
if (!elements.Contains(dc)) {
continue;
}
@ -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)
{

View file

@ -22,6 +22,10 @@
</UpgradeBackupLocation>
</PropertyGroup>
<ItemGroup>
<Reference Include="LinqBridge, Version=1.3.0.0, Culture=neutral, PublicKeyToken=c2b14eb747628076, processorArchitecture=MSIL">
<HintPath>..\packages\LinqBridge.1.3.0\lib\net20\LinqBridge.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="log4net">
<HintPath>Lib\log4net.dll</HintPath>
</Reference>

View file

@ -135,7 +135,6 @@ namespace Greenshot.Helpers {
private string _subject;
private string _body;
private RecipientCollection _recipientCollection;
private readonly List<string> _files;
private readonly ManualResetEvent _manualResetEvent;
#endregion Member Variables
@ -146,7 +145,7 @@ namespace Greenshot.Helpers {
/// Creates a blank mail message.
/// </summary>
public MapiMailMessage() {
_files = new List<string>();
Files = new List<string>();
_recipientCollection = new RecipientCollection();
_manualResetEvent = new ManualResetEvent(false);
}
@ -206,11 +205,7 @@ namespace Greenshot.Helpers {
/// <summary>
/// Gets the file list for this mail message.
/// </summary>
public List<string> Files {
get {
return _files;
}
}
public List<string> Files { get; }
#endregion Public Properties
@ -255,9 +250,9 @@ namespace Greenshot.Helpers {
/// Sends the mail message.
/// </summary>
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,33 +270,37 @@ 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) {
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) {
if (errorCode != MAPI_CODES.INVALID_RECIPS)
{
return;
}
_recipientCollection = new RecipientCollection();
_ShowMail();
}
}
}
}
/// <summary>
/// Deallocates the files in a message.
/// </summary>
/// <param name="message">The message to deallocate the files from.</param>
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 {
/// <returns></returns>
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 {
/// <summary>
/// Internal class for calling MAPI APIs
/// </summary>
internal class MAPIHelperInterop {
internal class MapiHelperInterop {
#region Constructors
/// <summary>
/// Private constructor.
/// </summary>
private MAPIHelperInterop() {
private MapiHelperInterop() {
// Intenationally blank
}
@ -599,8 +600,8 @@ namespace Greenshot.Helpers {
/// Returns an interop representation of a recepient.
/// </summary>
/// <returns></returns>
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 {
/// </summary>
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

View file

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="LinqBridge" version="1.3.0" targetFramework="net20" />
<package id="Tools.InnoSetup" version="5.5.9" targetFramework="net20" />
</packages>

View file

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

View file

@ -274,49 +274,40 @@ namespace Confluence {
return new Page(page);
}
public List<Space> GetSpaceSummaries() {
public IEnumerable<Space> GetSpaceSummaries() {
CheckCredentials();
RemoteSpaceSummary [] spaces = _confluence.getSpaces(_credentials);
List<Space> returnSpaces = new List<Space>();
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<Page> GetPageChildren(Page parentPage) {
public IEnumerable<Page> GetPageChildren(Page parentPage) {
CheckCredentials();
List<Page> returnPages = new List<Page>();
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<Page> GetPageSummaries(Space space) {
public IEnumerable<Page> GetPageSummaries(Space space) {
CheckCredentials();
List<Page> returnPages = new List<Page>();
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<Page> SearchPages(string query, string space) {
public IEnumerable<Page> SearchPages(string query, string space) {
CheckCredentials();
List<Page> results = new List<Page>();
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));
}
}
return results;
if ("page".Equals(searchResult.type))
{
yield return new Page(searchResult, space);
}
}
}
}
}

View file

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

View file

@ -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<ConfluenceConfiguration>();
private readonly ConfluenceUpload confluenceUpload;
public partial class ConfluenceSearch
{
private static readonly ConfluenceConfiguration ConfluenceConfig = IniConfig.GetIniSection<ConfluenceConfiguration>();
private readonly ConfluenceUpload _confluenceUpload;
public List<Confluence.Space> Spaces {
get {
return confluenceUpload.Spaces;
}
}
public IEnumerable<Confluence.Space> Spaces => _confluenceUpload.Spaces;
private readonly ObservableCollection<Confluence.Page> pages = new ObservableCollection<Confluence.Page>();
public ObservableCollection<Confluence.Page> Pages {
get {
return pages;
}
}
public ObservableCollection<Confluence.Page> Pages { get; } = new ObservableCollection<Confluence.Page>();
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<Confluence.Page> 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();
DoSearch();
e.Handled = true;
}
}
void Page_Loaded(object sender, RoutedEventArgs e) {
private void Page_Loaded(object sender, RoutedEventArgs e) {
SelectionChanged();
}

View file

@ -18,8 +18,9 @@
* 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;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
@ -32,96 +33,99 @@ namespace GreenshotConfluencePlugin {
/// <summary>
/// Interaction logic for ConfluenceTreePicker.xaml
/// </summary>
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(() => {
if (clickedItem.HasItems)
{
return;
}
Log.Debug("Loading pages for page: " + page.Title);
new Thread(() => {
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => {ShowBusy.Visibility = Visibility.Visible;}));
List<Confluence.Page> pages = confluenceConnector.GetPageChildren(page);
var pages = _confluenceConnector.GetPageChildren(page).OrderBy(p => p.Title);
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;
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 += new MouseButtonEventHandler(pageTreeViewItem_DoubleClick);
pageTreeViewItem.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(pageTreeViewItem_Click);
pageTreeViewItem.PreviewMouseDoubleClick += pageTreeViewItem_DoubleClick;
pageTreeViewItem.PreviewMouseLeftButtonDown += pageTreeViewItem_Click;
}
ShowBusy.Visibility = Visibility.Collapsed;
}));
}
) { Name = "Loading childpages for confluence page " + page.Title }).Start();
}
}) { 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<Space> 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();
}
}
}

View file

@ -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<Confluence.Space> _spaces;
public List<Confluence.Space> Spaces {
private static IList<Confluence.Space> _spaces;
public IList<Confluence.Space> 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();
}

View file

@ -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<string> IETabUrls {
public IEnumerable<string> IETabUrls {
get {
var urlList = new List<string>();
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;
}
}

View file

@ -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<string> imageFiles = GetImageFilenames(dataObject);
if (imageFiles != null && imageFiles.Count > 0) {
var imageFiles = GetImageFilenames(dataObject);
if (imageFiles.Any()) {
return true;
}
if (dataObject.GetDataPresent(FORMAT_FILECONTENTS)) {
@ -315,9 +316,7 @@ EndSelection:<<<<<<<4
yield return singleImage;
} else {
// check if files are supplied
List<string> imageFiles = GetImageFilenames(dataObject);
if (imageFiles != null) {
foreach (string imageFile in imageFiles) {
foreach (string imageFile in GetImageFilenames(dataObject)) {
Image returnImage = null;
try {
returnImage = ImageHelper.LoadImage(imageFile);
@ -331,7 +330,6 @@ EndSelection:<<<<<<<4
}
}
}
}
/// <summary>
/// Get an Image from the IDataObject, don't check for FileDrop
@ -818,22 +816,21 @@ EndSelection:<<<<<<<4
/// </summary>
/// <param name="dataObject">IDataObject</param>
/// <returns></returns>
public static List<string> GetImageFilenames(IDataObject dataObject) {
List<string> filenames = new List<string>();
public static IEnumerable<string> 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 (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;
}
/// <summary>

View file

@ -36,13 +36,11 @@ 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");
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;
}
/// <summary>
@ -77,24 +69,17 @@ namespace GreenshotPlugin.Core {
/// </summary>
/// <returns></returns>
public static IEnumerable<string> GetIEUrls() {
List<string> urls = new List<string>();
// 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<string> 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;
}
}
}

View file

@ -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;
}
/// <summary>
/// Based on: http://www.codeproject.com/KB/cs/IconExtractor.aspx
/// And a hint from: http://www.codeproject.com/KB/cs/IconLib.aspx

View file

@ -42,10 +42,10 @@ namespace GreenshotPlugin.Core {
/// Description of ImageOutput.
/// </summary>
public static class ImageOutput {
private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageOutput));
private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly ILog Log = LogManager.GetLogger(typeof(ImageOutput));
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131;
private static readonly Cache<string, string> tmpFileCache = new Cache<string, string>(10 * 60 * 60, RemoveExpiredTmpFile);
private static readonly Cache<string, string> TmpFileCache = new Cache<string, string>(10 * 60 * 60, RemoveExpiredTmpFile);
/// <summary>
/// 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 {
/// <param name="targetStream">stream to write the processed image to</param>
/// <returns></returns>
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 {
/// <param name="outputSettings"></param>
/// <returns>Path to image file</returns>
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 {
/// <param name="tmpfile"></param>
/// <returns>true if it worked</returns>
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
/// </summary>
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);
}
}

View file

@ -80,30 +80,26 @@ namespace GreenshotPlugin.Core {
set;
}
private List<IDestination> _captureDestinations = new List<IDestination>();
public List<IDestination> CaptureDestinations {
get {return _captureDestinations;}
set {_captureDestinations = value;}
}
public List<IDestination> CaptureDestinations { get; set; } = new List<IDestination>();
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;
}

View file

@ -24,6 +24,10 @@
<ItemGroup>
<Reference Include="Accessibility" />
<Reference Include="CustomMarshalers" />
<Reference Include="LinqBridge, Version=1.3.0.0, Culture=neutral, PublicKeyToken=c2b14eb747628076, processorArchitecture=MSIL">
<HintPath>..\packages\LinqBridge.1.3.0\lib\net20\LinqBridge.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="log4net">
<HintPath>..\Greenshot\Lib\log4net.dll</HintPath>
</Reference>
@ -223,4 +227,7 @@
<ItemGroup>
<Folder Include="Interfaces\Drawing\Filters\" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
</Project>

View file

@ -75,16 +75,15 @@ namespace Greenshot.Plugin {
public delegate void HotKeyHandler();
public class SurfaceOutputSettings {
private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private bool reduceColors;
private bool disableReduceColors;
private readonly List<IEffect> effects = new List<IEffect>();
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
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<IEffect> Effects {
get {
return effects;
}
}
public List<IEffect> Effects { get; } = new List<IEffect>();
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 {
/// </summary>
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;
}
}
}

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="LinqBridge" version="1.3.0" targetFramework="net20" />
</packages>

View file

@ -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\" }