This is a quick Imgur fix, and reducing the amount of traffic.

This commit is contained in:
Robin 2016-11-03 21:51:27 +01:00
commit a9a745a439
22 changed files with 1136 additions and 757 deletions

View file

@ -25,13 +25,10 @@ using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using log4net;
namespace Greenshot.Drawing.Filters { namespace Greenshot.Drawing.Filters {
[Serializable()] [Serializable]
public class BlurFilter : AbstractFilter { public class BlurFilter : AbstractFilter {
private static ILog LOG = LogManager.GetLogger(typeof(BlurFilter));
public double previewQuality; public double previewQuality;
public double PreviewQuality { public double PreviewQuality {
get { return previewQuality; } get { return previewQuality; }
@ -43,7 +40,7 @@ namespace Greenshot.Drawing.Filters {
AddField(GetType(), FieldType.PREVIEW_QUALITY, 1.0d); AddField(GetType(), FieldType.PREVIEW_QUALITY, 1.0d);
} }
public unsafe override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) { public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) {
int blurRadius = GetFieldValueAsInt(FieldType.BLUR_RADIUS); int blurRadius = GetFieldValueAsInt(FieldType.BLUR_RADIUS);
Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert); Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert);
if (applyRect.Width == 0 || applyRect.Height == 0) { if (applyRect.Width == 0 || applyRect.Height == 0) {
@ -54,7 +51,7 @@ namespace Greenshot.Drawing.Filters {
graphics.SetClip(applyRect); graphics.SetClip(applyRect);
graphics.ExcludeClip(rect); graphics.ExcludeClip(rect);
} }
if (GDIplus.isBlurPossible(blurRadius)) { if (GDIplus.IsBlurPossible(blurRadius)) {
GDIplus.DrawWithBlur(graphics, applyBitmap, applyRect, null, null, blurRadius, false); GDIplus.DrawWithBlur(graphics, applyBitmap, applyRect, null, null, blurRadius, false);
} else { } else {
using (IFastBitmap fastBitmap = FastBitmap.CreateCloneOf(applyBitmap, applyRect)) { using (IFastBitmap fastBitmap = FastBitmap.CreateCloneOf(applyBitmap, applyRect)) {
@ -63,7 +60,6 @@ namespace Greenshot.Drawing.Filters {
} }
} }
graphics.Restore(state); graphics.Restore(state);
return;
} }
} }
} }

View file

@ -7,8 +7,17 @@ CHANGE LOG:
All details to our tickets can be found here: https://greenshot.atlassian.net All details to our tickets can be found here: https://greenshot.atlassian.net
@DETAILVERSION@ @DETAILVERSION@
Changes for this release:
This has Imgur improvements for the newer API version, this is a backport from Greenshot 1.2.9
With the move to a new hosting platform, we also noticed our update checks are way to often, this needed to be reduced.
1.2.8.12-cab854b RELEASE
There were some major issues with the authenticated (non anonymous) uploads to Imgur. There were some major issues with the authenticated (non anonymous) uploads to Imgur.
After contacting Imgur they told us that their old API was deprecated or disabled, unfortunately this was not communicated. After contacting Imgur they told us that their old API was deprecated or disabled, unfortunately this was not communicated.
Although we are working hard on Greenshot 1.3, where we changed most of the Imgur code already, we can't release it. Although we are working hard on Greenshot 1.3, where we changed most of the Imgur code already, we can't release it.

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -19,7 +19,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System;
using GreenshotPlugin.Controls; using GreenshotPlugin.Controls;
namespace GreenshotImgurPlugin { namespace GreenshotImgurPlugin {
@ -27,7 +26,5 @@ namespace GreenshotImgurPlugin {
/// This class is needed for design-time resolving of the language files /// This class is needed for design-time resolving of the language files
/// </summary> /// </summary>
public class ImgurForm : GreenshotForm { public class ImgurForm : GreenshotForm {
public ImgurForm() : base() {
}
} }
} }

View file

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

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -31,24 +31,24 @@ namespace GreenshotImgurPlugin {
/// <summary> /// <summary>
/// Description of ImgurHistory. /// Description of ImgurHistory.
/// </summary> /// </summary>
public partial class ImgurHistory : ImgurForm { public sealed partial class ImgurHistory : ImgurForm {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurHistory)); private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurHistory));
private GreenshotColumnSorter columnSorter; private readonly GreenshotColumnSorter _columnSorter;
private static ImgurConfiguration config = IniConfig.GetIniSection<ImgurConfiguration>(); private static readonly ImgurConfiguration Config = IniConfig.GetIniSection<ImgurConfiguration>();
private static ImgurHistory instance; private static ImgurHistory _instance;
public static void ShowHistory() { public static void ShowHistory() {
// Make sure the history is loaded, will be done only once // Make sure the history is loaded, will be done only once
ImgurUtils.LoadHistory(); ImgurUtils.LoadHistory();
if (instance == null) { if (_instance == null) {
instance = new ImgurHistory(); _instance = new ImgurHistory();
} }
instance.Show(); _instance.Show();
instance.redraw(); _instance.Redraw();
} }
private ImgurHistory() { private ImgurHistory() {
this.ManualLanguageApply = true; ManualLanguageApply = true;
// //
// The InitializeComponent() call is required for Windows Forms designer support. // The InitializeComponent() call is required for Windows Forms designer support.
// //
@ -56,21 +56,21 @@ namespace GreenshotImgurPlugin {
AcceptButton = finishedButton; AcceptButton = finishedButton;
CancelButton = finishedButton; CancelButton = finishedButton;
// Init sorting // Init sorting
columnSorter = new GreenshotColumnSorter(); _columnSorter = new GreenshotColumnSorter();
this.listview_imgur_uploads.ListViewItemSorter = columnSorter; listview_imgur_uploads.ListViewItemSorter = _columnSorter;
columnSorter.SortColumn = 3; _columnSorter.SortColumn = 3;
columnSorter.Order = SortOrder.Descending; _columnSorter.Order = SortOrder.Descending;
redraw(); Redraw();
if (listview_imgur_uploads.Items.Count > 0) { if (listview_imgur_uploads.Items.Count > 0) {
listview_imgur_uploads.Items[0].Selected = true; listview_imgur_uploads.Items[0].Selected = true;
} }
ApplyLanguage(); ApplyLanguage();
if (config.Credits > 0) { if (Config.Credits > 0) {
this.Text = this.Text + " (" + config.Credits + " credits)"; Text = Text + " (" + Config.Credits + " credits)";
} }
} }
private void redraw() { private void Redraw() {
// Should fix Bug #3378699 // Should fix Bug #3378699
pictureBox1.Image = pictureBox1.ErrorImage; pictureBox1.Image = pictureBox1.ErrorImage;
listview_imgur_uploads.BeginUpdate(); listview_imgur_uploads.BeginUpdate();
@ -80,9 +80,11 @@ namespace GreenshotImgurPlugin {
foreach (string column in columns) { foreach (string column in columns) {
listview_imgur_uploads.Columns.Add(column); listview_imgur_uploads.Columns.Add(column);
} }
foreach (ImgurInfo imgurInfo in config.runtimeImgurHistory.Values) { foreach (ImgurInfo imgurInfo in Config.runtimeImgurHistory.Values) {
ListViewItem item = new ListViewItem(imgurInfo.Hash); var item = new ListViewItem(imgurInfo.Hash)
item.Tag = imgurInfo; {
Tag = imgurInfo
};
item.SubItems.Add(imgurInfo.Title); item.SubItems.Add(imgurInfo.Title);
item.SubItems.Add(imgurInfo.DeleteHash); item.SubItems.Add(imgurInfo.DeleteHash);
item.SubItems.Add(imgurInfo.Timestamp.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo)); item.SubItems.Add(imgurInfo.Timestamp.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo));
@ -101,7 +103,7 @@ namespace GreenshotImgurPlugin {
private void Listview_imgur_uploadsSelectedIndexChanged(object sender, EventArgs e) { private void Listview_imgur_uploadsSelectedIndexChanged(object sender, EventArgs e) {
pictureBox1.Image = pictureBox1.ErrorImage; pictureBox1.Image = pictureBox1.ErrorImage;
if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) { if (listview_imgur_uploads.SelectedItems.Count > 0) {
deleteButton.Enabled = true; deleteButton.Enabled = true;
openButton.Enabled = true; openButton.Enabled = true;
clipboardButton.Enabled = true; clipboardButton.Enabled = true;
@ -118,40 +120,39 @@ namespace GreenshotImgurPlugin {
} }
private void DeleteButtonClick(object sender, EventArgs e) { private void DeleteButtonClick(object sender, EventArgs e) {
if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) { if (listview_imgur_uploads.SelectedItems.Count > 0) {
for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) { for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) {
ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag; ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag;
DialogResult result = MessageBox.Show(Language.GetFormattedString("imgur", LangKey.delete_question, imgurInfo.Title), Language.GetFormattedString("imgur", LangKey.delete_title, imgurInfo.Hash), MessageBoxButtons.YesNo, MessageBoxIcon.Question); DialogResult result = MessageBox.Show(Language.GetFormattedString("imgur", LangKey.delete_question, imgurInfo.Title), Language.GetFormattedString("imgur", LangKey.delete_title, imgurInfo.Hash), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes) { if (result != DialogResult.Yes)
// Should fix Bug #3378699 {
pictureBox1.Image = pictureBox1.ErrorImage; continue;
try {
new PleaseWaitForm().ShowAndWait(ImgurPlugin.Attributes.Name, Language.GetString("imgur", LangKey.communication_wait),
delegate() {
ImgurUtils.DeleteImgurImage(imgurInfo);
}
);
} catch (Exception ex) {
LOG.Warn("Problem communicating with Imgur: ", ex);
}
imgurInfo.Dispose();
} }
// Should fix Bug #3378699
pictureBox1.Image = pictureBox1.ErrorImage;
try {
new PleaseWaitForm().ShowAndWait(ImgurPlugin.Attributes.Name, Language.GetString("imgur", LangKey.communication_wait),
delegate {
ImgurUtils.DeleteImgurImage(imgurInfo);
}
);
} catch (Exception ex) {
Log.Warn("Problem communicating with Imgur: ", ex);
}
imgurInfo.Dispose();
} }
} }
redraw(); Redraw();
} }
private void ClipboardButtonClick(object sender, EventArgs e) { private void ClipboardButtonClick(object sender, EventArgs e) {
StringBuilder links = new StringBuilder(); StringBuilder links = new StringBuilder();
if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) { if (listview_imgur_uploads.SelectedItems.Count > 0) {
for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) { for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++)
{
ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag; ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag;
if (config.UsePageLink) { links.AppendLine(Config.UsePageLink ? imgurInfo.Page : imgurInfo.Original);
links.AppendLine(imgurInfo.Page);
} else {
links.AppendLine(imgurInfo.Original);
}
} }
} }
ClipboardHelper.SetClipboardData(links.ToString()); ClipboardHelper.SetClipboardData(links.ToString());
@ -160,20 +161,20 @@ namespace GreenshotImgurPlugin {
private void ClearHistoryButtonClick(object sender, EventArgs e) { private void ClearHistoryButtonClick(object sender, EventArgs e) {
DialogResult result = MessageBox.Show(Language.GetString("imgur", LangKey.clear_question), "Imgur", MessageBoxButtons.YesNo, MessageBoxIcon.Question); DialogResult result = MessageBox.Show(Language.GetString("imgur", LangKey.clear_question), "Imgur", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes) { if (result == DialogResult.Yes) {
config.runtimeImgurHistory.Clear(); Config.runtimeImgurHistory.Clear();
config.ImgurUploadHistory.Clear(); Config.ImgurUploadHistory.Clear();
IniConfig.Save(); IniConfig.Save();
redraw(); Redraw();
} }
} }
private void FinishedButtonClick(object sender, EventArgs e) private void FinishedButtonClick(object sender, EventArgs e)
{ {
this.Hide(); Hide();
} }
private void OpenButtonClick(object sender, EventArgs e) { private void OpenButtonClick(object sender, EventArgs e) {
if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) { if (listview_imgur_uploads.SelectedItems.Count > 0) {
for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) { for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) {
ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag; ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag;
System.Diagnostics.Process.Start(imgurInfo.Page); System.Diagnostics.Process.Start(imgurInfo.Page);
@ -183,27 +184,23 @@ namespace GreenshotImgurPlugin {
private void listview_imgur_uploads_ColumnClick(object sender, ColumnClickEventArgs e) { private void listview_imgur_uploads_ColumnClick(object sender, ColumnClickEventArgs e) {
// Determine if clicked column is already the column that is being sorted. // Determine if clicked column is already the column that is being sorted.
if (e.Column == columnSorter.SortColumn) { if (e.Column == _columnSorter.SortColumn) {
// Reverse the current sort direction for this column. // Reverse the current sort direction for this column.
if (columnSorter.Order == SortOrder.Ascending) { _columnSorter.Order = _columnSorter.Order == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
columnSorter.Order = SortOrder.Descending;
} else {
columnSorter.Order = SortOrder.Ascending;
}
} else { } else {
// Set the column number that is to be sorted; default to ascending. // Set the column number that is to be sorted; default to ascending.
columnSorter.SortColumn = e.Column; _columnSorter.SortColumn = e.Column;
columnSorter.Order = SortOrder.Ascending; _columnSorter.Order = SortOrder.Ascending;
} }
// Perform the sort with these new sort options. // Perform the sort with these new sort options.
this.listview_imgur_uploads.Sort(); listview_imgur_uploads.Sort();
} }
void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e) private void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e)
{ {
instance = null; _instance = null;
} }
} }
} }

View file

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

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -19,16 +19,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System; using System;
using System.Windows.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.Controls;
namespace GreenshotImgurPlugin { namespace GreenshotImgurPlugin {
/// <summary> /// <summary>
/// Description of PasswordRequestForm. /// Description of PasswordRequestForm.
/// </summary> /// </summary>
public partial class SettingsForm : ImgurForm { public partial class SettingsForm : ImgurForm {
public SettingsForm(ImgurConfiguration config) : base() { public SettingsForm(ImgurConfiguration config)
{
// //
// The InitializeComponent() call is required for Windows Forms designer support. // The InitializeComponent() call is required for Windows Forms designer support.
// //
@ -38,14 +36,10 @@ namespace GreenshotImgurPlugin {
ImgurUtils.LoadHistory(); ImgurUtils.LoadHistory();
if (config.runtimeImgurHistory.Count > 0) { historyButton.Enabled = config.runtimeImgurHistory.Count > 0;
historyButton.Enabled = true;
} else {
historyButton.Enabled = false;
}
} }
void ButtonHistoryClick(object sender, EventArgs e) { private void ButtonHistoryClick(object sender, EventArgs e) {
ImgurHistory.ShowHistory(); ImgurHistory.ShowHistory();
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -32,47 +32,45 @@ namespace GreenshotImgurPlugin {
/// </summary> /// </summary>
[IniSection("Imgur", Description="Greenshot Imgur Plugin configuration")] [IniSection("Imgur", Description="Greenshot Imgur Plugin configuration")]
public class ImgurConfiguration : IniSection { public class ImgurConfiguration : IniSection {
[IniProperty("ImgurApiUrl", Description="Url to Imgur system.", DefaultValue= "http://api.imgur.com/2")]
public string ImgurApiUrl;
[IniProperty("ImgurApi3Url", Description = "Url to Imgur system.", DefaultValue = "https://api.imgur.com/3")] [IniProperty("ImgurApi3Url", Description = "Url to Imgur system.", DefaultValue = "https://api.imgur.com/3")]
public string ImgurApi3Url; public string ImgurApi3Url { get; set; }
[IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")] [IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
public OutputFormat UploadFormat; public OutputFormat UploadFormat { get; set; }
[IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")] [IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]
public int UploadJpegQuality; public int UploadJpegQuality { get; set; }
[IniProperty("UploadReduceColors", Description="Reduce color amount of the uploaded image to 256", DefaultValue="False")] [IniProperty("UploadReduceColors", Description="Reduce color amount of the uploaded image to 256", DefaultValue="False")]
public bool UploadReduceColors; public bool UploadReduceColors { get; set; }
[IniProperty("CopyLinkToClipboard", Description = "Copy the link, which one is controlled by the UsePageLink, on the clipboard", DefaultValue = "True")] [IniProperty("CopyLinkToClipboard", Description = "Copy the link, which one is controlled by the UsePageLink, on the clipboard", DefaultValue = "True")]
public bool CopyLinkToClipboard; public bool CopyLinkToClipboard { get; set; }
[IniProperty("UsePageLink", Description = "Use pagelink instead of direct link on the clipboard", DefaultValue = "False")] [IniProperty("UsePageLink", Description = "Use pagelink instead of direct link on the clipboard", DefaultValue = "False")]
public bool UsePageLink; public bool UsePageLink { get; set; }
[IniProperty("AnonymousAccess", Description = "Use anonymous access to Imgur", DefaultValue="true")] [IniProperty("AnonymousAccess", Description = "Use anonymous access to Imgur", DefaultValue="true")]
public bool AnonymousAccess; public bool AnonymousAccess { get; set; }
[IniProperty("RefreshToken", Description = "Imgur refresh Token", Encrypted = true, ExcludeIfNull = true)] [IniProperty("RefreshToken", Description = "Imgur refresh Token", Encrypted = true, ExcludeIfNull = true)]
public string RefreshToken; public string RefreshToken { get; set; }
/// <summary> /// <summary>
/// AccessToken, not stored /// AccessToken, not stored
/// </summary> /// </summary>
public string AccessToken; public string AccessToken { get; set; }
/// <summary> /// <summary>
/// AccessTokenExpires, not stored /// AccessTokenExpires, not stored
/// </summary> /// </summary>
public DateTimeOffset AccessTokenExpires; public DateTimeOffset AccessTokenExpires { get; set; }
[IniProperty("AddTitle", Description = "Is the title passed on to Imgur", DefaultValue = "False")] [IniProperty("AddTitle", Description = "Is the title passed on to Imgur", DefaultValue = "False")]
public bool AddTitle; public bool AddTitle { get; set; }
[IniProperty("AddFilename", Description = "Is the filename passed on to Imgur", DefaultValue = "False")] [IniProperty("AddFilename", Description = "Is the filename passed on to Imgur", DefaultValue = "False")]
public bool AddFilename; public bool AddFilename { get; set; }
[IniProperty("FilenamePattern", Description = "Filename for the Imgur upload", DefaultValue = "${capturetime:d\"yyyyMMdd-HHmm\"}")] [IniProperty("FilenamePattern", Description = "Filename for the Imgur upload", DefaultValue = "${capturetime:d\"yyyyMMdd-HHmm\"}")]
public string FilenamePattern; public string FilenamePattern { get; set; }
[IniProperty("ImgurUploadHistory", Description="Imgur upload history (ImgurUploadHistory.hash=deleteHash)")] [IniProperty("ImgurUploadHistory", Description="Imgur upload history (ImgurUploadHistory.hash=deleteHash)")]
public Dictionary<string, string> ImgurUploadHistory; public Dictionary<string, string> ImgurUploadHistory { get; set; }
// Not stored, only run-time! // Not stored, only run-time!
public Dictionary<string, ImgurInfo> runtimeImgurHistory = new Dictionary<string, ImgurInfo>(); public Dictionary<string, ImgurInfo> runtimeImgurHistory = new Dictionary<string, ImgurInfo>();
public int Credits { public int Credits {
@ -100,7 +98,7 @@ namespace GreenshotImgurPlugin {
SettingsForm settingsForm = null; SettingsForm settingsForm = null;
new PleaseWaitForm().ShowAndWait(ImgurPlugin.Attributes.Name, Language.GetString("imgur", LangKey.communication_wait), new PleaseWaitForm().ShowAndWait(ImgurPlugin.Attributes.Name, Language.GetString("imgur", LangKey.communication_wait),
delegate() { delegate {
settingsForm = new SettingsForm(this); settingsForm = new SettingsForm(this);
} }
); );

View file

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

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,7 +20,6 @@
*/ */
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using Greenshot.IniFile;
using Greenshot.Plugin; using Greenshot.Plugin;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
@ -29,25 +28,15 @@ namespace GreenshotImgurPlugin {
/// Description of ImgurDestination. /// Description of ImgurDestination.
/// </summary> /// </summary>
public class ImgurDestination : AbstractDestination { public class ImgurDestination : AbstractDestination {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurDestination)); private readonly ImgurPlugin _plugin;
private static ImgurConfiguration config = IniConfig.GetIniSection<ImgurConfiguration>();
private ImgurPlugin plugin = null;
public ImgurDestination(ImgurPlugin plugin) { public ImgurDestination(ImgurPlugin plugin) {
this.plugin = plugin; _plugin = plugin;
} }
public override string Designation { public override string Designation => "Imgur";
get {
return "Imgur";
}
}
public override string Description { public override string Description => Language.GetString("imgur", LangKey.upload_menu_item);
get {
return Language.GetString("imgur", LangKey.upload_menu_item);
}
}
public override Image DisplayIcon { public override Image DisplayIcon {
get { get {
@ -57,10 +46,10 @@ namespace GreenshotImgurPlugin {
} }
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(Designation, Description);
string uploadURL = null; string uploadUrl;
exportInformation.ExportMade = plugin.Upload(captureDetails, surface, out uploadURL); exportInformation.ExportMade = _plugin.Upload(captureDetails, surface, out uploadUrl);
exportInformation.Uri = uploadURL; exportInformation.Uri = uploadUrl;
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surface);
return exportInformation; return exportInformation;
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -27,8 +27,9 @@ namespace GreenshotImgurPlugin
/// <summary> /// <summary>
/// Description of ImgurInfo. /// Description of ImgurInfo.
/// </summary> /// </summary>
public class ImgurInfo : IDisposable { public class ImgurInfo : IDisposable
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurInfo)); {
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurInfo));
public string Hash public string Hash
{ {
@ -36,11 +37,13 @@ namespace GreenshotImgurPlugin
set; set;
} }
private string deleteHash; private string _deleteHash;
public string DeleteHash { public string DeleteHash
get {return deleteHash;} {
set { get { return _deleteHash; }
deleteHash = value; set
{
_deleteHash = value;
DeletePage = "https://imgur.com/delete/" + value; DeletePage = "https://imgur.com/delete/" + value;
} }
} }
@ -93,25 +96,23 @@ namespace GreenshotImgurPlugin
set; set;
} }
private Image image; private Image _image;
public Image Image { public Image Image
get {return image;} {
set { get { return _image; }
if (image != null) { set
image.Dispose(); {
} _image?.Dispose();
image = value; _image = value;
} }
} }
public ImgurInfo() {
}
/// <summary> /// <summary>
/// The public accessible Dispose /// The public accessible Dispose
/// Will call the GarbageCollector to SuppressFinalize, preventing being cleaned twice /// Will call the GarbageCollector to SuppressFinalize, preventing being cleaned twice
/// </summary> /// </summary>
public void Dispose() { public void Dispose()
{
Dispose(true); Dispose(true);
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
@ -121,16 +122,17 @@ namespace GreenshotImgurPlugin
/// When disposing==true all non-managed resources should be freed too! /// When disposing==true all non-managed resources should be freed too!
/// </summary> /// </summary>
/// <param name="disposing"></param> /// <param name="disposing"></param>
protected virtual void Dispose(bool disposing) { protected virtual void Dispose(bool disposing)
if (disposing) { {
if (image != null) { if (disposing)
image.Dispose(); {
} _image?.Dispose();
} }
image = null; _image = null;
} }
public static ImgurInfo ParseResponse(string response) { public static ImgurInfo ParseResponse(string response)
LOG.Debug(response); {
Log.Debug(response);
// This is actually a hack for BUG-1695 // This is actually a hack for BUG-1695
// The problem is the (C) sign, we send it HTML encoded "&reg;" to Imgur and get it HTML encoded in the XML back // The problem is the (C) sign, we send it HTML encoded "&reg;" to Imgur and get it HTML encoded in the XML back
// Added all the encodings I found quickly, I guess these are not all... but it should fix the issue for now. // Added all the encodings I found quickly, I guess these are not all... but it should fix the issue for now.
@ -142,35 +144,41 @@ namespace GreenshotImgurPlugin
response = response.Replace("&reg;", "&#174;"); response = response.Replace("&reg;", "&#174;");
ImgurInfo imgurInfo = new ImgurInfo(); ImgurInfo imgurInfo = new ImgurInfo();
try { try
{
XmlDocument doc = new XmlDocument(); XmlDocument doc = new XmlDocument();
doc.LoadXml(response); doc.LoadXml(response);
XmlNodeList nodes = doc.GetElementsByTagName("id"); XmlNodeList nodes = doc.GetElementsByTagName("id");
if(nodes.Count > 0) { if (nodes.Count > 0)
imgurInfo.Hash = nodes.Item(0).InnerText; {
imgurInfo.Hash = nodes.Item(0)?.InnerText;
} }
nodes = doc.GetElementsByTagName("hash"); nodes = doc.GetElementsByTagName("hash");
if (nodes.Count > 0) if (nodes.Count > 0)
{ {
imgurInfo.Hash = nodes.Item(0).InnerText; imgurInfo.Hash = nodes.Item(0)?.InnerText;
} }
nodes = doc.GetElementsByTagName("deletehash"); nodes = doc.GetElementsByTagName("deletehash");
if(nodes.Count > 0) { if (nodes.Count > 0)
imgurInfo.DeleteHash = nodes.Item(0).InnerText; {
imgurInfo.DeleteHash = nodes.Item(0)?.InnerText;
} }
nodes = doc.GetElementsByTagName("type"); nodes = doc.GetElementsByTagName("type");
if(nodes.Count > 0) { if (nodes.Count > 0)
imgurInfo.ImageType = nodes.Item(0).InnerText; {
imgurInfo.ImageType = nodes.Item(0)?.InnerText;
} }
nodes = doc.GetElementsByTagName("title"); nodes = doc.GetElementsByTagName("title");
if(nodes.Count > 0) { if (nodes.Count > 0)
imgurInfo.Title = nodes.Item(0).InnerText; {
imgurInfo.Title = nodes.Item(0)?.InnerText;
} }
nodes = doc.GetElementsByTagName("datetime"); nodes = doc.GetElementsByTagName("datetime");
if(nodes.Count > 0) { if (nodes.Count > 0)
{
// Version 3 has seconds since Epoch // Version 3 has seconds since Epoch
double secondsSince; double secondsSince;
if (double.TryParse(nodes.Item(0).InnerText, out secondsSince)) if (double.TryParse(nodes.Item(0)?.InnerText, out secondsSince))
{ {
var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime; imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime;
@ -179,35 +187,30 @@ namespace GreenshotImgurPlugin
nodes = doc.GetElementsByTagName("original"); nodes = doc.GetElementsByTagName("original");
if (nodes.Count > 0) if (nodes.Count > 0)
{ {
imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:"); imgurInfo.Original = nodes.Item(0)?.InnerText.Replace("http:", "https:");
} }
// Version 3 API only has Link // Version 3 API only has Link
nodes = doc.GetElementsByTagName("link"); nodes = doc.GetElementsByTagName("link");
if (nodes.Count > 0) if (nodes.Count > 0)
{ {
imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:"); imgurInfo.Original = nodes.Item(0)?.InnerText.Replace("http:", "https:");
} }
nodes = doc.GetElementsByTagName("imgur_page"); nodes = doc.GetElementsByTagName("imgur_page");
if (nodes.Count > 0) if (nodes.Count > 0)
{ {
imgurInfo.Page = nodes.Item(0).InnerText.Replace("http:", "https:"); imgurInfo.Page = nodes.Item(0)?.InnerText.Replace("http:", "https:");
} }
else else
{ {
// Version 3 doesn't have a page link in the response // Version 3 doesn't have a page link in the response
imgurInfo.Page = string.Format("https://imgur.com/{0}", imgurInfo.Hash); imgurInfo.Page = $"https://imgur.com/{imgurInfo.Hash}";
} }
nodes = doc.GetElementsByTagName("small_square"); nodes = doc.GetElementsByTagName("small_square");
if(nodes.Count > 0) { imgurInfo.SmallSquare = nodes.Count > 0 ? nodes.Item(0)?.InnerText : $"http://i.imgur.com/{imgurInfo.Hash}s.png";
imgurInfo.SmallSquare = nodes.Item(0).InnerText; }
} catch (Exception e)
nodes = doc.GetElementsByTagName("large_thumbnail"); {
if(nodes.Count > 0) Log.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
{
imgurInfo.LargeThumbnail = nodes.Item(0).InnerText.Replace("http:", "https:");
}
} catch(Exception e) {
LOG.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
} }
return imgurInfo; return imgurInfo;
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -35,13 +35,13 @@ namespace GreenshotImgurPlugin {
/// This is the ImgurPlugin code /// This is the ImgurPlugin code
/// </summary> /// </summary>
public class ImgurPlugin : IGreenshotPlugin { public class ImgurPlugin : IGreenshotPlugin {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurPlugin)); private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurPlugin));
private static ImgurConfiguration config; private static ImgurConfiguration _config;
public static PluginAttribute Attributes; public static PluginAttribute Attributes;
private IGreenshotHost host; private IGreenshotHost _host;
private ComponentResourceManager resources; private ComponentResourceManager _resources;
private ToolStripMenuItem historyMenuItem = null; private ToolStripMenuItem _historyMenuItem;
private ToolStripMenuItem itemPlugInConfig; private ToolStripMenuItem _itemPlugInConfig;
public void Dispose() { public void Dispose() {
Dispose(true); Dispose(true);
@ -50,20 +50,17 @@ namespace GreenshotImgurPlugin {
protected virtual void Dispose(bool disposing) { protected virtual void Dispose(bool disposing) {
if (disposing) { if (disposing) {
if (historyMenuItem != null) { if (_historyMenuItem != null) {
historyMenuItem.Dispose(); _historyMenuItem.Dispose();
historyMenuItem = null; _historyMenuItem = null;
} }
if (itemPlugInConfig != null) { if (_itemPlugInConfig != null) {
itemPlugInConfig.Dispose(); _itemPlugInConfig.Dispose();
itemPlugInConfig = null; _itemPlugInConfig = null;
} }
} }
} }
public ImgurPlugin() {
}
public IEnumerable<IDestination> Destinations() { public IEnumerable<IDestination> Destinations() {
yield return new ImgurDestination(this); yield return new ImgurDestination(this);
} }
@ -75,114 +72,112 @@ namespace GreenshotImgurPlugin {
/// <summary> /// <summary>
/// Implementation of the IGreenshotPlugin.Initialize /// Implementation of the IGreenshotPlugin.Initialize
/// </summary> /// </summary>
/// <param name="host">Use the IGreenshotPluginHost interface to register events</param> /// <param name="pluginHost">Use the IGreenshotPluginHost interface to register events</param>
/// <param name="captureHost">Use the ICaptureHost interface to register in the MainContextMenu</param> /// <param name="myAttributes">My own attributes</param>
/// <param name="pluginAttribute">My own attributes</param>
/// <returns>true if plugin is initialized, false if not (doesn't show)</returns> /// <returns>true if plugin is initialized, false if not (doesn't show)</returns>
public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) { public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) {
this.host = (IGreenshotHost)pluginHost; _host = pluginHost;
Attributes = myAttributes; Attributes = myAttributes;
// Get configuration // Get configuration
config = IniConfig.GetIniSection<ImgurConfiguration>(); _config = IniConfig.GetIniSection<ImgurConfiguration>();
resources = new ComponentResourceManager(typeof(ImgurPlugin)); _resources = new ComponentResourceManager(typeof(ImgurPlugin));
ToolStripMenuItem itemPlugInRoot = new ToolStripMenuItem("Imgur");
itemPlugInRoot.Image = (Image)resources.GetObject("Imgur");
historyMenuItem = new ToolStripMenuItem(Language.GetString("imgur", LangKey.history)); ToolStripMenuItem itemPlugInRoot = new ToolStripMenuItem("Imgur")
historyMenuItem.Tag = host; {
historyMenuItem.Click += delegate { Image = (Image) _resources.GetObject("Imgur")
};
_historyMenuItem = new ToolStripMenuItem(Language.GetString("imgur", LangKey.history))
{
Tag = _host
};
_historyMenuItem.Click += delegate {
ImgurHistory.ShowHistory(); ImgurHistory.ShowHistory();
}; };
itemPlugInRoot.DropDownItems.Add(historyMenuItem); itemPlugInRoot.DropDownItems.Add(_historyMenuItem);
itemPlugInConfig = new ToolStripMenuItem(Language.GetString("imgur", LangKey.configure)); _itemPlugInConfig = new ToolStripMenuItem(Language.GetString("imgur", LangKey.configure))
itemPlugInConfig.Tag = host; {
itemPlugInConfig.Click += delegate { Tag = _host
config.ShowConfigDialog();
}; };
itemPlugInRoot.DropDownItems.Add(itemPlugInConfig); _itemPlugInConfig.Click += delegate {
_config.ShowConfigDialog();
};
itemPlugInRoot.DropDownItems.Add(_itemPlugInConfig);
PluginUtils.AddToContextMenu(host, itemPlugInRoot); PluginUtils.AddToContextMenu(_host, itemPlugInRoot);
Language.LanguageChanged += new LanguageChangedHandler(OnLanguageChanged); Language.LanguageChanged += OnLanguageChanged;
// retrieve history in the background // retrieve history in the background
Thread backgroundTask = new Thread (new ThreadStart(CheckHistory)); Thread backgroundTask = new Thread(CheckHistory)
backgroundTask.Name = "Imgur History"; {
backgroundTask.IsBackground = true; Name = "Imgur History",
IsBackground = true
};
backgroundTask.SetApartmentState(ApartmentState.STA); backgroundTask.SetApartmentState(ApartmentState.STA);
backgroundTask.Start(); backgroundTask.Start();
return true; return true;
} }
public void OnLanguageChanged(object sender, EventArgs e) { public void OnLanguageChanged(object sender, EventArgs e) {
if (itemPlugInConfig != null) { if (_itemPlugInConfig != null) {
itemPlugInConfig.Text = Language.GetString("imgur", LangKey.configure); _itemPlugInConfig.Text = Language.GetString("imgur", LangKey.configure);
} }
if (historyMenuItem != null) { if (_historyMenuItem != null) {
historyMenuItem.Text = Language.GetString("imgur", LangKey.history); _historyMenuItem.Text = Language.GetString("imgur", LangKey.history);
} }
} }
private void CheckHistory() { private void CheckHistory() {
try { try {
ImgurUtils.LoadHistory(); ImgurUtils.LoadHistory();
host.GreenshotForm.BeginInvoke((MethodInvoker)delegate { _host.GreenshotForm.BeginInvoke((MethodInvoker)delegate {
if (config.ImgurUploadHistory.Count > 0) { if (_config.ImgurUploadHistory.Count > 0) {
historyMenuItem.Enabled = true; _historyMenuItem.Enabled = true;
} else { } else {
historyMenuItem.Enabled = false; _historyMenuItem.Enabled = false;
} }
}); });
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error("Error loading history", ex); Log.Error("Error loading history", ex);
}; }
} }
public virtual void Shutdown() { public virtual void Shutdown() {
LOG.Debug("Imgur Plugin shutdown."); Log.Debug("Imgur Plugin shutdown.");
Language.LanguageChanged -= new LanguageChangedHandler(OnLanguageChanged); Language.LanguageChanged -= OnLanguageChanged;
} }
/// <summary> /// <summary>
/// Implementation of the IPlugin.Configure /// Implementation of the IPlugin.Configure
/// </summary> /// </summary>
public virtual void Configure() { public virtual void Configure() {
config.ShowConfigDialog(); _config.ShowConfigDialog();
} }
/// <summary>
/// This will be called when Greenshot is shutting down
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Closing(object sender, FormClosingEventArgs e) {
LOG.Debug("Application closing, de-registering Imgur Plugin!");
Shutdown();
}
/// <summary> /// <summary>
/// Upload the capture to imgur /// Upload the capture to imgur
/// </summary> /// </summary>
/// <param name="captureDetails"></param> /// <param name="captureDetails">ICaptureDetails</param>
/// <param name="image"></param> /// <param name="surfaceToUpload">ISurface</param>
/// <param name="uploadURL">out string for the url</param> /// <param name="uploadUrl">out string for the url</param>
/// <returns>true if the upload succeeded</returns> /// <returns>true if the upload succeeded</returns>
public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadURL) { public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) {
SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors); SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, _config.UploadReduceColors);
try { try {
string filename = Path.GetFileName(FilenameHelper.GetFilenameFromPattern(config.FilenamePattern, config.UploadFormat, captureDetails)); string filename = Path.GetFileName(FilenameHelper.GetFilenameFromPattern(_config.FilenamePattern, _config.UploadFormat, captureDetails));
ImgurInfo imgurInfo = null; ImgurInfo imgurInfo = null;
// Run upload in the background // Run upload in the background
new PleaseWaitForm().ShowAndWait("Imgur plug-in", Language.GetString("imgur", LangKey.communication_wait), new PleaseWaitForm().ShowAndWait("Imgur plug-in", Language.GetString("imgur", LangKey.communication_wait),
delegate() { delegate
{
imgurInfo = ImgurUtils.UploadToImgur(surfaceToUpload, outputSettings, captureDetails.Title, filename); imgurInfo = ImgurUtils.UploadToImgur(surfaceToUpload, outputSettings, captureDetails.Title, filename);
if (imgurInfo != null && config.AnonymousAccess) { if (imgurInfo != null && _config.AnonymousAccess) {
LOG.InfoFormat("Storing imgur upload for hash {0} and delete hash {1}", imgurInfo.Hash, imgurInfo.DeleteHash); Log.InfoFormat("Storing imgur upload for hash {0} and delete hash {1}", imgurInfo.Hash, imgurInfo.DeleteHash);
config.ImgurUploadHistory.Add(imgurInfo.Hash, imgurInfo.DeleteHash); _config.ImgurUploadHistory.Add(imgurInfo.Hash, imgurInfo.DeleteHash);
config.runtimeImgurHistory.Add(imgurInfo.Hash, imgurInfo); _config.runtimeImgurHistory.Add(imgurInfo.Hash, imgurInfo);
CheckHistory(); CheckHistory();
} }
} }
@ -195,34 +190,34 @@ namespace GreenshotImgurPlugin {
} }
IniConfig.Save(); IniConfig.Save();
if (config.UsePageLink) if (_config.UsePageLink)
{ {
uploadURL = imgurInfo.Page; uploadUrl = imgurInfo.Page;
} }
else else
{ {
uploadURL = imgurInfo.Original; uploadUrl = imgurInfo.Original;
} }
if (!string.IsNullOrEmpty(uploadURL) && config.CopyLinkToClipboard) if (!string.IsNullOrEmpty(uploadUrl) && _config.CopyLinkToClipboard)
{ {
try try
{ {
ClipboardHelper.SetClipboardData(uploadURL); ClipboardHelper.SetClipboardData(uploadUrl);
} }
catch (Exception ex) catch (Exception ex)
{ {
LOG.Error("Can't write to clipboard: ", ex); Log.Error("Can't write to clipboard: ", ex);
uploadURL = null; uploadUrl = null;
} }
} }
return true; return true;
} }
} catch (Exception e) { } catch (Exception e) {
LOG.Error("Error uploading.", e); Log.Error("Error uploading.", e);
MessageBox.Show(Language.GetString("imgur", LangKey.upload_failure) + " " + e.Message); MessageBox.Show(Language.GetString("imgur", LangKey.upload_failure) + " " + e.Message);
} }
uploadURL = null; uploadUrl = null;
return false; return false;
} }
} }

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -32,7 +32,7 @@ namespace GreenshotImgurPlugin {
/// Description of ImgurUtils. /// Description of ImgurUtils.
/// </summary> /// </summary>
public static class ImgurUtils { public static class ImgurUtils {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurUtils)); private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurUtils));
private const string SmallUrlPattern = "http://i.imgur.com/{0}s.jpg"; private const string SmallUrlPattern = "http://i.imgur.com/{0}s.jpg";
private static readonly ImgurConfiguration Config = IniConfig.GetIniSection<ImgurConfiguration>(); private static readonly ImgurConfiguration Config = IniConfig.GetIniSection<ImgurConfiguration>();
private const string AuthUrlPattern = "https://api.imgur.com/oauth2/authorize?response_type=code&client_id={ClientId}&redirect_uri={RedirectUrl}&state={State}"; private const string AuthUrlPattern = "https://api.imgur.com/oauth2/authorize?response_type=code&client_id={ClientId}&redirect_uri={RedirectUrl}&state={State}";
@ -64,7 +64,7 @@ namespace GreenshotImgurPlugin {
RetrieveImgurThumbnail(imgurInfo); RetrieveImgurThumbnail(imgurInfo);
Config.runtimeImgurHistory.Add(hash, imgurInfo); Config.runtimeImgurHistory.Add(hash, imgurInfo);
} else { } else {
LOG.DebugFormat("Deleting not found ImgUr {0} from config.", hash); Log.DebugFormat("Deleting not found ImgUr {0} from config.", hash);
Config.ImgurUploadHistory.Remove(hash); Config.ImgurUploadHistory.Remove(hash);
saveNeeded = true; saveNeeded = true;
} }
@ -74,16 +74,16 @@ namespace GreenshotImgurPlugin {
HttpWebResponse response = ((HttpWebResponse)wE.Response); HttpWebResponse response = ((HttpWebResponse)wE.Response);
// Image no longer available // Image no longer available
if (response.StatusCode == HttpStatusCode.Redirect) { if (response.StatusCode == HttpStatusCode.Redirect) {
LOG.InfoFormat("ImgUr image for hash {0} is no longer available", hash); Log.InfoFormat("ImgUr image for hash {0} is no longer available", hash);
Config.ImgurUploadHistory.Remove(hash); Config.ImgurUploadHistory.Remove(hash);
redirected = true; redirected = true;
} }
} }
if (!redirected) { if (!redirected) {
LOG.Error("Problem loading ImgUr history for hash " + hash, wE); Log.Error("Problem loading ImgUr history for hash " + hash, wE);
} }
} catch (Exception e) { } catch (Exception e) {
LOG.Error("Problem loading ImgUr history for hash " + hash, e); Log.Error("Problem loading ImgUr history for hash " + hash, e);
} }
} }
if (saveNeeded) { if (saveNeeded) {
@ -119,7 +119,7 @@ namespace GreenshotImgurPlugin {
if (filename != null && Config.AddFilename) { if (filename != null && Config.AddFilename) {
otherParameters.Add("name", filename); otherParameters.Add("name", filename);
} }
string responseString; string responseString = null;
if (Config.AnonymousAccess) { if (Config.AnonymousAccess) {
// add key, we only use the other parameters for the AnonymousAccess // add key, we only use the other parameters for the AnonymousAccess
//otherParameters.Add("key", IMGUR_ANONYMOUS_API_KEY); //otherParameters.Add("key", IMGUR_ANONYMOUS_API_KEY);
@ -133,32 +133,40 @@ namespace GreenshotImgurPlugin {
ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings); ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings);
} }
using (WebResponse response = webRequest.GetResponse()) { using (WebResponse response = webRequest.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) { {
responseString = reader.ReadToEnd();
}
LogRateLimitInfo(response); LogRateLimitInfo(response);
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream, true))
{
responseString = reader.ReadToEnd();
}
}
} }
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error("Upload to imgur gave an exeption: ", ex); Log.Error("Upload to imgur gave an exeption: ", ex);
throw; throw;
} }
} else { } else {
var oauth2Settings = new OAuth2Settings(); var oauth2Settings = new OAuth2Settings
oauth2Settings.AuthUrlPattern = AuthUrlPattern; {
oauth2Settings.TokenUrl = TokenUrl; AuthUrlPattern = AuthUrlPattern,
oauth2Settings.RedirectUrl = "https://imgur.com"; TokenUrl = TokenUrl,
oauth2Settings.CloudServiceName = "Imgur"; RedirectUrl = "https://imgur.com",
oauth2Settings.ClientId = ImgurCredentials.CONSUMER_KEY; CloudServiceName = "Imgur",
oauth2Settings.ClientSecret = ImgurCredentials.CONSUMER_SECRET; ClientId = ImgurCredentials.CONSUMER_KEY,
oauth2Settings.AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser; ClientSecret = ImgurCredentials.CONSUMER_SECRET,
oauth2Settings.BrowserSize = new Size(680, 880); AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser,
BrowserSize = new Size(680, 880),
RefreshToken = Config.RefreshToken,
AccessToken = Config.AccessToken,
AccessTokenExpires = Config.AccessTokenExpires
};
// Copy the settings from the config, which is kept in memory and on the disk // Copy the settings from the config, which is kept in memory and on the disk
oauth2Settings.RefreshToken = Config.RefreshToken;
oauth2Settings.AccessToken = Config.AccessToken;
oauth2Settings.AccessTokenExpires = Config.AccessTokenExpires;
try try
{ {
@ -179,6 +187,10 @@ namespace GreenshotImgurPlugin {
IniConfig.Save(); IniConfig.Save();
} }
} }
if (string.IsNullOrEmpty(responseString))
{
return null;
}
return ImgurInfo.ParseResponse(responseString); return ImgurInfo.ParseResponse(responseString);
} }
@ -188,19 +200,20 @@ namespace GreenshotImgurPlugin {
/// <param name="imgurInfo"></param> /// <param name="imgurInfo"></param>
public static void RetrieveImgurThumbnail(ImgurInfo imgurInfo) { public static void RetrieveImgurThumbnail(ImgurInfo imgurInfo) {
if (imgurInfo.SmallSquare == null) { if (imgurInfo.SmallSquare == null) {
LOG.Warn("Imgur URL was null, not retrieving thumbnail."); Log.Warn("Imgur URL was null, not retrieving thumbnail.");
return; return;
} }
LOG.InfoFormat("Retrieving Imgur image for {0} with url {1}", imgurInfo.Hash, imgurInfo.SmallSquare); Log.InfoFormat("Retrieving Imgur image for {0} with url {1}", imgurInfo.Hash, imgurInfo.SmallSquare);
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(string.Format(SmallUrlPattern, imgurInfo.Hash), HTTPMethod.GET); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(string.Format(SmallUrlPattern, imgurInfo.Hash), HTTPMethod.GET);
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest); // Not for getting the thumbnail, in anonymous modus
//SetClientId(webRequest);
using (WebResponse response = webRequest.GetResponse()) { using (WebResponse response = webRequest.GetResponse()) {
LogRateLimitInfo(response); LogRateLimitInfo(response);
Stream responseStream = response.GetResponseStream(); Stream responseStream = response.GetResponseStream();
if (responseStream != null) if (responseStream != null)
{ {
imgurInfo.Image = Image.FromStream(responseStream); imgurInfo.Image = ImageHelper.FromStream(responseStream);
} }
} }
} }
@ -212,17 +225,22 @@ namespace GreenshotImgurPlugin {
/// <param name="deleteHash"></param> /// <param name="deleteHash"></param>
/// <returns>ImgurInfo</returns> /// <returns>ImgurInfo</returns>
public static ImgurInfo RetrieveImgurInfo(string hash, string deleteHash) { public static ImgurInfo RetrieveImgurInfo(string hash, string deleteHash) {
string url = Config.ImgurApiUrl + "/image/" + hash; string url = Config.ImgurApi3Url + "/image/" + hash + ".xml";
LOG.InfoFormat("Retrieving Imgur info for {0} with url {1}", hash, url); Log.InfoFormat("Retrieving Imgur info for {0} with url {1}", hash, url);
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET);
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest); SetClientId(webRequest);
string responseString; string responseString = null;
try { try {
using (WebResponse response = webRequest.GetResponse()) { using (WebResponse response = webRequest.GetResponse()) {
LogRateLimitInfo(response); LogRateLimitInfo(response);
using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) { var responseStream = response.GetResponseStream();
responseString = reader.ReadToEnd(); if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream, true))
{
responseString = reader.ReadToEnd();
}
} }
} }
} catch (WebException wE) { } catch (WebException wE) {
@ -233,9 +251,13 @@ namespace GreenshotImgurPlugin {
} }
throw; throw;
} }
LOG.Debug(responseString); ImgurInfo imgurInfo = null;
ImgurInfo imgurInfo = ImgurInfo.ParseResponse(responseString); if (responseString != null)
imgurInfo.DeleteHash = deleteHash; {
Log.Debug(responseString);
imgurInfo = ImgurInfo.ParseResponse(responseString);
imgurInfo.DeleteHash = deleteHash;
}
return imgurInfo; return imgurInfo;
} }
@ -244,21 +266,26 @@ namespace GreenshotImgurPlugin {
/// </summary> /// </summary>
/// <param name="imgurInfo"></param> /// <param name="imgurInfo"></param>
public static void DeleteImgurImage(ImgurInfo imgurInfo) { public static void DeleteImgurImage(ImgurInfo imgurInfo) {
LOG.InfoFormat("Deleting Imgur image for {0}", imgurInfo.DeleteHash); Log.InfoFormat("Deleting Imgur image for {0}", imgurInfo.DeleteHash);
try { try {
string url = Config.ImgurApiUrl + "/delete/" + imgurInfo.DeleteHash; string url = Config.ImgurApi3Url + "/image/" + imgurInfo.DeleteHash + ".xml";
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.DELETE);
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest); SetClientId(webRequest);
string responseString; string responseString = null;
using (WebResponse response = webRequest.GetResponse()) { using (WebResponse response = webRequest.GetResponse()) {
LogRateLimitInfo(response); LogRateLimitInfo(response);
using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) { var responseStream = response.GetResponseStream();
responseString = reader.ReadToEnd(); if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream, true))
{
responseString = reader.ReadToEnd();
}
} }
} }
LOG.InfoFormat("Delete result: {0}", responseString); Log.InfoFormat("Delete result: {0}", responseString);
} catch (WebException wE) { } catch (WebException wE) {
// Allow "Bad request" this means we already deleted it // Allow "Bad request" this means we already deleted it
if (wE.Status == WebExceptionStatus.ProtocolError) { if (wE.Status == WebExceptionStatus.ProtocolError) {
@ -280,7 +307,7 @@ namespace GreenshotImgurPlugin {
/// <param name="key"></param> /// <param name="key"></param>
private static void LogHeader(IDictionary<string, string> nameValues, string key) { private static void LogHeader(IDictionary<string, string> nameValues, string key) {
if (nameValues.ContainsKey(key)) { if (nameValues.ContainsKey(key)) {
LOG.InfoFormat("key={0}", nameValues[key]); Log.InfoFormat("key={0}", nameValues[key]);
} }
} }

View file

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

View file

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

View file

@ -174,7 +174,7 @@ namespace GreenshotPlugin.Core {
[IniProperty("ExcludeDestinations", Description = "Comma separated list of destinations which should be disabled.")] [IniProperty("ExcludeDestinations", Description = "Comma separated list of destinations which should be disabled.")]
public List<string> ExcludeDestinations; public List<string> ExcludeDestinations;
[IniProperty("UpdateCheckInterval", Description="How many days between every update check? (0=no checks)", DefaultValue="1")] [IniProperty("UpdateCheckInterval", Description="How many days between every update check? (0=no checks)", DefaultValue="14")]
public int UpdateCheckInterval; public int UpdateCheckInterval;
[IniProperty("LastUpdateCheck", Description="Last update check")] [IniProperty("LastUpdateCheck", Description="Last update check")]
public DateTime LastUpdateCheck; public DateTime LastUpdateCheck;
@ -430,12 +430,18 @@ namespace GreenshotPlugin.Core {
// Store version, this can be used later to fix settings after an update // Store version, this can be used later to fix settings after an update
LastSaveWithVersion = Assembly.GetEntryAssembly().GetName().Version.ToString(); LastSaveWithVersion = Assembly.GetEntryAssembly().GetName().Version.ToString();
} catch { } catch {
// Ignore
} }
// Disable the AutoReduceColors as it causes issues with Mozzila applications and some others // Disable the AutoReduceColors as it causes issues with Mozzila applications and some others
OutputFileAutoReduceColors = false; OutputFileAutoReduceColors = false;
} }
// Force update check to 14 days, but only if it's not turned off
if (UpdateCheckInterval < 7 && UpdateCheckInterval > 0)
{
UpdateCheckInterval = 14;
}
// Enable OneNote if upgrading from 1.1 // Enable OneNote if upgrading from 1.1
if(ExcludeDestinations != null && ExcludeDestinations.Contains("OneNote")) { if(ExcludeDestinations != null && ExcludeDestinations.Contains("OneNote")) {
if(LastSaveWithVersion != null && LastSaveWithVersion.StartsWith("1.1")) { if(LastSaveWithVersion != null && LastSaveWithVersion.StartsWith("1.1")) {

View file

@ -0,0 +1,29 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotPlugin.Core
{
public delegate TResult Func<out TResult>();
public delegate TResult Func<in T, out TResult>(T arg);
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
}

File diff suppressed because it is too large Load diff

View file

@ -41,10 +41,6 @@ namespace GreenshotPlugin.Core {
public string Link { public string Link {
get {return _link;} get {return _link;}
} }
private readonly string _directLink;
public string DirectLink {
get {return _directLink;}
}
private Version _version; private Version _version;
public Version Version { public Version Version {
get {return _version;} get {return _version;}
@ -85,11 +81,10 @@ namespace GreenshotPlugin.Core {
} }
} }
public SourceforgeFile(string file, string pubdate, string link, string directLink) { public SourceforgeFile(string file, string pubdate, string link) {
this._file = file; this._file = file;
DateTime.TryParse(pubdate, out _pubdate); DateTime.TryParse(pubdate, out _pubdate);
this._link = link; this._link = link;
this._directLink = directLink;
} }
} }
/// <summary> /// <summary>
@ -180,9 +175,6 @@ namespace GreenshotPlugin.Core {
string subdir = match.Groups[2].Value; string subdir = match.Groups[2].Value;
string type = match.Groups[3].Value; string type = match.Groups[3].Value;
string file = match.Groups[4].Value; string file = match.Groups[4].Value;
// !!! Change this to the mirror !!!
string mirror = "kent";
string directLink = Uri.EscapeUriString("http://"+mirror+".dl.sourceforge.net/project/"+project+"/"+subdir+"/"+type+"/"+file);
Dictionary<string, SourceforgeFile> filesForType; Dictionary<string, SourceforgeFile> filesForType;
if (rssFiles.ContainsKey(type)) { if (rssFiles.ContainsKey(type)) {
filesForType = rssFiles[type]; filesForType = rssFiles[type];
@ -190,7 +182,7 @@ namespace GreenshotPlugin.Core {
filesForType = new Dictionary<string, SourceforgeFile>(); filesForType = new Dictionary<string, SourceforgeFile>();
rssFiles.Add(type, filesForType); rssFiles.Add(type, filesForType);
} }
SourceforgeFile rssFile = new SourceforgeFile(file, pubdate, sfLink, directLink); SourceforgeFile rssFile = new SourceforgeFile(file, pubdate, sfLink);
if (file.EndsWith(".exe") ||file.EndsWith(".zip")) { if (file.EndsWith(".exe") ||file.EndsWith(".zip")) {
string version = Regex.Replace(file, @".*[a-zA-Z_]\-", ""); string version = Regex.Replace(file, @".*[a-zA-Z_]\-", "");
version = version.Replace(@"\-[a-zA-Z]+.*",""); version = version.Replace(@"\-[a-zA-Z]+.*","");

View file

@ -42,6 +42,7 @@
<Compile Include="Core\CaptureHandler.cs" /> <Compile Include="Core\CaptureHandler.cs" />
<Compile Include="Core\EventDelay.cs" /> <Compile Include="Core\EventDelay.cs" />
<Compile Include="Core\FastBitmap.cs" /> <Compile Include="Core\FastBitmap.cs" />
<Compile Include="Core\Func.cs" />
<Compile Include="Core\WmInputLangChangeRequestFilter.cs" /> <Compile Include="Core\WmInputLangChangeRequestFilter.cs" />
<Compile Include="GlobalSuppressions.cs" /> <Compile Include="GlobalSuppressions.cs" />
<Compile Include="IEInterop\IHTMLBodyElement.cs" /> <Compile Include="IEInterop\IHTMLBodyElement.cs" />

View file

@ -1,9 +1,9 @@
/* /*
* Greenshot - a free and open source screenshot tool * Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
* *
* For more information see: http://getgreenshot.org/ * For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,9 +21,7 @@
using System; using System;
using System.Drawing; using System.Drawing;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security;
using log4net; using log4net;
using Microsoft.Win32.SafeHandles;
using System.Reflection; using System.Reflection;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Imaging; using System.Drawing.Imaging;
@ -94,7 +92,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// GDIplus Helpers /// GDIplus Helpers
/// </summary> /// </summary>
public static class GDIplus { public static class GDIplus {
private static ILog LOG = LogManager.GetLogger(typeof(GDIplus)); private static readonly ILog Log = LogManager.GetLogger(typeof(GDIplus));
[DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)] [DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)]
private static extern int GdipBitmapApplyEffect(IntPtr bitmap, IntPtr effect, ref RECT rectOfInterest, bool useAuxData, IntPtr auxData, int auxDataSize); private static extern int GdipBitmapApplyEffect(IntPtr bitmap, IntPtr effect, ref RECT rectOfInterest, bool useAuxData, IntPtr auxData, int auxDataSize);
@ -107,7 +105,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
private static extern int GdipCreateEffect(Guid guid, out IntPtr effect); private static extern int GdipCreateEffect(Guid guid, out IntPtr effect);
[DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)] [DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)]
private static extern int GdipDeleteEffect(IntPtr effect); private static extern int GdipDeleteEffect(IntPtr effect);
private static Guid BlurEffectGuid = new Guid("{633C80A4-1843-482B-9EF2-BE2834C5FDD4}"); private static readonly Guid BlurEffectGuid = new Guid("{633C80A4-1843-482B-9EF2-BE2834C5FDD4}");
// Constant "FieldInfo" for getting the nativeImage from the Bitmap // Constant "FieldInfo" for getting the nativeImage from the Bitmap
private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGE = typeof(Bitmap).GetField("nativeImage", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic); private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGE = typeof(Bitmap).GetField("nativeImage", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
@ -118,7 +116,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
// Constant "FieldInfo" for getting the nativeImageAttributes from the ImageAttributes // Constant "FieldInfo" for getting the nativeImageAttributes from the ImageAttributes
private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGEATTRIBUTES = typeof(ImageAttributes).GetField("nativeImageAttributes", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic); private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGEATTRIBUTES = typeof(ImageAttributes).GetField("nativeImageAttributes", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
private static bool isBlurEnabled = Environment.OSVersion.Version.Major >= 6; private static bool _isBlurEnabled = Environment.OSVersion.Version.Major >= 6;
/// <summary> /// <summary>
/// Get the nativeImage field from the bitmap /// Get the nativeImage field from the bitmap
/// </summary> /// </summary>
@ -172,14 +170,12 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// This accounts for the "bug" I reported here: http://social.technet.microsoft.com/Forums/en/w8itprogeneral/thread/99ddbe9d-556d-475a-8bab-84e25aa13a2c /// This accounts for the "bug" I reported here: http://social.technet.microsoft.com/Forums/en/w8itprogeneral/thread/99ddbe9d-556d-475a-8bab-84e25aa13a2c
/// </summary> /// </summary>
/// <param name="radius"></param> /// <param name="radius"></param>
/// <returns></returns> /// <returns>false if blur is not possible</returns>
public static bool isBlurPossible(int radius) { public static bool IsBlurPossible(int radius) {
if (!isBlurEnabled) { if (!_isBlurEnabled) {
return false;
} else if (Environment.OSVersion.Version.Minor >= 2 && radius < 20) {
return false; return false;
} }
return true; return Environment.OSVersion.Version.Minor < 2 || radius >= 20;
} }
/// <summary> /// <summary>
@ -191,25 +187,31 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// <param name="expandEdges">bool true if the edges are expanded with the radius</param> /// <param name="expandEdges">bool true if the edges are expanded with the radius</param>
/// <returns>false if there is no GDI+ available or an exception occured</returns> /// <returns>false if there is no GDI+ available or an exception occured</returns>
public static bool ApplyBlur(Bitmap destinationBitmap, Rectangle area, int radius, bool expandEdges) { public static bool ApplyBlur(Bitmap destinationBitmap, Rectangle area, int radius, bool expandEdges) {
if (!isBlurPossible(radius)) { if (!IsBlurPossible(radius)) {
return false; return false;
} }
IntPtr hBlurParams = IntPtr.Zero; IntPtr hBlurParams = IntPtr.Zero;
IntPtr hEffect = IntPtr.Zero; IntPtr hEffect = IntPtr.Zero;
try { try {
// Create the GDI+ BlurEffect, using the Guid
int status = GdipCreateEffect(BlurEffectGuid, out hEffect);
if (status != 0)
{
return false;
}
// Create a BlurParams struct and set the values // Create a BlurParams struct and set the values
BlurParams blurParams = new BlurParams(); var blurParams = new BlurParams
blurParams.Radius = radius; {
blurParams.ExpandEdges = expandEdges; Radius = radius,
ExpandEdges = expandEdges
};
// Allocate space in unmanaged memory // Allocate space in unmanaged memory
hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams)); hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams));
// Copy the structure to the unmanaged memory // Copy the structure to the unmanaged memory
Marshal.StructureToPtr(blurParams, hBlurParams, false); Marshal.StructureToPtr(blurParams, hBlurParams, false);
// Create the GDI+ BlurEffect, using the Guid
int status = GdipCreateEffect(BlurEffectGuid, out hEffect);
// Set the blurParams to the effect // Set the blurParams to the effect
GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams)); GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams));
@ -226,8 +228,8 @@ namespace GreenshotPlugin.UnmanagedHelpers {
// Everything worked, return true // Everything worked, return true
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {
isBlurEnabled = false; _isBlurEnabled = false;
LOG.Error("Problem using GdipBitmapApplyEffect: ", ex); Log.Error("Problem using GdipBitmapApplyEffect: ", ex);
return false; return false;
} finally { } finally {
try { try {
@ -240,8 +242,8 @@ namespace GreenshotPlugin.UnmanagedHelpers {
Marshal.FreeHGlobal(hBlurParams); Marshal.FreeHGlobal(hBlurParams);
} }
} catch (Exception ex) { } catch (Exception ex) {
isBlurEnabled = false; _isBlurEnabled = false;
LOG.Error("Problem cleaning up ApplyBlur: ", ex); Log.Error("Problem cleaning up ApplyBlur: ", ex);
} }
} }
} }
@ -251,7 +253,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// </summary> /// </summary>
/// <returns>false if there is no GDI+ available or an exception occured</returns> /// <returns>false if there is no GDI+ available or an exception occured</returns>
public static bool DrawWithBlur(Graphics graphics, Bitmap image, Rectangle source, Matrix transform, ImageAttributes imageAttributes, int radius, bool expandEdges) { public static bool DrawWithBlur(Graphics graphics, Bitmap image, Rectangle source, Matrix transform, ImageAttributes imageAttributes, int radius, bool expandEdges) {
if (!isBlurPossible(radius)) { if (!IsBlurPossible(radius)) {
return false; return false;
} }
@ -259,20 +261,26 @@ namespace GreenshotPlugin.UnmanagedHelpers {
IntPtr hEffect = IntPtr.Zero; IntPtr hEffect = IntPtr.Zero;
try { try {
// Create the GDI+ BlurEffect, using the Guid
int status = GdipCreateEffect(BlurEffectGuid, out hEffect);
if (status != 0)
{
return false;
}
// Create a BlurParams struct and set the values // Create a BlurParams struct and set the values
BlurParams blurParams = new BlurParams(); var blurParams = new BlurParams
blurParams.Radius = radius; {
Radius = radius,
ExpandEdges = false
};
//blurParams.Padding = radius; //blurParams.Padding = radius;
blurParams.ExpandEdges = false;
// Allocate space in unmanaged memory // Allocate space in unmanaged memory
hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams)); hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams));
// Copy the structure to the unmanaged memory // Copy the structure to the unmanaged memory
Marshal.StructureToPtr(blurParams, hBlurParams, true); Marshal.StructureToPtr(blurParams, hBlurParams, true);
// Create the GDI+ BlurEffect, using the Guid
int status = GdipCreateEffect(BlurEffectGuid, out hEffect);
// Set the blurParams to the effect // Set the blurParams to the effect
GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams)); GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams));
@ -284,15 +292,15 @@ namespace GreenshotPlugin.UnmanagedHelpers {
IntPtr hAttributes = GetNativeImageAttributes(imageAttributes); IntPtr hAttributes = GetNativeImageAttributes(imageAttributes);
// Create a RECT from the Rectangle // Create a RECT from the Rectangle
RECTF sourceRECF = new RECTF(source); RECTF sourceRecf = new RECTF(source);
// Apply the effect to the bitmap in the specified area // Apply the effect to the bitmap in the specified area
GdipDrawImageFX(hGraphics, hBitmap, ref sourceRECF, hMatrix, hEffect, hAttributes, GpUnit.UnitPixel); GdipDrawImageFX(hGraphics, hBitmap, ref sourceRecf, hMatrix, hEffect, hAttributes, GpUnit.UnitPixel);
// Everything worked, return true // Everything worked, return true
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {
isBlurEnabled = false; _isBlurEnabled = false;
LOG.Error("Problem using GdipDrawImageFX: ", ex); Log.Error("Problem using GdipDrawImageFX: ", ex);
return false; return false;
} finally { } finally {
try { try {
@ -305,8 +313,8 @@ namespace GreenshotPlugin.UnmanagedHelpers {
Marshal.FreeHGlobal(hBlurParams); Marshal.FreeHGlobal(hBlurParams);
} }
} catch (Exception ex) { } catch (Exception ex) {
isBlurEnabled = false; _isBlurEnabled = false;
LOG.Error("Problem cleaning up DrawWithBlur: ", ex); Log.Error("Problem cleaning up DrawWithBlur: ", ex);
} }
} }
} }

View file

@ -67,12 +67,14 @@ deploy:
auth_token: auth_token:
secure: 4sYcNGg7byBFtR7EkJHS8d3H3qP0u0LodlJWCV7g/4jEyv3vvVxqzh19zZ6Zgrf1 secure: 4sYcNGg7byBFtR7EkJHS8d3H3qP0u0LodlJWCV7g/4jEyv3vvVxqzh19zZ6Zgrf1
prerelease: true prerelease: true
draft: true
on: on:
build_type: UNSTABLE build_type: UNSTABLE
- provider: GitHub - provider: GitHub
tag: Greenshot-$(build_type)-$(APPVEYOR_BUILD_VERSION) tag: Greenshot-$(build_type)-$(APPVEYOR_BUILD_VERSION)
auth_token: auth_token:
secure: 4sYcNGg7byBFtR7EkJHS8d3H3qP0u0LodlJWCV7g/4jEyv3vvVxqzh19zZ6Zgrf1 secure: 4sYcNGg7byBFtR7EkJHS8d3H3qP0u0LodlJWCV7g/4jEyv3vvVxqzh19zZ6Zgrf1
draft: true
on: on:
build_type: RELEASE build_type: RELEASE
notifications: notifications: