diff --git a/src/Greenshot.Plugin.Box/BoxConfiguration.cs b/src/Greenshot.Plugin.Box/BoxConfiguration.cs
index a940b319e..a4d83ef68 100644
--- a/src/Greenshot.Plugin.Box/BoxConfiguration.cs
+++ b/src/Greenshot.Plugin.Box/BoxConfiguration.cs
@@ -25,56 +25,55 @@ using Greenshot.Plugin.Box.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.Box {
- ///
- /// Description of ImgurConfiguration.
- ///
- [IniSection("Box", Description = "Greenshot Box Plugin configuration")]
- public class BoxConfiguration : IniSection {
- [IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
- public OutputFormat UploadFormat { get; set; }
+namespace Greenshot.Plugin.Box
+{
+ ///
+ /// Description of ImgurConfiguration.
+ ///
+ [IniSection("Box", Description = "Greenshot Box Plugin configuration")]
+ public class BoxConfiguration : IniSection
+ {
+ [IniProperty("UploadFormat", Description = "What file type to use for uploading", DefaultValue = "png")]
+ public OutputFormat UploadFormat { get; set; }
- [IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]
- public int UploadJpegQuality { get; set; }
+ [IniProperty("UploadJpegQuality", Description = "JPEG file save quality in %.", DefaultValue = "80")]
+ public int UploadJpegQuality { get; set; }
- [IniProperty("AfterUploadLinkToClipBoard", Description = "After upload send Box link to clipboard.", DefaultValue = "true")]
- public bool AfterUploadLinkToClipBoard { get; set; }
+ [IniProperty("AfterUploadLinkToClipBoard", Description = "After upload send Box link to clipboard.", DefaultValue = "true")]
+ public bool AfterUploadLinkToClipBoard { get; set; }
- [IniProperty("UseSharedLink", Description = "Use the shared link, instead of the private, on the clipboard", DefaultValue = "True")]
- public bool UseSharedLink { get; set; }
- [IniProperty("FolderId", Description = "Folder ID to upload to, only change if you know what you are doing!", DefaultValue = "0")]
- public string FolderId { get; set; }
+ [IniProperty("UseSharedLink", Description = "Use the shared link, instead of the private, on the clipboard", DefaultValue = "True")]
+ public bool UseSharedLink { get; set; }
- [IniProperty("RefreshToken", Description = "Box authorization refresh Token", Encrypted = true)]
- public string RefreshToken { get; set; }
+ [IniProperty("FolderId", Description = "Folder ID to upload to, only change if you know what you are doing!", DefaultValue = "0")]
+ public string FolderId { get; set; }
- ///
- /// Not stored
- ///
- public string AccessToken {
- get;
- set;
- }
+ [IniProperty("RefreshToken", Description = "Box authorization refresh Token", Encrypted = true)]
+ public string RefreshToken { get; set; }
- ///
- /// Not stored
- ///
- public DateTimeOffset AccessTokenExpires {
- get;
- set;
- }
+ ///
+ /// Not stored
+ ///
+ public string AccessToken { get; set; }
- ///
- /// A form for token
- ///
- /// bool true if OK was pressed, false if cancel
- public bool ShowConfigDialog() {
- DialogResult result = new SettingsForm().ShowDialog();
- if (result == DialogResult.OK) {
- return true;
- }
- return false;
- }
+ ///
+ /// Not stored
+ ///
+ public DateTimeOffset AccessTokenExpires { get; set; }
- }
-}
+ ///
+ /// A form for token
+ ///
+ /// bool true if OK was pressed, false if cancel
+ public bool ShowConfigDialog()
+ {
+ DialogResult result = new SettingsForm().ShowDialog();
+ if (result == DialogResult.OK)
+ {
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Box/BoxDestination.cs b/src/Greenshot.Plugin.Box/BoxDestination.cs
index 3c1a0622d..0bc547b88 100644
--- a/src/Greenshot.Plugin.Box/BoxDestination.cs
+++ b/src/Greenshot.Plugin.Box/BoxDestination.cs
@@ -24,33 +24,42 @@ using System.Drawing;
using GreenshotPlugin.Core;
using GreenshotPlugin.Interfaces;
-namespace Greenshot.Plugin.Box {
- public class BoxDestination : AbstractDestination {
- private readonly BoxPlugin _plugin;
- public BoxDestination(BoxPlugin plugin) {
- _plugin = plugin;
- }
-
- public override string Designation => "Box";
+namespace Greenshot.Plugin.Box
+{
+ public class BoxDestination : AbstractDestination
+ {
+ private readonly BoxPlugin _plugin;
- public override string Description => Language.GetString("box", LangKey.upload_menu_item);
+ public BoxDestination(BoxPlugin plugin)
+ {
+ _plugin = plugin;
+ }
- public override Image DisplayIcon {
- get {
- ComponentResourceManager resources = new ComponentResourceManager(typeof(BoxPlugin));
- return (Image)resources.GetObject("Box");
- }
- }
+ public override string Designation => "Box";
- public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
- ExportInformation exportInformation = new ExportInformation(Designation, Description);
- string uploadUrl = _plugin.Upload(captureDetails, surface);
- if (uploadUrl != null) {
- exportInformation.ExportMade = true;
- exportInformation.Uri = uploadUrl;
- }
- ProcessExport(exportInformation, surface);
- return exportInformation;
- }
- }
-}
+ public override string Description => Language.GetString("box", LangKey.upload_menu_item);
+
+ public override Image DisplayIcon
+ {
+ get
+ {
+ ComponentResourceManager resources = new ComponentResourceManager(typeof(BoxPlugin));
+ return (Image) resources.GetObject("Box");
+ }
+ }
+
+ public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
+ {
+ ExportInformation exportInformation = new ExportInformation(Designation, Description);
+ string uploadUrl = _plugin.Upload(captureDetails, surface);
+ if (uploadUrl != null)
+ {
+ exportInformation.ExportMade = true;
+ exportInformation.Uri = uploadUrl;
+ }
+
+ ProcessExport(exportInformation, surface);
+ return exportInformation;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Box/BoxEntities.cs b/src/Greenshot.Plugin.Box/BoxEntities.cs
index bf5476f4e..d99612377 100644
--- a/src/Greenshot.Plugin.Box/BoxEntities.cs
+++ b/src/Greenshot.Plugin.Box/BoxEntities.cs
@@ -22,39 +22,35 @@
using System.Collections.Generic;
using System.Runtime.Serialization;
-namespace Greenshot.Plugin.Box {
- [DataContract]
- public class Authorization {
- [DataMember(Name = "access_token")]
- public string AccessToken { get; set; }
- [DataMember(Name = "expires_in")]
- public int ExpiresIn { get; set; }
- [DataMember(Name = "refresh_token")]
- public string RefreshToken { get; set; }
- [DataMember(Name = "token_type")]
- public string TokenType { get; set; }
- }
- [DataContract]
- public class SharedLink {
- [DataMember(Name = "url")]
- public string Url { get; set; }
- [DataMember(Name = "download_url")]
- public string DownloadUrl { get; set; }
- }
+namespace Greenshot.Plugin.Box
+{
+ [DataContract]
+ public class Authorization
+ {
+ [DataMember(Name = "access_token")] public string AccessToken { get; set; }
+ [DataMember(Name = "expires_in")] public int ExpiresIn { get; set; }
+ [DataMember(Name = "refresh_token")] public string RefreshToken { get; set; }
+ [DataMember(Name = "token_type")] public string TokenType { get; set; }
+ }
- [DataContract]
- public class FileEntry {
- [DataMember(Name = "id")]
- public string Id { get; set; }
- [DataMember(Name = "name")]
- public string Name { get; set; }
- [DataMember(Name = "shared_link")]
- public SharedLink SharedLink { get; set; }
- }
+ [DataContract]
+ public class SharedLink
+ {
+ [DataMember(Name = "url")] public string Url { get; set; }
+ [DataMember(Name = "download_url")] public string DownloadUrl { get; set; }
+ }
- [DataContract]
- public class Upload {
- [DataMember(Name = "entries")]
- public List Entries { get; set; }
- }
-}
+ [DataContract]
+ public class FileEntry
+ {
+ [DataMember(Name = "id")] public string Id { get; set; }
+ [DataMember(Name = "name")] public string Name { get; set; }
+ [DataMember(Name = "shared_link")] public SharedLink SharedLink { get; set; }
+ }
+
+ [DataContract]
+ public class Upload
+ {
+ [DataMember(Name = "entries")] public List Entries { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Box/BoxPlugin.cs b/src/Greenshot.Plugin.Box/BoxPlugin.cs
index 6a01dda9e..9918b5e93 100644
--- a/src/Greenshot.Plugin.Box/BoxPlugin.cs
+++ b/src/Greenshot.Plugin.Box/BoxPlugin.cs
@@ -30,99 +30,111 @@ using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
-namespace Greenshot.Plugin.Box {
- ///
- /// This is the Box base code
- ///
+namespace Greenshot.Plugin.Box
+{
+ ///
+ /// This is the Box base code
+ ///
[Plugin("Box", true)]
- public class BoxPlugin : IGreenshotPlugin {
- private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(BoxPlugin));
- private static BoxConfiguration _config;
- private ComponentResourceManager _resources;
- private ToolStripMenuItem _itemPlugInConfig;
+ public class BoxPlugin : IGreenshotPlugin
+ {
+ private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(BoxPlugin));
+ private static BoxConfiguration _config;
+ private ComponentResourceManager _resources;
+ private ToolStripMenuItem _itemPlugInConfig;
- public void Dispose() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- protected void Dispose(bool disposing)
- {
- if (!disposing) return;
+ protected void Dispose(bool disposing)
+ {
+ if (!disposing) return;
- if (_itemPlugInConfig == null) return;
-
- _itemPlugInConfig.Dispose();
- _itemPlugInConfig = null;
- }
+ if (_itemPlugInConfig == null) return;
- ///
- /// Implementation of the IGreenshotPlugin.Initialize
- ///
- public bool Initialize() {
+ _itemPlugInConfig.Dispose();
+ _itemPlugInConfig = null;
+ }
- // Register configuration (don't need the configuration itself)
- _config = IniConfig.GetIniSection();
- _resources = new ComponentResourceManager(typeof(BoxPlugin));
+ ///
+ /// Implementation of the IGreenshotPlugin.Initialize
+ ///
+ public bool Initialize()
+ {
+ // Register configuration (don't need the configuration itself)
+ _config = IniConfig.GetIniSection();
+ _resources = new ComponentResourceManager(typeof(BoxPlugin));
SimpleServiceProvider.Current.AddService(new BoxDestination(this));
- _itemPlugInConfig = new ToolStripMenuItem {
- Image = (Image) _resources.GetObject("Box"),
- Text = Language.GetString("box", LangKey.Configure)
- };
- _itemPlugInConfig.Click += ConfigMenuClick;
+ _itemPlugInConfig = new ToolStripMenuItem
+ {
+ Image = (Image) _resources.GetObject("Box"),
+ Text = Language.GetString("box", LangKey.Configure)
+ };
+ _itemPlugInConfig.Click += ConfigMenuClick;
- PluginUtils.AddToContextMenu(_itemPlugInConfig);
- Language.LanguageChanged += OnLanguageChanged;
- return true;
- }
+ PluginUtils.AddToContextMenu(_itemPlugInConfig);
+ Language.LanguageChanged += OnLanguageChanged;
+ return true;
+ }
- public void OnLanguageChanged(object sender, EventArgs e) {
- if (_itemPlugInConfig != null) {
- _itemPlugInConfig.Text = Language.GetString("box", LangKey.Configure);
- }
- }
+ public void OnLanguageChanged(object sender, EventArgs e)
+ {
+ if (_itemPlugInConfig != null)
+ {
+ _itemPlugInConfig.Text = Language.GetString("box", LangKey.Configure);
+ }
+ }
- public void Shutdown() {
- LOG.Debug("Box Plugin shutdown.");
- }
+ public void Shutdown()
+ {
+ LOG.Debug("Box Plugin shutdown.");
+ }
- ///
- /// Implementation of the IPlugin.Configure
- ///
- public void Configure() {
- _config.ShowConfigDialog();
- }
+ ///
+ /// Implementation of the IPlugin.Configure
+ ///
+ public void Configure()
+ {
+ _config.ShowConfigDialog();
+ }
- public void ConfigMenuClick(object sender, EventArgs eventArgs) {
- _config.ShowConfigDialog();
- }
+ public void ConfigMenuClick(object sender, EventArgs eventArgs)
+ {
+ _config.ShowConfigDialog();
+ }
- ///
- /// This will be called when the menu item in the Editor is clicked
- ///
- public string Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload) {
- SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false);
- try {
- string url = null;
- string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails));
- SurfaceContainer imageToUpload = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
-
- new PleaseWaitForm().ShowAndWait("Box", Language.GetString("box", LangKey.communication_wait),
- delegate {
- url = BoxUtils.UploadToBox(imageToUpload, captureDetails.Title, filename);
- }
- );
+ ///
+ /// This will be called when the menu item in the Editor is clicked
+ ///
+ public string Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload)
+ {
+ SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false);
+ try
+ {
+ string url = null;
+ string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails));
+ SurfaceContainer imageToUpload = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
- if (url != null && _config.AfterUploadLinkToClipBoard) {
- ClipboardHelper.SetClipboardData(url);
- }
+ new PleaseWaitForm().ShowAndWait("Box", Language.GetString("box", LangKey.communication_wait),
+ delegate { url = BoxUtils.UploadToBox(imageToUpload, captureDetails.Title, filename); }
+ );
- return url;
- } catch (Exception ex) {
- LOG.Error("Error uploading.", ex);
- MessageBox.Show(Language.GetString("box", LangKey.upload_failure) + " " + ex.Message);
- return null;
- }
- }
- }
-}
+ if (url != null && _config.AfterUploadLinkToClipBoard)
+ {
+ ClipboardHelper.SetClipboardData(url);
+ }
+
+ return url;
+ }
+ catch (Exception ex)
+ {
+ LOG.Error("Error uploading.", ex);
+ MessageBox.Show(Language.GetString("box", LangKey.upload_failure) + " " + ex.Message);
+ return null;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Box/BoxUtils.cs b/src/Greenshot.Plugin.Box/BoxUtils.cs
index 22e8acf49..37a0eac53 100644
--- a/src/Greenshot.Plugin.Box/BoxUtils.cs
+++ b/src/Greenshot.Plugin.Box/BoxUtils.cs
@@ -27,112 +27,128 @@ using GreenshotPlugin.Core;
using GreenshotPlugin.Core.OAuth;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.Box {
-
+namespace Greenshot.Plugin.Box
+{
///
/// Description of BoxUtils.
///
- public static class BoxUtils {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(BoxUtils));
- private static readonly BoxConfiguration Config = IniConfig.GetIniSection();
- private const string UploadFileUri = "https://upload.box.com/api/2.0/files/content";
- private const string FilesUri = "https://www.box.com/api/2.0/files/{0}";
+ public static class BoxUtils
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(BoxUtils));
+ private static readonly BoxConfiguration Config = IniConfig.GetIniSection();
+ private const string UploadFileUri = "https://upload.box.com/api/2.0/files/content";
+ private const string FilesUri = "https://www.box.com/api/2.0/files/{0}";
- ///
- /// Put string
- ///
- ///
- ///
- /// OAuth2Settings
- /// response
- public static string HttpPut(string url, string content, OAuth2Settings settings) {
- var webRequest= OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.PUT, url, settings);
-
- byte[] data = Encoding.UTF8.GetBytes(content);
- using (var requestStream = webRequest.GetRequestStream()) {
- requestStream.Write(data, 0, data.Length);
- }
- return NetworkHelper.GetResponseAsString(webRequest);
- }
-
- ///
- /// Do the actual upload to Box
- /// For more details on the available parameters, see: http://developers.box.net/w/page/12923951/ApiFunction_Upload%20and%20Download
- ///
- /// Image for box upload
- /// Title of box upload
- /// Filename of box upload
- /// url to uploaded image
- public static string UploadToBox(SurfaceContainer image, string title, string filename) {
-
- // Fill the OAuth2Settings
- var settings = new OAuth2Settings
- {
- AuthUrlPattern = "https://app.box.com/api/oauth2/authorize?client_id={ClientId}&response_type=code&state={State}&redirect_uri={RedirectUrl}",
- TokenUrl = "https://api.box.com/oauth2/token",
- CloudServiceName = "Box",
- ClientId = BoxCredentials.ClientId,
- ClientSecret = BoxCredentials.ClientSecret,
- RedirectUrl = "https://getgreenshot.org/authorize/box",
- AuthorizeMode = OAuth2AuthorizeMode.JsonReceiver,
- RefreshToken = Config.RefreshToken,
- AccessToken = Config.AccessToken,
- AccessTokenExpires = Config.AccessTokenExpires
- };
-
-
- // Copy the settings from the config, which is kept in memory and on the disk
-
- try {
- var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, UploadFileUri, settings);
- IDictionary parameters = new Dictionary
- {
- { "file", image },
- { "parent_id", Config.FolderId }
- };
-
- NetworkHelper.WriteMultipartFormData(webRequest, parameters);
-
- var response = NetworkHelper.GetResponseAsString(webRequest);
-
- Log.DebugFormat("Box response: {0}", response);
-
- var upload = JsonSerializer.Deserialize(response);
- if (upload?.Entries == null || upload.Entries.Count == 0) return null;
-
- if (Config.UseSharedLink) {
- string filesResponse = HttpPut(string.Format(FilesUri, upload.Entries[0].Id), "{\"shared_link\": {\"access\": \"open\"}}", settings);
- var file = JsonSerializer.Deserialize(filesResponse);
- return file.SharedLink.Url;
- }
- return $"http://www.box.com/files/0/f/0/1/f_{upload.Entries[0].Id}";
- } finally {
- // Copy the settings back to the config, so they are stored.
- Config.RefreshToken = settings.RefreshToken;
- Config.AccessToken = settings.AccessToken;
- Config.AccessTokenExpires = settings.AccessTokenExpires;
- Config.IsDirty = true;
- IniConfig.Save();
- }
- }
- }
- ///
- /// A simple helper class for the DataContractJsonSerializer
- ///
- internal static class JsonSerializer {
///
- /// Helper method to parse JSON to object
- ///
- ///
- ///
- ///
- public static T Deserialize(string jsonString) {
- var deserializer = new DataContractJsonSerializer(typeof(T));
+ /// Put string
+ ///
+ ///
+ ///
+ /// OAuth2Settings
+ /// response
+ public static string HttpPut(string url, string content, OAuth2Settings settings)
+ {
+ var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.PUT, url, settings);
+
+ byte[] data = Encoding.UTF8.GetBytes(content);
+ using (var requestStream = webRequest.GetRequestStream())
+ {
+ requestStream.Write(data, 0, data.Length);
+ }
+
+ return NetworkHelper.GetResponseAsString(webRequest);
+ }
+
+ ///
+ /// Do the actual upload to Box
+ /// For more details on the available parameters, see: http://developers.box.net/w/page/12923951/ApiFunction_Upload%20and%20Download
+ ///
+ /// Image for box upload
+ /// Title of box upload
+ /// Filename of box upload
+ /// url to uploaded image
+ public static string UploadToBox(SurfaceContainer image, string title, string filename)
+ {
+ // Fill the OAuth2Settings
+ var settings = new OAuth2Settings
+ {
+ AuthUrlPattern = "https://app.box.com/api/oauth2/authorize?client_id={ClientId}&response_type=code&state={State}&redirect_uri={RedirectUrl}",
+ TokenUrl = "https://api.box.com/oauth2/token",
+ CloudServiceName = "Box",
+ ClientId = BoxCredentials.ClientId,
+ ClientSecret = BoxCredentials.ClientSecret,
+ RedirectUrl = "https://getgreenshot.org/authorize/box",
+ AuthorizeMode = OAuth2AuthorizeMode.JsonReceiver,
+ RefreshToken = Config.RefreshToken,
+ AccessToken = Config.AccessToken,
+ AccessTokenExpires = Config.AccessTokenExpires
+ };
+
+
+ // Copy the settings from the config, which is kept in memory and on the disk
+
+ try
+ {
+ var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, UploadFileUri, settings);
+ IDictionary parameters = new Dictionary
+ {
+ {
+ "file", image
+ },
+ {
+ "parent_id", Config.FolderId
+ }
+ };
+
+ NetworkHelper.WriteMultipartFormData(webRequest, parameters);
+
+ var response = NetworkHelper.GetResponseAsString(webRequest);
+
+ Log.DebugFormat("Box response: {0}", response);
+
+ var upload = JsonSerializer.Deserialize(response);
+ if (upload?.Entries == null || upload.Entries.Count == 0) return null;
+
+ if (Config.UseSharedLink)
+ {
+ string filesResponse = HttpPut(string.Format(FilesUri, upload.Entries[0].Id), "{\"shared_link\": {\"access\": \"open\"}}", settings);
+ var file = JsonSerializer.Deserialize(filesResponse);
+ return file.SharedLink.Url;
+ }
+
+ return $"http://www.box.com/files/0/f/0/1/f_{upload.Entries[0].Id}";
+ }
+ finally
+ {
+ // Copy the settings back to the config, so they are stored.
+ Config.RefreshToken = settings.RefreshToken;
+ Config.AccessToken = settings.AccessToken;
+ Config.AccessTokenExpires = settings.AccessTokenExpires;
+ Config.IsDirty = true;
+ IniConfig.Save();
+ }
+ }
+ }
+
+ ///
+ /// A simple helper class for the DataContractJsonSerializer
+ ///
+ internal static class JsonSerializer
+ {
+ ///
+ /// Helper method to parse JSON to object
+ ///
+ ///
+ ///
+ ///
+ public static T Deserialize(string jsonString)
+ {
+ var deserializer = new DataContractJsonSerializer(typeof(T));
using var stream = new MemoryStream();
byte[] content = Encoding.UTF8.GetBytes(jsonString);
stream.Write(content, 0, content.Length);
stream.Seek(0, SeekOrigin.Begin);
- return (T)deserializer.ReadObject(stream);
+ return (T) deserializer.ReadObject(stream);
}
- }
-}
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Box/Forms/BoxForm.cs b/src/Greenshot.Plugin.Box/Forms/BoxForm.cs
index 5bb895823..646bdf87b 100644
--- a/src/Greenshot.Plugin.Box/Forms/BoxForm.cs
+++ b/src/Greenshot.Plugin.Box/Forms/BoxForm.cs
@@ -21,7 +21,9 @@
using GreenshotPlugin.Controls;
-namespace Greenshot.Plugin.Box.Forms {
- public class BoxForm : GreenshotForm {
- }
+namespace Greenshot.Plugin.Box.Forms
+{
+ public class BoxForm : GreenshotForm
+ {
+ }
}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Box/Forms/SettingsForm.cs b/src/Greenshot.Plugin.Box/Forms/SettingsForm.cs
index 1de1e7b32..588350c76 100644
--- a/src/Greenshot.Plugin.Box/Forms/SettingsForm.cs
+++ b/src/Greenshot.Plugin.Box/Forms/SettingsForm.cs
@@ -19,18 +19,21 @@
* along with this program. If not, see .
*/
-namespace Greenshot.Plugin.Box.Forms {
- ///
- /// Description of PasswordRequestForm.
- ///
- public partial class SettingsForm : BoxForm {
- public SettingsForm() {
- //
- // The InitializeComponent() call is required for Windows Forms designer support.
- //
- InitializeComponent();
- AcceptButton = buttonOK;
- CancelButton = buttonCancel;
- }
- }
-}
+namespace Greenshot.Plugin.Box.Forms
+{
+ ///
+ /// Description of PasswordRequestForm.
+ ///
+ public partial class SettingsForm : BoxForm
+ {
+ public SettingsForm()
+ {
+ //
+ // The InitializeComponent() call is required for Windows Forms designer support.
+ //
+ InitializeComponent();
+ AcceptButton = buttonOK;
+ CancelButton = buttonCancel;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Box/LanguageKeys.cs b/src/Greenshot.Plugin.Box/LanguageKeys.cs
index 32230ebd1..c6c64bfdf 100644
--- a/src/Greenshot.Plugin.Box/LanguageKeys.cs
+++ b/src/Greenshot.Plugin.Box/LanguageKeys.cs
@@ -18,11 +18,14 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
-namespace Greenshot.Plugin.Box {
- public enum LangKey {
- upload_menu_item,
- upload_failure,
- communication_wait,
- Configure
- }
-}
+
+namespace Greenshot.Plugin.Box
+{
+ public enum LangKey
+ {
+ upload_menu_item,
+ upload_failure,
+ communication_wait,
+ Configure
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Box/Properties/AssemblyInfo.cs b/src/Greenshot.Plugin.Box/Properties/AssemblyInfo.cs
index b6b19f1c8..8af36d000 100644
--- a/src/Greenshot.Plugin.Box/Properties/AssemblyInfo.cs
+++ b/src/Greenshot.Plugin.Box/Properties/AssemblyInfo.cs
@@ -29,4 +29,4 @@ using System.Runtime.InteropServices;
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
-[assembly: ComVisible(false)]
+[assembly: ComVisible(false)]
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Confluence.cs b/src/Greenshot.Plugin.Confluence/Confluence.cs
index 13f5d0ab3..79d11a034 100644
--- a/src/Greenshot.Plugin.Confluence/Confluence.cs
+++ b/src/Greenshot.Plugin.Confluence/Confluence.cs
@@ -26,283 +26,333 @@ using GreenshotConfluencePlugin.confluence;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.Confluence {
- public class Page {
- public Page(RemotePage page) {
- Id = page.id;
- Title = page.title;
- SpaceKey = page.space;
- Url = page.url;
- Content = page.content;
- }
- public Page(RemoteSearchResult searchResult, string space) {
- Id = searchResult.id;
- Title = searchResult.title;
- SpaceKey = space;
- Url = searchResult.url;
- Content = searchResult.excerpt;
- }
-
- public Page(RemotePageSummary pageSummary) {
- Id = pageSummary.id;
- Title = pageSummary.title;
- SpaceKey = pageSummary.space;
- Url =pageSummary.url;
- }
- public long Id {
- get;
- set;
- }
- public string Title {
- get;
- set;
- }
- public string Url {
- get;
- set;
- }
- public string Content {
- get;
- set;
- }
- public string SpaceKey {
- get;
- set;
- }
- }
- public class Space {
- public Space(RemoteSpaceSummary space) {
- Key = space.key;
- Name = space.name;
- }
- public string Key {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- }
+namespace Greenshot.Plugin.Confluence
+{
+ public class Page
+ {
+ public Page(RemotePage page)
+ {
+ Id = page.id;
+ Title = page.title;
+ SpaceKey = page.space;
+ Url = page.url;
+ Content = page.content;
+ }
+
+ public Page(RemoteSearchResult searchResult, string space)
+ {
+ Id = searchResult.id;
+ Title = searchResult.title;
+ SpaceKey = space;
+ Url = searchResult.url;
+ Content = searchResult.excerpt;
+ }
+
+ public Page(RemotePageSummary pageSummary)
+ {
+ Id = pageSummary.id;
+ Title = pageSummary.title;
+ SpaceKey = pageSummary.space;
+ Url = pageSummary.url;
+ }
+
+ public long Id { get; set; }
+ public string Title { get; set; }
+ public string Url { get; set; }
+ public string Content { get; set; }
+ public string SpaceKey { get; set; }
+ }
+
+ public class Space
+ {
+ public Space(RemoteSpaceSummary space)
+ {
+ Key = space.key;
+ Name = space.name;
+ }
+
+ public string Key { get; set; }
+ public string Name { get; set; }
+ }
///
- /// For details see the Confluence API site
- /// See: http://confluence.atlassian.com/display/CONFDEV/Remote+API+Specification
- ///
- public class ConfluenceConnector : IDisposable {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ConfluenceConnector));
- private const string AuthFailedExceptionName = "com.atlassian.confluence.rpc.AuthenticationFailedException";
- private const string V2Failed = "AXIS";
- private static readonly ConfluenceConfiguration Config = IniConfig.GetIniSection();
- private string _credentials;
- private DateTime _loggedInTime = DateTime.Now;
- private bool _loggedIn;
- private ConfluenceSoapServiceService _confluence;
- private readonly int _timeout;
- private string _url;
- private readonly Cache _pageCache = new Cache(60 * Config.Timeout);
+ /// For details see the Confluence API site
+ /// See: http://confluence.atlassian.com/display/CONFDEV/Remote+API+Specification
+ ///
+ public class ConfluenceConnector : IDisposable
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ConfluenceConnector));
+ private const string AuthFailedExceptionName = "com.atlassian.confluence.rpc.AuthenticationFailedException";
+ private const string V2Failed = "AXIS";
+ private static readonly ConfluenceConfiguration Config = IniConfig.GetIniSection();
+ private string _credentials;
+ private DateTime _loggedInTime = DateTime.Now;
+ private bool _loggedIn;
+ private ConfluenceSoapServiceService _confluence;
+ private readonly int _timeout;
+ private string _url;
+ private readonly Cache _pageCache = new Cache(60 * Config.Timeout);
- public void Dispose() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- protected void Dispose(bool disposing) {
- if (_confluence != null) {
- Logout();
- }
- if (disposing) {
- if (_confluence != null) {
- _confluence.Dispose();
- _confluence = null;
- }
- }
- }
+ protected void Dispose(bool disposing)
+ {
+ if (_confluence != null)
+ {
+ Logout();
+ }
- public ConfluenceConnector(string url, int timeout) {
- _timeout = timeout;
- Init(url);
- }
+ if (disposing)
+ {
+ if (_confluence != null)
+ {
+ _confluence.Dispose();
+ _confluence = null;
+ }
+ }
+ }
- private void Init(string url) {
- _url = url;
- _confluence = new ConfluenceSoapServiceService
- {
- Url = url,
- Proxy = NetworkHelper.CreateProxy(new Uri(url))
- };
- }
+ public ConfluenceConnector(string url, int timeout)
+ {
+ _timeout = timeout;
+ Init(url);
+ }
- ~ConfluenceConnector() {
- Dispose(false);
- }
+ private void Init(string url)
+ {
+ _url = url;
+ _confluence = new ConfluenceSoapServiceService
+ {
+ Url = url,
+ Proxy = NetworkHelper.CreateProxy(new Uri(url))
+ };
+ }
- ///
- /// Internal login which catches the exceptions
- ///
- /// true if login was done sucessfully
- private bool DoLogin(string user, string password) {
- try {
- _credentials = _confluence.login(user, password);
- _loggedInTime = DateTime.Now;
- _loggedIn = true;
- } catch (Exception e) {
- // Check if confluence-v2 caused an error, use v1 instead
- if (e.Message.Contains(V2Failed) && _url.Contains("v2")) {
- Init(_url.Replace("v2", "v1"));
- return DoLogin(user, password);
- }
- // check if auth failed
- if (e.Message.Contains(AuthFailedExceptionName)) {
- return false;
- }
- // Not an authentication issue
- _loggedIn = false;
- _credentials = null;
- e.Data.Add("user", user);
- e.Data.Add("url", _url);
- throw;
- }
- return true;
- }
+ ~ConfluenceConnector()
+ {
+ Dispose(false);
+ }
- public void Login() {
- Logout();
- try {
- // Get the system name, so the user knows where to login to
- string systemName = _url.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX1,"");
- systemName = systemName.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX2, "");
- CredentialsDialog dialog = new CredentialsDialog(systemName)
- {
- Name = null
- };
- while (dialog.Show(dialog.Name) == DialogResult.OK) {
- if (DoLogin(dialog.Name, dialog.Password)) {
- if (dialog.SaveChecked) {
- dialog.Confirm(true);
- }
- return;
- } else {
- try {
- dialog.Confirm(false);
- } catch (ApplicationException e) {
- // exception handling ...
- Log.Error("Problem using the credentials dialog", e);
- }
- // For every windows version after XP show an incorrect password baloon
- dialog.IncorrectPassword = true;
- // Make sure the dialog is display, the password was false!
- dialog.AlwaysDisplay = true;
- }
- }
- } catch (ApplicationException e) {
- // exception handling ...
- Log.Error("Problem using the credentials dialog", e);
- }
- }
+ ///
+ /// Internal login which catches the exceptions
+ ///
+ /// true if login was done sucessfully
+ private bool DoLogin(string user, string password)
+ {
+ try
+ {
+ _credentials = _confluence.login(user, password);
+ _loggedInTime = DateTime.Now;
+ _loggedIn = true;
+ }
+ catch (Exception e)
+ {
+ // Check if confluence-v2 caused an error, use v1 instead
+ if (e.Message.Contains(V2Failed) && _url.Contains("v2"))
+ {
+ Init(_url.Replace("v2", "v1"));
+ return DoLogin(user, password);
+ }
- public void Logout() {
- if (_credentials != null) {
- _confluence.logout(_credentials);
- _credentials = null;
- _loggedIn = false;
- }
- }
+ // check if auth failed
+ if (e.Message.Contains(AuthFailedExceptionName))
+ {
+ return false;
+ }
- private void CheckCredentials() {
- if (_loggedIn) {
- if (_loggedInTime.AddMinutes(_timeout-1).CompareTo(DateTime.Now) < 0) {
- Logout();
- Login();
- }
- } else {
- Login();
- }
- }
+ // Not an authentication issue
+ _loggedIn = false;
+ _credentials = null;
+ e.Data.Add("user", user);
+ e.Data.Add("url", _url);
+ throw;
+ }
- public bool IsLoggedIn => _loggedIn;
+ return true;
+ }
- public void AddAttachment(long pageId, string mime, string comment, string filename, IBinaryContainer image) {
- CheckCredentials();
- // Comment is ignored, see: http://jira.atlassian.com/browse/CONF-9395
- var attachment = new RemoteAttachment
- {
- comment = comment,
- fileName = filename,
- contentType = mime
- };
- _confluence.addAttachment(_credentials, pageId, attachment, image.ToByteArray());
- }
-
- public Page GetPage(string spaceKey, string pageTitle) {
- RemotePage page = null;
- string cacheKey = spaceKey + pageTitle;
- if (_pageCache.Contains(cacheKey)) {
- page = _pageCache[cacheKey];
- }
- if (page == null) {
- CheckCredentials();
- page = _confluence.getPage(_credentials, spaceKey, pageTitle);
- _pageCache.Add(cacheKey, page);
- }
- return new Page(page);
- }
+ public void Login()
+ {
+ Logout();
+ try
+ {
+ // Get the system name, so the user knows where to login to
+ string systemName = _url.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX1, "");
+ systemName = systemName.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX2, "");
+ CredentialsDialog dialog = new CredentialsDialog(systemName)
+ {
+ Name = null
+ };
+ while (dialog.Show(dialog.Name) == DialogResult.OK)
+ {
+ if (DoLogin(dialog.Name, dialog.Password))
+ {
+ if (dialog.SaveChecked)
+ {
+ dialog.Confirm(true);
+ }
- public Page GetPage(long pageId) {
- RemotePage page = null;
- string cacheKey = pageId.ToString();
-
- if (_pageCache.Contains(cacheKey)) {
- page = _pageCache[cacheKey];
- }
- if (page == null) {
- CheckCredentials();
- page = _confluence.getPage(_credentials, pageId);
- _pageCache.Add(cacheKey, page);
- }
- return new Page(page);
- }
+ return;
+ }
+ else
+ {
+ try
+ {
+ dialog.Confirm(false);
+ }
+ catch (ApplicationException e)
+ {
+ // exception handling ...
+ Log.Error("Problem using the credentials dialog", e);
+ }
- public Page GetSpaceHomepage(Space spaceSummary) {
- CheckCredentials();
- RemoteSpace spaceDetail = _confluence.getSpace(_credentials, spaceSummary.Key);
- RemotePage page = _confluence.getPage(_credentials, spaceDetail.homePage);
- return new Page(page);
- }
+ // For every windows version after XP show an incorrect password baloon
+ dialog.IncorrectPassword = true;
+ // Make sure the dialog is display, the password was false!
+ dialog.AlwaysDisplay = true;
+ }
+ }
+ }
+ catch (ApplicationException e)
+ {
+ // exception handling ...
+ Log.Error("Problem using the credentials dialog", e);
+ }
+ }
- public IEnumerable GetSpaceSummaries() {
- CheckCredentials();
- RemoteSpaceSummary [] spaces = _confluence.getSpaces(_credentials);
- foreach(RemoteSpaceSummary space in spaces) {
- yield return new Space(space);
- }
- }
-
- public IEnumerable GetPageChildren(Page parentPage) {
- CheckCredentials();
- RemotePageSummary[] pages = _confluence.getChildren(_credentials, parentPage.Id);
- foreach(RemotePageSummary page in pages) {
- yield return new Page(page);
- }
- }
+ public void Logout()
+ {
+ if (_credentials != null)
+ {
+ _confluence.logout(_credentials);
+ _credentials = null;
+ _loggedIn = false;
+ }
+ }
- public IEnumerable GetPageSummaries(Space space) {
- CheckCredentials();
- RemotePageSummary[] pages = _confluence.getPages(_credentials, space.Key);
- foreach(RemotePageSummary page in pages) {
- yield return new Page(page);
- }
- }
-
- public IEnumerable SearchPages(string query, string space) {
- CheckCredentials();
- foreach(var searchResult in _confluence.search(_credentials, query, 20)) {
- Log.DebugFormat("Got result of type {0}", searchResult.type);
- if ("page".Equals(searchResult.type))
- {
- yield return new Page(searchResult, space);
- }
- }
- }
- }
-}
+ private void CheckCredentials()
+ {
+ if (_loggedIn)
+ {
+ if (_loggedInTime.AddMinutes(_timeout - 1).CompareTo(DateTime.Now) < 0)
+ {
+ Logout();
+ Login();
+ }
+ }
+ else
+ {
+ Login();
+ }
+ }
+
+ public bool IsLoggedIn => _loggedIn;
+
+ public void AddAttachment(long pageId, string mime, string comment, string filename, IBinaryContainer image)
+ {
+ CheckCredentials();
+ // Comment is ignored, see: http://jira.atlassian.com/browse/CONF-9395
+ var attachment = new RemoteAttachment
+ {
+ comment = comment,
+ fileName = filename,
+ contentType = mime
+ };
+ _confluence.addAttachment(_credentials, pageId, attachment, image.ToByteArray());
+ }
+
+ public Page GetPage(string spaceKey, string pageTitle)
+ {
+ RemotePage page = null;
+ string cacheKey = spaceKey + pageTitle;
+ if (_pageCache.Contains(cacheKey))
+ {
+ page = _pageCache[cacheKey];
+ }
+
+ if (page == null)
+ {
+ CheckCredentials();
+ page = _confluence.getPage(_credentials, spaceKey, pageTitle);
+ _pageCache.Add(cacheKey, page);
+ }
+
+ return new Page(page);
+ }
+
+ public Page GetPage(long pageId)
+ {
+ RemotePage page = null;
+ string cacheKey = pageId.ToString();
+
+ if (_pageCache.Contains(cacheKey))
+ {
+ page = _pageCache[cacheKey];
+ }
+
+ if (page == null)
+ {
+ CheckCredentials();
+ page = _confluence.getPage(_credentials, pageId);
+ _pageCache.Add(cacheKey, page);
+ }
+
+ return new Page(page);
+ }
+
+ public Page GetSpaceHomepage(Space spaceSummary)
+ {
+ CheckCredentials();
+ RemoteSpace spaceDetail = _confluence.getSpace(_credentials, spaceSummary.Key);
+ RemotePage page = _confluence.getPage(_credentials, spaceDetail.homePage);
+ return new Page(page);
+ }
+
+ public IEnumerable GetSpaceSummaries()
+ {
+ CheckCredentials();
+ RemoteSpaceSummary[] spaces = _confluence.getSpaces(_credentials);
+ foreach (RemoteSpaceSummary space in spaces)
+ {
+ yield return new Space(space);
+ }
+ }
+
+ public IEnumerable GetPageChildren(Page parentPage)
+ {
+ CheckCredentials();
+ RemotePageSummary[] pages = _confluence.getChildren(_credentials, parentPage.Id);
+ foreach (RemotePageSummary page in pages)
+ {
+ yield return new Page(page);
+ }
+ }
+
+ public IEnumerable GetPageSummaries(Space space)
+ {
+ CheckCredentials();
+ RemotePageSummary[] pages = _confluence.getPages(_credentials, space.Key);
+ foreach (RemotePageSummary page in pages)
+ {
+ yield return new Page(page);
+ }
+ }
+
+ public IEnumerable SearchPages(string query, string space)
+ {
+ CheckCredentials();
+ foreach (var searchResult in _confluence.search(_credentials, query, 20))
+ {
+ Log.DebugFormat("Got result of type {0}", searchResult.type);
+ if ("page".Equals(searchResult.type))
+ {
+ yield return new Page(searchResult, space);
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceConfiguration.cs b/src/Greenshot.Plugin.Confluence/ConfluenceConfiguration.cs
index a742fc45b..df23e7768 100644
--- a/src/Greenshot.Plugin.Confluence/ConfluenceConfiguration.cs
+++ b/src/Greenshot.Plugin.Confluence/ConfluenceConfiguration.cs
@@ -23,63 +23,45 @@ using System;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.Confluence {
- ///
- /// Description of ConfluenceConfiguration.
- ///
- [Serializable]
- [IniSection("Confluence", Description="Greenshot Confluence Plugin configuration")]
- public class ConfluenceConfiguration : IniSection {
- public const string DEFAULT_POSTFIX1 = "/rpc/soap-axis/confluenceservice-v1?wsdl";
- public const string DEFAULT_POSTFIX2 = "/rpc/soap-axis/confluenceservice-v2?wsdl";
- public const string DEFAULT_PREFIX = "http://";
- private const string DEFAULT_URL = DEFAULT_PREFIX + "confluence";
+namespace Greenshot.Plugin.Confluence
+{
+ ///
+ /// Description of ConfluenceConfiguration.
+ ///
+ [Serializable]
+ [IniSection("Confluence", Description = "Greenshot Confluence Plugin configuration")]
+ public class ConfluenceConfiguration : IniSection
+ {
+ public const string DEFAULT_POSTFIX1 = "/rpc/soap-axis/confluenceservice-v1?wsdl";
+ public const string DEFAULT_POSTFIX2 = "/rpc/soap-axis/confluenceservice-v2?wsdl";
+ public const string DEFAULT_PREFIX = "http://";
+ private const string DEFAULT_URL = DEFAULT_PREFIX + "confluence";
- [IniProperty("Url", Description="Url to Confluence system, including wsdl.", DefaultValue=DEFAULT_URL)]
- public string Url {
- get;
- set;
- }
- [IniProperty("Timeout", Description="Session timeout in minutes", DefaultValue="30")]
- public int Timeout {
- get;
- set;
- }
+ [IniProperty("Url", Description = "Url to Confluence system, including wsdl.", DefaultValue = DEFAULT_URL)]
+ public string Url { get; set; }
- [IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
- public OutputFormat UploadFormat {
- get;
- set;
- }
- [IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]
- public int UploadJpegQuality {
- get;
- set;
- }
- [IniProperty("UploadReduceColors", Description="Reduce color amount of the uploaded image to 256", DefaultValue="False")]
- public bool UploadReduceColors {
- get;
- set;
- }
- [IniProperty("OpenPageAfterUpload", Description="Open the page where the picture is uploaded after upload", DefaultValue="True")]
- public bool OpenPageAfterUpload {
- get;
- set;
- }
- [IniProperty("CopyWikiMarkupForImageToClipboard", Description="Copy the Wikimarkup for the recently uploaded image to the Clipboard", DefaultValue="True")]
- public bool CopyWikiMarkupForImageToClipboard {
- get;
- set;
- }
- [IniProperty("SearchSpaceKey", Description="Key of last space that was searched for")]
- public string SearchSpaceKey {
- get;
- set;
- }
- [IniProperty("IncludePersonSpaces", Description = "Include personal spaces in the search & browse spaces list", DefaultValue = "False")]
- public bool IncludePersonSpaces {
- get;
- set;
- }
- }
-}
+ [IniProperty("Timeout", Description = "Session timeout in minutes", DefaultValue = "30")]
+ public int Timeout { get; set; }
+
+ [IniProperty("UploadFormat", Description = "What file type to use for uploading", DefaultValue = "png")]
+ public OutputFormat UploadFormat { get; set; }
+
+ [IniProperty("UploadJpegQuality", Description = "JPEG file save quality in %.", DefaultValue = "80")]
+ public int UploadJpegQuality { get; set; }
+
+ [IniProperty("UploadReduceColors", Description = "Reduce color amount of the uploaded image to 256", DefaultValue = "False")]
+ public bool UploadReduceColors { get; set; }
+
+ [IniProperty("OpenPageAfterUpload", Description = "Open the page where the picture is uploaded after upload", DefaultValue = "True")]
+ public bool OpenPageAfterUpload { get; set; }
+
+ [IniProperty("CopyWikiMarkupForImageToClipboard", Description = "Copy the Wikimarkup for the recently uploaded image to the Clipboard", DefaultValue = "True")]
+ public bool CopyWikiMarkupForImageToClipboard { get; set; }
+
+ [IniProperty("SearchSpaceKey", Description = "Key of last space that was searched for")]
+ public string SearchSpaceKey { get; set; }
+
+ [IniProperty("IncludePersonSpaces", Description = "Include personal spaces in the search & browse spaces list", DefaultValue = "False")]
+ public bool IncludePersonSpaces { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs b/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs
index d2661d141..275ace4d1 100644
--- a/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs
+++ b/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs
@@ -32,174 +32,221 @@ using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
-namespace Greenshot.Plugin.Confluence {
- ///
- /// Description of ConfluenceDestination.
- ///
- public class ConfluenceDestination : AbstractDestination {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ConfluenceDestination));
- private static readonly ConfluenceConfiguration ConfluenceConfig = IniConfig.GetIniSection();
- private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection();
- private static readonly Image ConfluenceIcon;
- private readonly Page _page;
+namespace Greenshot.Plugin.Confluence
+{
+ ///
+ /// Description of ConfluenceDestination.
+ ///
+ public class ConfluenceDestination : AbstractDestination
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ConfluenceDestination));
+ private static readonly ConfluenceConfiguration ConfluenceConfig = IniConfig.GetIniSection();
+ private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection();
+ private static readonly Image ConfluenceIcon;
+ private readonly Page _page;
- static ConfluenceDestination() {
- IsInitialized = false;
- try {
- Uri confluenceIconUri = new Uri("/GreenshotConfluencePlugin;component/Images/Confluence.ico", UriKind.Relative);
- using (Stream iconStream = Application.GetResourceStream(confluenceIconUri)?.Stream)
- {
- // TODO: Check what to do with the IImage
- ConfluenceIcon = ImageHelper.FromStream(iconStream);
- }
- IsInitialized = true;
- } catch (Exception ex) {
- Log.ErrorFormat("Problem in the confluence static initializer: {0}", ex.Message);
- }
- }
-
- public static bool IsInitialized
+ static ConfluenceDestination()
{
- get;
- private set;
+ IsInitialized = false;
+ try
+ {
+ Uri confluenceIconUri = new Uri("/GreenshotConfluencePlugin;component/Images/Confluence.ico", UriKind.Relative);
+ using (Stream iconStream = Application.GetResourceStream(confluenceIconUri)?.Stream)
+ {
+ // TODO: Check what to do with the IImage
+ ConfluenceIcon = ImageHelper.FromStream(iconStream);
+ }
+
+ IsInitialized = true;
+ }
+ catch (Exception ex)
+ {
+ Log.ErrorFormat("Problem in the confluence static initializer: {0}", ex.Message);
+ }
}
- public ConfluenceDestination() {
- }
+ public static bool IsInitialized { get; private set; }
- public ConfluenceDestination(Page page) {
- _page = page;
- }
-
- public override string Designation {
- get {
- return "Confluence";
- }
- }
+ public ConfluenceDestination()
+ {
+ }
- public override string Description {
- get {
- if (_page == null) {
- return Language.GetString("confluence", LangKey.upload_menu_item);
- } else {
- return Language.GetString("confluence", LangKey.upload_menu_item) + ": \"" + _page.Title + "\"";
- }
- }
- }
+ public ConfluenceDestination(Page page)
+ {
+ _page = page;
+ }
- public override bool IsDynamic {
- get {
- return true;
- }
- }
-
- public override bool IsActive {
- get {
- return base.IsActive && !string.IsNullOrEmpty(ConfluenceConfig.Url);
- }
- }
+ public override string Designation
+ {
+ get { return "Confluence"; }
+ }
- public override Image DisplayIcon {
- get {
- return ConfluenceIcon;
- }
- }
-
- public override IEnumerable DynamicDestinations() {
- if (ConfluencePlugin.ConfluenceConnectorNoLogin == null || !ConfluencePlugin.ConfluenceConnectorNoLogin.IsLoggedIn) {
- yield break;
- }
- List currentPages = ConfluenceUtils.GetCurrentPages();
- if (currentPages == null || currentPages.Count == 0) {
- yield break;
- }
- foreach(Page currentPage in currentPages) {
- yield return new ConfluenceDestination(currentPage);
- }
- }
+ public override string Description
+ {
+ get
+ {
+ if (_page == null)
+ {
+ return Language.GetString("confluence", LangKey.upload_menu_item);
+ }
+ else
+ {
+ return Language.GetString("confluence", LangKey.upload_menu_item) + ": \"" + _page.Title + "\"";
+ }
+ }
+ }
- public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
- ExportInformation exportInformation = new ExportInformation(Designation, Description);
- // force password check to take place before the pages load
- if (!ConfluencePlugin.ConfluenceConnector.IsLoggedIn) {
- return exportInformation;
- }
+ public override bool IsDynamic
+ {
+ get { return true; }
+ }
- Page selectedPage = _page;
- bool openPage = (_page == null) && ConfluenceConfig.OpenPageAfterUpload;
- string filename = FilenameHelper.GetFilenameWithoutExtensionFromPattern(CoreConfig.OutputFileFilenamePattern, captureDetails);
- if (selectedPage == null) {
- Forms.ConfluenceUpload confluenceUpload = new Forms.ConfluenceUpload(filename);
- bool? dialogResult = confluenceUpload.ShowDialog();
- if (dialogResult.HasValue && dialogResult.Value) {
- selectedPage = confluenceUpload.SelectedPage;
- if (confluenceUpload.IsOpenPageSelected) {
- openPage = false;
- }
- filename = confluenceUpload.Filename;
- }
- }
- string extension = "." + ConfluenceConfig.UploadFormat;
- if (!filename.ToLower().EndsWith(extension)) {
- filename += extension;
- }
- if (selectedPage != null) {
+ public override bool IsActive
+ {
+ get { return base.IsActive && !string.IsNullOrEmpty(ConfluenceConfig.Url); }
+ }
+
+ public override Image DisplayIcon
+ {
+ get { return ConfluenceIcon; }
+ }
+
+ public override IEnumerable DynamicDestinations()
+ {
+ if (ConfluencePlugin.ConfluenceConnectorNoLogin == null || !ConfluencePlugin.ConfluenceConnectorNoLogin.IsLoggedIn)
+ {
+ yield break;
+ }
+
+ List currentPages = ConfluenceUtils.GetCurrentPages();
+ if (currentPages == null || currentPages.Count == 0)
+ {
+ yield break;
+ }
+
+ foreach (Page currentPage in currentPages)
+ {
+ yield return new ConfluenceDestination(currentPage);
+ }
+ }
+
+ public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
+ {
+ ExportInformation exportInformation = new ExportInformation(Designation, Description);
+ // force password check to take place before the pages load
+ if (!ConfluencePlugin.ConfluenceConnector.IsLoggedIn)
+ {
+ return exportInformation;
+ }
+
+ Page selectedPage = _page;
+ bool openPage = (_page == null) && ConfluenceConfig.OpenPageAfterUpload;
+ string filename = FilenameHelper.GetFilenameWithoutExtensionFromPattern(CoreConfig.OutputFileFilenamePattern, captureDetails);
+ if (selectedPage == null)
+ {
+ Forms.ConfluenceUpload confluenceUpload = new Forms.ConfluenceUpload(filename);
+ bool? dialogResult = confluenceUpload.ShowDialog();
+ if (dialogResult.HasValue && dialogResult.Value)
+ {
+ selectedPage = confluenceUpload.SelectedPage;
+ if (confluenceUpload.IsOpenPageSelected)
+ {
+ openPage = false;
+ }
+
+ filename = confluenceUpload.Filename;
+ }
+ }
+
+ string extension = "." + ConfluenceConfig.UploadFormat;
+ if (!filename.ToLower().EndsWith(extension))
+ {
+ filename += extension;
+ }
+
+ if (selectedPage != null)
+ {
bool uploaded = Upload(surface, selectedPage, filename, out var errorMessage);
- if (uploaded) {
- if (openPage) {
- try
- {
- Process.Start(selectedPage.Url);
- }
- catch
- {
- // Ignore
- }
- }
- exportInformation.ExportMade = true;
- exportInformation.Uri = selectedPage.Url;
- } else {
- exportInformation.ErrorMessage = errorMessage;
- }
- }
- ProcessExport(exportInformation, surface);
- return exportInformation;
- }
+ if (uploaded)
+ {
+ if (openPage)
+ {
+ try
+ {
+ Process.Start(selectedPage.Url);
+ }
+ catch
+ {
+ // Ignore
+ }
+ }
- private bool Upload(ISurface surfaceToUpload, Page page, string filename, out string errorMessage) {
- SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(ConfluenceConfig.UploadFormat, ConfluenceConfig.UploadJpegQuality, ConfluenceConfig.UploadReduceColors);
- errorMessage = null;
- try {
- new PleaseWaitForm().ShowAndWait(Description, Language.GetString("confluence", LangKey.communication_wait),
- delegate {
- ConfluencePlugin.ConfluenceConnector.AddAttachment(page.Id, "image/" + ConfluenceConfig.UploadFormat.ToString().ToLower(), null, filename, new SurfaceContainer(surfaceToUpload, outputSettings, filename));
- }
- );
- Log.Debug("Uploaded to Confluence.");
- if (!ConfluenceConfig.CopyWikiMarkupForImageToClipboard)
- {
- return true;
- }
- int retryCount = 2;
- while (retryCount >= 0) {
- try {
- Clipboard.SetText("!" + filename + "!");
- break;
- } catch (Exception ee) {
- if (retryCount == 0) {
- Log.Error(ee);
- } else {
- Thread.Sleep(100);
- }
- } finally {
- --retryCount;
- }
- }
- return true;
- } catch(Exception e) {
- errorMessage = e.Message;
- }
- return false;
- }
- }
-}
+ exportInformation.ExportMade = true;
+ exportInformation.Uri = selectedPage.Url;
+ }
+ else
+ {
+ exportInformation.ErrorMessage = errorMessage;
+ }
+ }
+
+ ProcessExport(exportInformation, surface);
+ return exportInformation;
+ }
+
+ private bool Upload(ISurface surfaceToUpload, Page page, string filename, out string errorMessage)
+ {
+ SurfaceOutputSettings outputSettings =
+ new SurfaceOutputSettings(ConfluenceConfig.UploadFormat, ConfluenceConfig.UploadJpegQuality, ConfluenceConfig.UploadReduceColors);
+ errorMessage = null;
+ try
+ {
+ new PleaseWaitForm().ShowAndWait(Description, Language.GetString("confluence", LangKey.communication_wait),
+ delegate
+ {
+ ConfluencePlugin.ConfluenceConnector.AddAttachment(page.Id, "image/" + ConfluenceConfig.UploadFormat.ToString().ToLower(), null, filename,
+ new SurfaceContainer(surfaceToUpload, outputSettings, filename));
+ }
+ );
+ Log.Debug("Uploaded to Confluence.");
+ if (!ConfluenceConfig.CopyWikiMarkupForImageToClipboard)
+ {
+ return true;
+ }
+
+ int retryCount = 2;
+ while (retryCount >= 0)
+ {
+ try
+ {
+ Clipboard.SetText("!" + filename + "!");
+ break;
+ }
+ catch (Exception ee)
+ {
+ if (retryCount == 0)
+ {
+ Log.Error(ee);
+ }
+ else
+ {
+ Thread.Sleep(100);
+ }
+ }
+ finally
+ {
+ --retryCount;
+ }
+ }
+
+ return true;
+ }
+ catch (Exception e)
+ {
+ errorMessage = e.Message;
+ }
+
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs b/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs
index 4cca23c8f..fbe852691 100644
--- a/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs
+++ b/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs
@@ -28,109 +28,142 @@ using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
-namespace Greenshot.Plugin.Confluence {
- ///
- /// This is the ConfluencePlugin base code
- ///
- [Plugin("Confluence", true)]
- public class ConfluencePlugin : IGreenshotPlugin {
- private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluencePlugin));
- private static ConfluenceConnector _confluenceConnector;
- private static ConfluenceConfiguration _config;
+namespace Greenshot.Plugin.Confluence
+{
+ ///
+ /// This is the ConfluencePlugin base code
+ ///
+ [Plugin("Confluence", true)]
+ public class ConfluencePlugin : IGreenshotPlugin
+ {
+ private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluencePlugin));
+ private static ConfluenceConnector _confluenceConnector;
+ private static ConfluenceConfiguration _config;
- public void Dispose() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- protected void Dispose(bool disposing) {
- //if (disposing) {}
- }
+ protected void Dispose(bool disposing)
+ {
+ //if (disposing) {}
+ }
- private static void CreateConfluenceConnector() {
- if (_confluenceConnector == null) {
- if (_config.Url.Contains("soap-axis")) {
- _confluenceConnector = new ConfluenceConnector(_config.Url, _config.Timeout);
- } else {
- _confluenceConnector = new ConfluenceConnector(_config.Url + ConfluenceConfiguration.DEFAULT_POSTFIX2, _config.Timeout);
- }
- }
- }
+ private static void CreateConfluenceConnector()
+ {
+ if (_confluenceConnector == null)
+ {
+ if (_config.Url.Contains("soap-axis"))
+ {
+ _confluenceConnector = new ConfluenceConnector(_config.Url, _config.Timeout);
+ }
+ else
+ {
+ _confluenceConnector = new ConfluenceConnector(_config.Url + ConfluenceConfiguration.DEFAULT_POSTFIX2, _config.Timeout);
+ }
+ }
+ }
- public static ConfluenceConnector ConfluenceConnectorNoLogin {
- get {
- return _confluenceConnector;
- }
- }
+ public static ConfluenceConnector ConfluenceConnectorNoLogin
+ {
+ get { return _confluenceConnector; }
+ }
- public static ConfluenceConnector ConfluenceConnector {
- get {
- if (_confluenceConnector == null) {
- CreateConfluenceConnector();
- }
- try {
- if (_confluenceConnector != null && !_confluenceConnector.IsLoggedIn) {
- _confluenceConnector.Login();
- }
- } catch (Exception e) {
- MessageBox.Show(Language.GetFormattedString("confluence", LangKey.login_error, e.Message));
- }
- return _confluenceConnector;
- }
- }
+ public static ConfluenceConnector ConfluenceConnector
+ {
+ get
+ {
+ if (_confluenceConnector == null)
+ {
+ CreateConfluenceConnector();
+ }
+
+ try
+ {
+ if (_confluenceConnector != null && !_confluenceConnector.IsLoggedIn)
+ {
+ _confluenceConnector.Login();
+ }
+ }
+ catch (Exception e)
+ {
+ MessageBox.Show(Language.GetFormattedString("confluence", LangKey.login_error, e.Message));
+ }
+
+ return _confluenceConnector;
+ }
+ }
+
+ ///
+ /// Implementation of the IGreenshotPlugin.Initialize
+ ///
+ public bool Initialize()
+ {
+ // Register configuration (don't need the configuration itself)
+ _config = IniConfig.GetIniSection();
+ if (_config.IsDirty)
+ {
+ IniConfig.Save();
+ }
+
+ try
+ {
+ TranslationManager.Instance.TranslationProvider = new LanguageXMLTranslationProvider();
+ //resources = new ComponentResourceManager(typeof(ConfluencePlugin));
+ }
+ catch (Exception ex)
+ {
+ LOG.ErrorFormat("Problem in ConfluencePlugin.Initialize: {0}", ex.Message);
+ return false;
+ }
- ///
- /// Implementation of the IGreenshotPlugin.Initialize
- ///
- public bool Initialize() {
- // Register configuration (don't need the configuration itself)
- _config = IniConfig.GetIniSection();
- if(_config.IsDirty) {
- IniConfig.Save();
- }
- try {
- TranslationManager.Instance.TranslationProvider = new LanguageXMLTranslationProvider();
- //resources = new ComponentResourceManager(typeof(ConfluencePlugin));
- } catch (Exception ex) {
- LOG.ErrorFormat("Problem in ConfluencePlugin.Initialize: {0}", ex.Message);
- return false;
- }
if (ConfluenceDestination.IsInitialized)
{
SimpleServiceProvider.Current.AddService(new ConfluenceDestination());
}
- return true;
- }
- public void Shutdown() {
- LOG.Debug("Confluence Plugin shutdown.");
- if (_confluenceConnector != null) {
- _confluenceConnector.Logout();
- _confluenceConnector = null;
- }
- }
+ return true;
+ }
- ///
- /// Implementation of the IPlugin.Configure
- ///
- public void Configure() {
- ConfluenceConfiguration clonedConfig = _config.Clone();
- ConfluenceConfigurationForm configForm = new ConfluenceConfigurationForm(clonedConfig);
- string url = _config.Url;
- bool? dialogResult = configForm.ShowDialog();
- if (dialogResult.HasValue && dialogResult.Value) {
- // copy the new object to the old...
- clonedConfig.CloneTo(_config);
- IniConfig.Save();
- if (_confluenceConnector != null) {
- if (!url.Equals(_config.Url)) {
- if (_confluenceConnector.IsLoggedIn) {
- _confluenceConnector.Logout();
- }
- _confluenceConnector = null;
- }
- }
- }
- }
- }
-}
+ public void Shutdown()
+ {
+ LOG.Debug("Confluence Plugin shutdown.");
+ if (_confluenceConnector != null)
+ {
+ _confluenceConnector.Logout();
+ _confluenceConnector = null;
+ }
+ }
+
+ ///
+ /// Implementation of the IPlugin.Configure
+ ///
+ public void Configure()
+ {
+ ConfluenceConfiguration clonedConfig = _config.Clone();
+ ConfluenceConfigurationForm configForm = new ConfluenceConfigurationForm(clonedConfig);
+ string url = _config.Url;
+ bool? dialogResult = configForm.ShowDialog();
+ if (dialogResult.HasValue && dialogResult.Value)
+ {
+ // copy the new object to the old...
+ clonedConfig.CloneTo(_config);
+ IniConfig.Save();
+ if (_confluenceConnector != null)
+ {
+ if (!url.Equals(_config.Url))
+ {
+ if (_confluenceConnector.IsLoggedIn)
+ {
+ _confluenceConnector.Logout();
+ }
+
+ _confluenceConnector = null;
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs
index 55a40fa8c..2c878d6d9 100644
--- a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs
+++ b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs
@@ -26,126 +26,172 @@ using System.Text.RegularExpressions;
using System.Windows.Automation;
using GreenshotPlugin.Core;
-namespace Greenshot.Plugin.Confluence {
- ///
- /// Description of ConfluenceUtils.
- ///
- public class ConfluenceUtils {
- private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceUtils));
+namespace Greenshot.Plugin.Confluence
+{
+ ///
+ /// Description of ConfluenceUtils.
+ ///
+ public class ConfluenceUtils
+ {
+ private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceUtils));
- public static List GetCurrentPages() {
- List pages = new List();
- Regex pageIdRegex = new Regex(@"pageId=(\d+)");
- Regex spacePageRegex = new Regex(@"\/display\/([^\/]+)\/([^#]+)");
- foreach(string browserurl in GetBrowserUrls()) {
- string url;
- try {
- url = Uri.UnescapeDataString(browserurl).Replace("+", " ");
- } catch {
- LOG.WarnFormat("Error processing URL: {0}", browserurl);
- continue;
- }
- MatchCollection pageIdMatch = pageIdRegex.Matches(url);
- if (pageIdMatch != null && pageIdMatch.Count > 0) {
- long pageId = long.Parse(pageIdMatch[0].Groups[1].Value);
- try {
- bool pageDouble = false;
- foreach(Page page in pages) {
- if (page.Id == pageId) {
- pageDouble = true;
- LOG.DebugFormat("Skipping double page with ID {0}", pageId);
- break;
- }
- }
- if (!pageDouble) {
- Page page = ConfluencePlugin.ConfluenceConnector.GetPage(pageId);
- LOG.DebugFormat("Adding page {0}", page.Title);
- pages.Add(page);
- }
- continue;
- } catch (Exception ex) {
- // Preventing security problems
- LOG.DebugFormat("Couldn't get page details for PageID {0}", pageId);
- LOG.Warn(ex);
- }
- }
- MatchCollection spacePageMatch = spacePageRegex.Matches(url);
- if (spacePageMatch != null && spacePageMatch.Count > 0) {
- if (spacePageMatch[0].Groups.Count >= 2) {
- string space = spacePageMatch[0].Groups[1].Value;
- string title = spacePageMatch[0].Groups[2].Value;
- if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(space)) {
- continue;
- }
- if (title.EndsWith("#")) {
- title = title.Substring(0, title.Length-1);
- }
- try {
- bool pageDouble = false;
- foreach(Page page in pages) {
- if (page.Title.Equals(title)) {
- LOG.DebugFormat("Skipping double page with title {0}", title);
- pageDouble = true;
- break;
- }
- }
- if (!pageDouble) {
- Page page = ConfluencePlugin.ConfluenceConnector.GetPage(space, title);
- LOG.DebugFormat("Adding page {0}", page.Title);
- pages.Add(page);
-
- }
- } catch (Exception ex) {
- // Preventing security problems
- LOG.DebugFormat("Couldn't get page details for space {0} / title {1}", space, title);
- LOG.Warn(ex);
- }
- }
- }
- }
- return pages;
- }
+ public static List GetCurrentPages()
+ {
+ List pages = new List();
+ Regex pageIdRegex = new Regex(@"pageId=(\d+)");
+ Regex spacePageRegex = new Regex(@"\/display\/([^\/]+)\/([^#]+)");
+ foreach (string browserurl in GetBrowserUrls())
+ {
+ string url;
+ try
+ {
+ url = Uri.UnescapeDataString(browserurl).Replace("+", " ");
+ }
+ catch
+ {
+ LOG.WarnFormat("Error processing URL: {0}", browserurl);
+ continue;
+ }
- private static IEnumerable GetBrowserUrls() {
- HashSet urls = new HashSet();
+ MatchCollection pageIdMatch = pageIdRegex.Matches(url);
+ if (pageIdMatch != null && pageIdMatch.Count > 0)
+ {
+ long pageId = long.Parse(pageIdMatch[0].Groups[1].Value);
+ try
+ {
+ bool pageDouble = false;
+ foreach (Page page in pages)
+ {
+ if (page.Id == pageId)
+ {
+ pageDouble = true;
+ LOG.DebugFormat("Skipping double page with ID {0}", pageId);
+ break;
+ }
+ }
- // FireFox
- foreach (WindowDetails window in WindowDetails.GetAllWindows("MozillaWindowClass")) {
- if (window.Text.Length == 0) {
- continue;
- }
- AutomationElement currentElement = AutomationElement.FromHandle(window.Handle);
- Condition conditionCustom = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom), new PropertyCondition(AutomationElement.IsOffscreenProperty, false));
- for (int i = 5; i > 0 && currentElement != null; i--) {
- currentElement = currentElement.FindFirst(TreeScope.Children, conditionCustom);
- }
- if (currentElement == null) {
- continue;
- }
+ if (!pageDouble)
+ {
+ Page page = ConfluencePlugin.ConfluenceConnector.GetPage(pageId);
+ LOG.DebugFormat("Adding page {0}", page.Title);
+ pages.Add(page);
+ }
- Condition conditionDocument = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document), new PropertyCondition(AutomationElement.IsOffscreenProperty, false));
- AutomationElement docElement = currentElement.FindFirst(TreeScope.Children, conditionDocument);
- if (docElement == null) {
- continue;
- }
- foreach (AutomationPattern pattern in docElement.GetSupportedPatterns()) {
- if (pattern.ProgrammaticName != "ValuePatternIdentifiers.Pattern") {
- continue;
- }
- string url = (docElement.GetCurrentPattern(pattern) as ValuePattern).Current.Value;
- if (!string.IsNullOrEmpty(url)) {
- urls.Add(url);
- break;
- }
- }
- }
+ continue;
+ }
+ catch (Exception ex)
+ {
+ // Preventing security problems
+ LOG.DebugFormat("Couldn't get page details for PageID {0}", pageId);
+ LOG.Warn(ex);
+ }
+ }
- foreach(string url in IEHelper.GetIEUrls().Distinct()) {
- urls.Add(url);
- }
+ MatchCollection spacePageMatch = spacePageRegex.Matches(url);
+ if (spacePageMatch != null && spacePageMatch.Count > 0)
+ {
+ if (spacePageMatch[0].Groups.Count >= 2)
+ {
+ string space = spacePageMatch[0].Groups[1].Value;
+ string title = spacePageMatch[0].Groups[2].Value;
+ if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(space))
+ {
+ continue;
+ }
- return urls;
- }
+ if (title.EndsWith("#"))
+ {
+ title = title.Substring(0, title.Length - 1);
+ }
- }
-}
+ try
+ {
+ bool pageDouble = false;
+ foreach (Page page in pages)
+ {
+ if (page.Title.Equals(title))
+ {
+ LOG.DebugFormat("Skipping double page with title {0}", title);
+ pageDouble = true;
+ break;
+ }
+ }
+
+ if (!pageDouble)
+ {
+ Page page = ConfluencePlugin.ConfluenceConnector.GetPage(space, title);
+ LOG.DebugFormat("Adding page {0}", page.Title);
+ pages.Add(page);
+ }
+ }
+ catch (Exception ex)
+ {
+ // Preventing security problems
+ LOG.DebugFormat("Couldn't get page details for space {0} / title {1}", space, title);
+ LOG.Warn(ex);
+ }
+ }
+ }
+ }
+
+ return pages;
+ }
+
+ private static IEnumerable GetBrowserUrls()
+ {
+ HashSet urls = new HashSet();
+
+ // FireFox
+ foreach (WindowDetails window in WindowDetails.GetAllWindows("MozillaWindowClass"))
+ {
+ if (window.Text.Length == 0)
+ {
+ continue;
+ }
+
+ AutomationElement currentElement = AutomationElement.FromHandle(window.Handle);
+ Condition conditionCustom = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom),
+ new PropertyCondition(AutomationElement.IsOffscreenProperty, false));
+ for (int i = 5; i > 0 && currentElement != null; i--)
+ {
+ currentElement = currentElement.FindFirst(TreeScope.Children, conditionCustom);
+ }
+
+ if (currentElement == null)
+ {
+ continue;
+ }
+
+ Condition conditionDocument = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document),
+ new PropertyCondition(AutomationElement.IsOffscreenProperty, false));
+ AutomationElement docElement = currentElement.FindFirst(TreeScope.Children, conditionDocument);
+ if (docElement == null)
+ {
+ continue;
+ }
+
+ foreach (AutomationPattern pattern in docElement.GetSupportedPatterns())
+ {
+ if (pattern.ProgrammaticName != "ValuePatternIdentifiers.Pattern")
+ {
+ continue;
+ }
+
+ string url = (docElement.GetCurrentPattern(pattern) as ValuePattern).Current.Value;
+ if (!string.IsNullOrEmpty(url))
+ {
+ urls.Add(url);
+ break;
+ }
+ }
+ }
+
+ foreach (string url in IEHelper.GetIEUrls().Distinct())
+ {
+ urls.Add(url);
+ }
+
+ return urls;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs
index 185593c87..c4023a828 100644
--- a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs
+++ b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs
@@ -28,70 +28,87 @@ using System.Reflection;
using System.Windows.Data;
using GreenshotPlugin.Core;
-namespace Greenshot.Plugin.Confluence {
- public class EnumDisplayer : IValueConverter {
- private Type _type;
- private IDictionary _displayValues;
- private IDictionary _reverseValues;
+namespace Greenshot.Plugin.Confluence
+{
+ public class EnumDisplayer : IValueConverter
+ {
+ private Type _type;
+ private IDictionary _displayValues;
+ private IDictionary _reverseValues;
- public Type Type {
- get { return _type; }
- set {
- if (!value.IsEnum) {
- throw new ArgumentException("parameter is not an Enumerated type", nameof(value));
- }
- _type = value;
- }
- }
-
- public ReadOnlyCollection DisplayNames {
- get {
- var genericTypeDefinition = typeof(Dictionary<,>).GetGenericTypeDefinition();
- if (genericTypeDefinition != null)
- {
- _reverseValues = (IDictionary) Activator.CreateInstance(genericTypeDefinition.MakeGenericType(typeof(string),_type));
- }
+ public Type Type
+ {
+ get { return _type; }
+ set
+ {
+ if (!value.IsEnum)
+ {
+ throw new ArgumentException("parameter is not an Enumerated type", nameof(value));
+ }
- var typeDefinition = typeof(Dictionary<,>).GetGenericTypeDefinition();
- if (typeDefinition != null)
- {
- _displayValues = (IDictionary)Activator.CreateInstance(typeDefinition.MakeGenericType(_type, typeof(string)));
- }
+ _type = value;
+ }
+ }
- var fields = _type.GetFields(BindingFlags.Public | BindingFlags.Static);
- foreach (var field in fields) {
- DisplayKeyAttribute[] a = (DisplayKeyAttribute[])field.GetCustomAttributes(typeof(DisplayKeyAttribute), false);
-
- string displayKey = GetDisplayKeyValue(a);
- object enumValue = field.GetValue(null);
-
- string displayString;
- if (displayKey != null && Language.HasKey(displayKey)) {
- displayString = Language.GetString(displayKey);
- }
- displayString = displayKey ?? enumValue.ToString();
+ public ReadOnlyCollection DisplayNames
+ {
+ get
+ {
+ var genericTypeDefinition = typeof(Dictionary<,>).GetGenericTypeDefinition();
+ if (genericTypeDefinition != null)
+ {
+ _reverseValues = (IDictionary) Activator.CreateInstance(genericTypeDefinition.MakeGenericType(typeof(string), _type));
+ }
- _displayValues.Add(enumValue, displayString);
- _reverseValues.Add(displayString, enumValue);
- }
- return new List((IEnumerable)_displayValues.Values).AsReadOnly();
- }
- }
-
- private static string GetDisplayKeyValue(DisplayKeyAttribute[] a) {
- if (a == null || a.Length == 0) {
- return null;
- }
- DisplayKeyAttribute dka = a[0];
- return dka.Value;
- }
-
- object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) {
- return _displayValues[value];
- }
-
- object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
- return _reverseValues[value];
- }
- }
-}
+ var typeDefinition = typeof(Dictionary<,>).GetGenericTypeDefinition();
+ if (typeDefinition != null)
+ {
+ _displayValues = (IDictionary) Activator.CreateInstance(typeDefinition.MakeGenericType(_type, typeof(string)));
+ }
+
+ var fields = _type.GetFields(BindingFlags.Public | BindingFlags.Static);
+ foreach (var field in fields)
+ {
+ DisplayKeyAttribute[] a = (DisplayKeyAttribute[]) field.GetCustomAttributes(typeof(DisplayKeyAttribute), false);
+
+ string displayKey = GetDisplayKeyValue(a);
+ object enumValue = field.GetValue(null);
+
+ string displayString;
+ if (displayKey != null && Language.HasKey(displayKey))
+ {
+ displayString = Language.GetString(displayKey);
+ }
+
+ displayString = displayKey ?? enumValue.ToString();
+
+ _displayValues.Add(enumValue, displayString);
+ _reverseValues.Add(displayString, enumValue);
+ }
+
+ return new List((IEnumerable) _displayValues.Values).AsReadOnly();
+ }
+ }
+
+ private static string GetDisplayKeyValue(DisplayKeyAttribute[] a)
+ {
+ if (a == null || a.Length == 0)
+ {
+ return null;
+ }
+
+ DisplayKeyAttribute dka = a[0];
+ return dka.Value;
+ }
+
+ object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ return _displayValues[value];
+ }
+
+ object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ return _reverseValues[value];
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs
index cd31165ba..dd9d46a1b 100644
--- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs
+++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs
@@ -21,21 +21,25 @@
using System.Windows;
-namespace Greenshot.Plugin.Confluence.Forms {
- ///
- /// Interaction logic for ConfluenceConfigurationForm.xaml
- ///
- public partial class ConfluenceConfigurationForm : Window {
- public ConfluenceConfiguration Config { get; }
+namespace Greenshot.Plugin.Confluence.Forms
+{
+ ///
+ /// Interaction logic for ConfluenceConfigurationForm.xaml
+ ///
+ public partial class ConfluenceConfigurationForm : Window
+ {
+ public ConfluenceConfiguration Config { get; }
- public ConfluenceConfigurationForm(ConfluenceConfiguration config) {
- DataContext = config;
- Config = config;
- InitializeComponent();
- }
+ public ConfluenceConfigurationForm(ConfluenceConfiguration config)
+ {
+ DataContext = config;
+ Config = config;
+ InitializeComponent();
+ }
- private void Button_OK_Click(object sender, RoutedEventArgs e) {
- DialogResult = true;
- }
- }
+ private void Button_OK_Click(object sender, RoutedEventArgs e)
+ {
+ DialogResult = true;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs
index 55ca76659..de3ffc934 100644
--- a/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs
+++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs
@@ -21,36 +21,44 @@
using System.Collections.Generic;
-namespace Greenshot.Plugin.Confluence.Forms {
- ///
- /// Interaction logic for ConfluencePagePicker.xaml
- ///
- public partial class ConfluencePagePicker
- {
- private readonly ConfluenceUpload _confluenceUpload;
+namespace Greenshot.Plugin.Confluence.Forms
+{
+ ///
+ /// Interaction logic for ConfluencePagePicker.xaml
+ ///
+ public partial class ConfluencePagePicker
+ {
+ private readonly ConfluenceUpload _confluenceUpload;
- public ConfluencePagePicker(ConfluenceUpload confluenceUpload, List pagesToPick) {
- _confluenceUpload = confluenceUpload;
- DataContext = pagesToPick;
- InitializeComponent();
- }
+ public ConfluencePagePicker(ConfluenceUpload confluenceUpload, List pagesToPick)
+ {
+ _confluenceUpload = confluenceUpload;
+ DataContext = pagesToPick;
+ InitializeComponent();
+ }
- private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
- SelectionChanged();
- }
+ private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
+ {
+ SelectionChanged();
+ }
- private void SelectionChanged() {
- if (PageListView.HasItems && PageListView.SelectedItems.Count > 0) {
- _confluenceUpload.SelectedPage = (Page)PageListView.SelectedItem;
- // Make sure the uploader knows we selected an already opened page
- _confluenceUpload.IsOpenPageSelected = true;
- } else {
- _confluenceUpload.SelectedPage = null;
- }
- }
+ private void SelectionChanged()
+ {
+ if (PageListView.HasItems && PageListView.SelectedItems.Count > 0)
+ {
+ _confluenceUpload.SelectedPage = (Page) PageListView.SelectedItem;
+ // Make sure the uploader knows we selected an already opened page
+ _confluenceUpload.IsOpenPageSelected = true;
+ }
+ else
+ {
+ _confluenceUpload.SelectedPage = null;
+ }
+ }
- private void Page_Loaded(object sender, System.Windows.RoutedEventArgs e) {
- SelectionChanged();
- }
- }
+ private void Page_Loaded(object sender, System.Windows.RoutedEventArgs e)
+ {
+ SelectionChanged();
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs
index a39c36a39..2b296f5f0 100644
--- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs
+++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs
@@ -25,69 +25,88 @@ using System.Linq;
using System.Windows;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.Confluence.Forms {
- public partial class ConfluenceSearch
- {
- private static readonly ConfluenceConfiguration ConfluenceConfig = IniConfig.GetIniSection();
- private readonly ConfluenceUpload _confluenceUpload;
-
- public IEnumerable Spaces => _confluenceUpload.Spaces;
+namespace Greenshot.Plugin.Confluence.Forms
+{
+ public partial class ConfluenceSearch
+ {
+ private static readonly ConfluenceConfiguration ConfluenceConfig = IniConfig.GetIniSection();
+ private readonly ConfluenceUpload _confluenceUpload;
- public ObservableCollection Pages { get; } = new ObservableCollection();
+ public IEnumerable Spaces => _confluenceUpload.Spaces;
- public ConfluenceSearch(ConfluenceUpload confluenceUpload) {
- _confluenceUpload = confluenceUpload;
- DataContext = this;
- InitializeComponent();
- if (ConfluenceConfig.SearchSpaceKey == null) {
- SpaceComboBox.SelectedItem = Spaces.FirstOrDefault();
- } else {
- foreach(var space in Spaces) {
- if (space.Key.Equals(ConfluenceConfig.SearchSpaceKey)) {
- SpaceComboBox.SelectedItem = space;
- }
- }
- }
- }
+ public ObservableCollection Pages { get; } = new ObservableCollection();
- private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
- SelectionChanged();
- }
+ public ConfluenceSearch(ConfluenceUpload confluenceUpload)
+ {
+ _confluenceUpload = confluenceUpload;
+ DataContext = this;
+ InitializeComponent();
+ if (ConfluenceConfig.SearchSpaceKey == null)
+ {
+ SpaceComboBox.SelectedItem = Spaces.FirstOrDefault();
+ }
+ else
+ {
+ foreach (var space in Spaces)
+ {
+ if (space.Key.Equals(ConfluenceConfig.SearchSpaceKey))
+ {
+ SpaceComboBox.SelectedItem = space;
+ }
+ }
+ }
+ }
- private void SelectionChanged() {
- if (PageListView.HasItems && PageListView.SelectedItems.Count > 0) {
- _confluenceUpload.SelectedPage = (Page)PageListView.SelectedItem;
- } else {
- _confluenceUpload.SelectedPage = null;
- }
- }
+ private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
+ {
+ SelectionChanged();
+ }
- private void Search_Click(object sender, RoutedEventArgs e) {
- DoSearch();
- }
+ private void SelectionChanged()
+ {
+ if (PageListView.HasItems && PageListView.SelectedItems.Count > 0)
+ {
+ _confluenceUpload.SelectedPage = (Page) PageListView.SelectedItem;
+ }
+ else
+ {
+ _confluenceUpload.SelectedPage = null;
+ }
+ }
- private void DoSearch() {
- string spaceKey = (string)SpaceComboBox.SelectedValue;
- ConfluenceConfig.SearchSpaceKey = spaceKey;
- Pages.Clear();
- foreach(var page in ConfluencePlugin.ConfluenceConnector.SearchPages(searchText.Text, spaceKey).OrderBy(p => p.Title)) {
- Pages.Add(page);
- }
- }
+ private void Search_Click(object sender, RoutedEventArgs e)
+ {
+ DoSearch();
+ }
- private void SearchText_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) {
- if (e.Key == System.Windows.Input.Key.Return && Search.IsEnabled) {
- DoSearch();
- e.Handled = true;
- }
- }
+ private void DoSearch()
+ {
+ string spaceKey = (string) SpaceComboBox.SelectedValue;
+ ConfluenceConfig.SearchSpaceKey = spaceKey;
+ Pages.Clear();
+ foreach (var page in ConfluencePlugin.ConfluenceConnector.SearchPages(searchText.Text, spaceKey).OrderBy(p => p.Title))
+ {
+ Pages.Add(page);
+ }
+ }
- private void Page_Loaded(object sender, RoutedEventArgs e) {
- SelectionChanged();
- }
+ private void SearchText_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
+ {
+ if (e.Key == System.Windows.Input.Key.Return && Search.IsEnabled)
+ {
+ DoSearch();
+ e.Handled = true;
+ }
+ }
- private void SearchText_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) {
- Search.IsEnabled = !string.IsNullOrEmpty(searchText.Text);
- }
- }
+ private void Page_Loaded(object sender, RoutedEventArgs e)
+ {
+ SelectionChanged();
+ }
+
+ private void SearchText_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
+ {
+ Search.IsEnabled = !string.IsNullOrEmpty(searchText.Text);
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceTreePicker.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceTreePicker.xaml.cs
index cff4878be..62089b4ed 100644
--- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceTreePicker.xaml.cs
+++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceTreePicker.xaml.cs
@@ -27,101 +27,131 @@ using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
-namespace Greenshot.Plugin.Confluence.Forms {
- ///
- /// Interaction logic for ConfluenceTreePicker.xaml
- ///
- 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;
- _confluenceUpload = confluenceUpload;
- InitializeComponent();
- }
+namespace Greenshot.Plugin.Confluence.Forms
+{
+ ///
+ /// Interaction logic for ConfluenceTreePicker.xaml
+ ///
+ 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;
- private void PageTreeViewItem_DoubleClick(object sender, MouseButtonEventArgs eventArgs) {
- Log.Debug("spaceTreeViewItem_MouseLeftButtonDown is called!");
- TreeViewItem clickedItem = eventArgs.Source as TreeViewItem;
- if (clickedItem?.Tag is not Page page) {
- return;
- }
- if (clickedItem.HasItems)
- {
- return;
- }
- Log.Debug("Loading pages for page: " + page.Title);
- new Thread(() => {
- Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => {ShowBusy.Visibility = Visibility.Visible;}));
- var pages = _confluenceConnector.GetPageChildren(page).OrderBy(p => p.Title);
- Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => {
- foreach(var childPage in pages) {
- Log.Debug("Adding page: " + childPage.Title);
- var pageTreeViewItem = new TreeViewItem
- {
- Header = childPage.Title,
- Tag = childPage
- };
- clickedItem.Items.Add(pageTreeViewItem);
- pageTreeViewItem.PreviewMouseDoubleClick += PageTreeViewItem_DoubleClick;
- pageTreeViewItem.PreviewMouseLeftButtonDown += PageTreeViewItem_Click;
- }
- ShowBusy.Visibility = Visibility.Collapsed;
- }));
- }) { Name = "Loading childpages for confluence page " + page.Title }.Start();
- }
+ public ConfluenceTreePicker(ConfluenceUpload confluenceUpload)
+ {
+ _confluenceConnector = ConfluencePlugin.ConfluenceConnector;
+ _confluenceUpload = confluenceUpload;
+ InitializeComponent();
+ }
- private void PageTreeViewItem_Click(object sender, MouseButtonEventArgs eventArgs) {
- Log.Debug("pageTreeViewItem_PreviewMouseDoubleClick is called!");
- if (eventArgs.Source is not TreeViewItem clickedItem) {
- return;
- }
- Page page = clickedItem.Tag as Page;
- _confluenceUpload.SelectedPage = page;
- if (page != null) {
- Log.Debug("Page selected: " + page.Title);
- }
- }
+ private void PageTreeViewItem_DoubleClick(object sender, MouseButtonEventArgs eventArgs)
+ {
+ Log.Debug("spaceTreeViewItem_MouseLeftButtonDown is called!");
+ TreeViewItem clickedItem = eventArgs.Source as TreeViewItem;
+ if (clickedItem?.Tag is not Page page)
+ {
+ return;
+ }
- private void Page_Loaded(object sender, RoutedEventArgs e) {
- _confluenceUpload.SelectedPage = null;
- if (_isInitDone) {
- return;
- }
- ShowBusy.Visibility = Visibility.Visible;
- new Thread(() => {
- Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() => {
- foreach (Space space in _confluenceUpload.Spaces) {
- TreeViewItem spaceTreeViewItem = new TreeViewItem
- {
- Header = space.Name,
- Tag = space
- };
+ if (clickedItem.HasItems)
+ {
+ return;
+ }
- // Get homepage
- try {
- 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 + ")");
- }
- }
- ShowBusy.Visibility = Visibility.Collapsed;
- _isInitDone = true;
- }));
- }) { Name = "Loading spaces for confluence"}.Start();
- }
- }
+ Log.Debug("Loading pages for page: " + page.Title);
+ new Thread(() =>
+ {
+ Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) (() => { ShowBusy.Visibility = Visibility.Visible; }));
+ var pages = _confluenceConnector.GetPageChildren(page).OrderBy(p => p.Title);
+ Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) (() =>
+ {
+ foreach (var childPage in pages)
+ {
+ Log.Debug("Adding page: " + childPage.Title);
+ var pageTreeViewItem = new TreeViewItem
+ {
+ Header = childPage.Title,
+ Tag = childPage
+ };
+ clickedItem.Items.Add(pageTreeViewItem);
+ pageTreeViewItem.PreviewMouseDoubleClick += PageTreeViewItem_DoubleClick;
+ pageTreeViewItem.PreviewMouseLeftButtonDown += PageTreeViewItem_Click;
+ }
+
+ ShowBusy.Visibility = Visibility.Collapsed;
+ }));
+ })
+ {
+ Name = "Loading childpages for confluence page " + page.Title
+ }.Start();
+ }
+
+ private void PageTreeViewItem_Click(object sender, MouseButtonEventArgs eventArgs)
+ {
+ Log.Debug("pageTreeViewItem_PreviewMouseDoubleClick is called!");
+ if (eventArgs.Source is not TreeViewItem clickedItem)
+ {
+ return;
+ }
+
+ Page page = clickedItem.Tag as Page;
+ _confluenceUpload.SelectedPage = page;
+ if (page != null)
+ {
+ Log.Debug("Page selected: " + page.Title);
+ }
+ }
+
+ private void Page_Loaded(object sender, RoutedEventArgs e)
+ {
+ _confluenceUpload.SelectedPage = null;
+ if (_isInitDone)
+ {
+ return;
+ }
+
+ ShowBusy.Visibility = Visibility.Visible;
+ new Thread(() =>
+ {
+ Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) (() =>
+ {
+ foreach (Space space in _confluenceUpload.Spaces)
+ {
+ TreeViewItem spaceTreeViewItem = new TreeViewItem
+ {
+ Header = space.Name,
+ Tag = space
+ };
+
+ // Get homepage
+ try
+ {
+ 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 + ")");
+ }
+ }
+
+ ShowBusy.Visibility = Visibility.Collapsed;
+ _isInitDone = true;
+ }));
+ })
+ {
+ Name = "Loading spaces for confluence"
+ }.Start();
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs
index 276788579..494036c24 100644
--- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs
+++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs
@@ -25,92 +25,117 @@ using System.Linq;
using System.Threading;
using System.Windows;
-namespace Greenshot.Plugin.Confluence.Forms {
- ///
- /// Interaction logic for ConfluenceUpload.xaml
- ///
- public partial class ConfluenceUpload : Window {
- private System.Windows.Controls.Page _pickerPage;
- public System.Windows.Controls.Page PickerPage {
- get {
- if (_pickerPage == null) {
- List pages = ConfluenceUtils.GetCurrentPages();
- if (pages != null && pages.Count > 0) {
- _pickerPage = new ConfluencePagePicker(this, pages);
- }
- }
- return _pickerPage;
- }
- }
+namespace Greenshot.Plugin.Confluence.Forms
+{
+ ///
+ /// Interaction logic for ConfluenceUpload.xaml
+ ///
+ public partial class ConfluenceUpload : Window
+ {
+ private System.Windows.Controls.Page _pickerPage;
- private System.Windows.Controls.Page _searchPage;
- public System.Windows.Controls.Page SearchPage {
- get { return _searchPage ??= new ConfluenceSearch(this); }
- }
+ public System.Windows.Controls.Page PickerPage
+ {
+ get
+ {
+ if (_pickerPage == null)
+ {
+ List pages = ConfluenceUtils.GetCurrentPages();
+ if (pages != null && pages.Count > 0)
+ {
+ _pickerPage = new ConfluencePagePicker(this, pages);
+ }
+ }
- private System.Windows.Controls.Page _browsePage;
- public System.Windows.Controls.Page BrowsePage {
- get { return _browsePage ??= new ConfluenceTreePicker(this); }
- }
+ return _pickerPage;
+ }
+ }
- private Page _selectedPage;
- public Page SelectedPage {
- get => _selectedPage;
- set {
- _selectedPage = value;
- Upload.IsEnabled = _selectedPage != null;
- IsOpenPageSelected = false;
- }
- }
+ private System.Windows.Controls.Page _searchPage;
- public bool IsOpenPageSelected {
- get;
- set;
- }
- public string Filename {
- get;
- set;
- }
-
- private static DateTime _lastLoad = DateTime.Now;
- private static IList _spaces;
- public IList Spaces {
- get {
- UpdateSpaces();
- while (_spaces == null) {
- Thread.Sleep(300);
- }
- return _spaces;
- }
- }
+ public System.Windows.Controls.Page SearchPage
+ {
+ get { return _searchPage ??= new ConfluenceSearch(this); }
+ }
- public ConfluenceUpload(string filename) {
- Filename = filename;
- InitializeComponent();
- DataContext = this;
- UpdateSpaces();
- if (PickerPage == null) {
- PickerTab.Visibility = Visibility.Collapsed;
- SearchTab.IsSelected = true;
- }
- }
+ private System.Windows.Controls.Page _browsePage;
- private void UpdateSpaces() {
- if (_spaces != null && DateTime.Now.AddMinutes(-60).CompareTo(_lastLoad) > 0) {
- // Reset
- _spaces = null;
- }
- // Check if load is needed
- if (_spaces == null) {
- (new Thread(() => {
- _spaces = ConfluencePlugin.ConfluenceConnector.GetSpaceSummaries().OrderBy(s => s.Name).ToList();
- _lastLoad = DateTime.Now;
- }) { Name = "Loading spaces for confluence"}).Start();
- }
- }
+ public System.Windows.Controls.Page BrowsePage
+ {
+ get { return _browsePage ??= new ConfluenceTreePicker(this); }
+ }
- private void Upload_Click(object sender, RoutedEventArgs e) {
- DialogResult = true;
- }
- }
+ private Page _selectedPage;
+
+ public Page SelectedPage
+ {
+ get => _selectedPage;
+ set
+ {
+ _selectedPage = value;
+ Upload.IsEnabled = _selectedPage != null;
+ IsOpenPageSelected = false;
+ }
+ }
+
+ public bool IsOpenPageSelected { get; set; }
+ public string Filename { get; set; }
+
+ private static DateTime _lastLoad = DateTime.Now;
+ private static IList _spaces;
+
+ public IList Spaces
+ {
+ get
+ {
+ UpdateSpaces();
+ while (_spaces == null)
+ {
+ Thread.Sleep(300);
+ }
+
+ return _spaces;
+ }
+ }
+
+ public ConfluenceUpload(string filename)
+ {
+ Filename = filename;
+ InitializeComponent();
+ DataContext = this;
+ UpdateSpaces();
+ if (PickerPage == null)
+ {
+ PickerTab.Visibility = Visibility.Collapsed;
+ SearchTab.IsSelected = true;
+ }
+ }
+
+ private void UpdateSpaces()
+ {
+ if (_spaces != null && DateTime.Now.AddMinutes(-60).CompareTo(_lastLoad) > 0)
+ {
+ // Reset
+ _spaces = null;
+ }
+
+ // Check if load is needed
+ if (_spaces == null)
+ {
+ (new Thread(() =>
+ {
+ _spaces = ConfluencePlugin.ConfluenceConnector.GetSpaceSummaries().OrderBy(s => s.Name).ToList();
+ _lastLoad = DateTime.Now;
+ })
+ {
+ Name = "Loading spaces for confluence"
+ }).Start();
+ }
+ }
+
+ private void Upload_Click(object sender, RoutedEventArgs e)
+ {
+ DialogResult = true;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/LanguageKeys.cs b/src/Greenshot.Plugin.Confluence/LanguageKeys.cs
index bdbd039a7..bfee1cea8 100644
--- a/src/Greenshot.Plugin.Confluence/LanguageKeys.cs
+++ b/src/Greenshot.Plugin.Confluence/LanguageKeys.cs
@@ -19,10 +19,12 @@
* along with this program. If not, see .
*/
-namespace Greenshot.Plugin.Confluence {
- public enum LangKey {
- login_error,
- upload_menu_item,
- communication_wait
- }
-}
+namespace Greenshot.Plugin.Confluence
+{
+ public enum LangKey
+ {
+ login_error,
+ upload_menu_item,
+ communication_wait
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Support/ITranslationProvider.cs b/src/Greenshot.Plugin.Confluence/Support/ITranslationProvider.cs
index bbabf3a0b..d189db670 100644
--- a/src/Greenshot.Plugin.Confluence/Support/ITranslationProvider.cs
+++ b/src/Greenshot.Plugin.Confluence/Support/ITranslationProvider.cs
@@ -1,5 +1,7 @@
-namespace Greenshot.Plugin.Confluence.Support {
- public interface ITranslationProvider {
+namespace Greenshot.Plugin.Confluence.Support
+{
+ public interface ITranslationProvider
+ {
///
/// Translates the specified key.
///
@@ -7,4 +9,4 @@
///
object Translate(string key);
}
-}
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs b/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs
index 64cc4b0a3..6ca4ec384 100644
--- a/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs
+++ b/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs
@@ -22,13 +22,13 @@ namespace Greenshot.Plugin.Confluence.Support
protected override void StartListening(object source)
{
- var manager = (TranslationManager)source;
+ var manager = (TranslationManager) source;
manager.LanguageChanged += OnLanguageChanged;
}
protected override void StopListening(object source)
{
- var manager = (TranslationManager)source;
+ var manager = (TranslationManager) source;
manager.LanguageChanged -= OnLanguageChanged;
}
@@ -37,15 +37,15 @@ namespace Greenshot.Plugin.Confluence.Support
get
{
Type managerType = typeof(LanguageChangedEventManager);
- var manager = (LanguageChangedEventManager)GetCurrentManager(managerType);
+ var manager = (LanguageChangedEventManager) GetCurrentManager(managerType);
if (manager == null)
{
manager = new LanguageChangedEventManager();
SetCurrentManager(managerType, manager);
}
+
return manager;
}
- }
-
+ }
}
-}
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs b/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs
index 4c98fd1b9..926e7ad8e 100644
--- a/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs
+++ b/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs
@@ -1,18 +1,23 @@
using GreenshotPlugin.Core;
-namespace Greenshot.Plugin.Confluence.Support {
- ///
- ///
- ///
- public class LanguageXMLTranslationProvider : ITranslationProvider {
+namespace Greenshot.Plugin.Confluence.Support
+{
+ ///
+ ///
+ ///
+ public class LanguageXMLTranslationProvider : ITranslationProvider
+ {
///
- /// See
- ///
- public object Translate(string key) {
- if (Language.HasKey("confluence", key)) {
- return Language.GetString("confluence", key);
- }
- return key;
- }
+ /// See
+ ///
+ public object Translate(string key)
+ {
+ if (Language.HasKey("confluence", key))
+ {
+ return Language.GetString("confluence", key);
+ }
+
+ return key;
+ }
}
-}
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs b/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs
index 8d9a6e230..012f0c552 100644
--- a/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs
+++ b/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs
@@ -25,7 +25,7 @@ namespace Greenshot.Plugin.Confluence.Support
public string Key
{
get { return _key; }
- set { _key = value;}
+ set { _key = value; }
}
///
@@ -34,10 +34,10 @@ namespace Greenshot.Plugin.Confluence.Support
public override object ProvideValue(IServiceProvider serviceProvider)
{
var binding = new Binding("Value")
- {
- Source = new TranslationData(_key)
- };
+ {
+ Source = new TranslationData(_key)
+ };
return binding.ProvideValue(serviceProvider);
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs b/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs
index 0f920efc4..0ebce8300 100644
--- a/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs
+++ b/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs
@@ -2,44 +2,49 @@
using System.ComponentModel;
using System.Windows;
-namespace Greenshot.Plugin.Confluence.Support {
- public class TranslationData : IWeakEventListener, INotifyPropertyChanged {
+namespace Greenshot.Plugin.Confluence.Support
+{
+ public class TranslationData : IWeakEventListener, INotifyPropertyChanged
+ {
private readonly string _key;
///
- /// Initializes a new instance of the class.
- ///
- /// The key.
- public TranslationData( string key) {
- _key = key;
- LanguageChangedEventManager.AddListener(TranslationManager.Instance, this);
- }
+ /// Initializes a new instance of the class.
+ ///
+ /// The key.
+ public TranslationData(string key)
+ {
+ _key = key;
+ LanguageChangedEventManager.AddListener(TranslationManager.Instance, this);
+ }
- ///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
- ///
- ~TranslationData() {
- LanguageChangedEventManager.RemoveListener(TranslationManager.Instance, this);
- }
+ ///
+ /// Releases unmanaged resources and performs other cleanup operations before the
+ /// is reclaimed by garbage collection.
+ ///
+ ~TranslationData()
+ {
+ LanguageChangedEventManager.RemoveListener(TranslationManager.Instance, this);
+ }
- public object Value => TranslationManager.Instance.Translate(_key);
+ public object Value => TranslationManager.Instance.Translate(_key);
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
- {
- if (managerType == typeof(LanguageChangedEventManager))
- {
- OnLanguageChanged(sender, e);
- return true;
- }
- return false;
- }
+ {
+ if (managerType == typeof(LanguageChangedEventManager))
+ {
+ OnLanguageChanged(sender, e);
+ return true;
+ }
- private void OnLanguageChanged(object sender, EventArgs e)
- {
- PropertyChanged?.Invoke( this, new PropertyChangedEventArgs("Value"));
- }
+ return false;
+ }
+
+ private void OnLanguageChanged(object sender, EventArgs e)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
+ }
public event PropertyChangedEventHandler PropertyChanged;
}
-}
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Confluence/Support/TranslationManager.cs b/src/Greenshot.Plugin.Confluence/Support/TranslationManager.cs
index c9af13a4f..825d1aae7 100644
--- a/src/Greenshot.Plugin.Confluence/Support/TranslationManager.cs
+++ b/src/Greenshot.Plugin.Confluence/Support/TranslationManager.cs
@@ -1,40 +1,45 @@
using System;
-namespace Greenshot.Plugin.Confluence.Support {
- public class TranslationManager {
- private static TranslationManager _translationManager;
+namespace Greenshot.Plugin.Confluence.Support
+{
+ public class TranslationManager
+ {
+ private static TranslationManager _translationManager;
- public event EventHandler LanguageChanged;
+ public event EventHandler LanguageChanged;
- /*public CultureInfo CurrentLanguage {
- get { return Thread.CurrentThread.CurrentUICulture; }
- set {
- if( value != Thread.CurrentThread.CurrentUICulture) {
- Thread.CurrentThread.CurrentUICulture = value;
- OnLanguageChanged();
- }
- }
- }
+ /*public CultureInfo CurrentLanguage {
+ get { return Thread.CurrentThread.CurrentUICulture; }
+ set {
+ if( value != Thread.CurrentThread.CurrentUICulture) {
+ Thread.CurrentThread.CurrentUICulture = value;
+ OnLanguageChanged();
+ }
+ }
+ }
- public IEnumerable Languages {
- get {
- if( TranslationProvider != null) {
- return TranslationProvider.Languages;
- }
- return Enumerable.Empty();
- }
- }*/
+ public IEnumerable Languages {
+ get {
+ if( TranslationProvider != null) {
+ return TranslationProvider.Languages;
+ }
+ return Enumerable.Empty();
+ }
+ }*/
- public static TranslationManager Instance => _translationManager ??= new TranslationManager();
+ public static TranslationManager Instance => _translationManager ??= new TranslationManager();
- public ITranslationProvider TranslationProvider { get; set; }
+ public ITranslationProvider TranslationProvider { get; set; }
- public object Translate(string key) {
- object translatedValue = TranslationProvider?.Translate(key);
- if( translatedValue != null) {
- return translatedValue;
- }
- return $"!{key}!";
- }
- }
-}
+ public object Translate(string key)
+ {
+ object translatedValue = TranslationProvider?.Translate(key);
+ if (translatedValue != null)
+ {
+ return translatedValue;
+ }
+
+ return $"!{key}!";
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs b/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs
index 7de974307..61f7a8705 100644
--- a/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs
+++ b/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs
@@ -25,38 +25,48 @@ using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
-namespace Greenshot.Plugin.Dropbox {
- internal class DropboxDestination : AbstractDestination {
- private static readonly DropboxPluginConfiguration DropboxConfig = IniConfig.GetIniSection();
+namespace Greenshot.Plugin.Dropbox
+{
+ internal class DropboxDestination : AbstractDestination
+ {
+ private static readonly DropboxPluginConfiguration DropboxConfig = IniConfig.GetIniSection();
- private readonly DropboxPlugin _plugin;
- public DropboxDestination(DropboxPlugin plugin) {
- _plugin = plugin;
- }
+ private readonly DropboxPlugin _plugin;
- public override string Designation => "Dropbox";
+ public DropboxDestination(DropboxPlugin plugin)
+ {
+ _plugin = plugin;
+ }
- public override string Description => Language.GetString("dropbox", LangKey.upload_menu_item);
+ public override string Designation => "Dropbox";
- public override Image DisplayIcon {
- get {
- ComponentResourceManager resources = new ComponentResourceManager(typeof(DropboxPlugin));
- return (Image)resources.GetObject("Dropbox");
- }
- }
+ public override string Description => Language.GetString("dropbox", LangKey.upload_menu_item);
- public override ExportInformation ExportCapture(bool manually, ISurface surface, ICaptureDetails captureDetails) {
- ExportInformation exportInformation = new ExportInformation(Designation, Description);
- bool uploaded = _plugin.Upload(captureDetails, surface, out var uploadUrl);
- if (uploaded) {
- exportInformation.Uri = uploadUrl;
- exportInformation.ExportMade = true;
- if (DropboxConfig.AfterUploadLinkToClipBoard) {
- ClipboardHelper.SetClipboardData(uploadUrl);
- }
- }
- ProcessExport(exportInformation, surface);
- return exportInformation;
- }
- }
-}
+ public override Image DisplayIcon
+ {
+ get
+ {
+ ComponentResourceManager resources = new ComponentResourceManager(typeof(DropboxPlugin));
+ return (Image) resources.GetObject("Dropbox");
+ }
+ }
+
+ public override ExportInformation ExportCapture(bool manually, ISurface surface, ICaptureDetails captureDetails)
+ {
+ ExportInformation exportInformation = new ExportInformation(Designation, Description);
+ bool uploaded = _plugin.Upload(captureDetails, surface, out var uploadUrl);
+ if (uploaded)
+ {
+ exportInformation.Uri = uploadUrl;
+ exportInformation.ExportMade = true;
+ if (DropboxConfig.AfterUploadLinkToClipBoard)
+ {
+ ClipboardHelper.SetClipboardData(uploadUrl);
+ }
+ }
+
+ ProcessExport(exportInformation, surface);
+ return exportInformation;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs b/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs
index abd83112f..1ec893423 100644
--- a/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs
+++ b/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs
@@ -29,93 +29,101 @@ using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
-namespace Greenshot.Plugin.Dropbox {
- ///
- /// This is the Dropbox base code
- ///
+namespace Greenshot.Plugin.Dropbox
+{
+ ///
+ /// This is the Dropbox base code
+ ///
[Plugin("Dropbox", true)]
- public class DropboxPlugin : IGreenshotPlugin {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(DropboxPlugin));
- private static DropboxPluginConfiguration _config;
- private ComponentResourceManager _resources;
- private ToolStripMenuItem _itemPlugInConfig;
+ public class DropboxPlugin : IGreenshotPlugin
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(DropboxPlugin));
+ private static DropboxPluginConfiguration _config;
+ private ComponentResourceManager _resources;
+ private ToolStripMenuItem _itemPlugInConfig;
- public void Dispose() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- private void Dispose(bool disposing)
- {
- if (!disposing) return;
- if (_itemPlugInConfig == null) return;
- _itemPlugInConfig.Dispose();
- _itemPlugInConfig = null;
- }
+ private void Dispose(bool disposing)
+ {
+ if (!disposing) return;
+ if (_itemPlugInConfig == null) return;
+ _itemPlugInConfig.Dispose();
+ _itemPlugInConfig = null;
+ }
- ///
- /// Implementation of the IGreenshotPlugin.Initialize
- ///
- public bool Initialize() {
-
- // Register configuration (don't need the configuration itself)
- _config = IniConfig.GetIniSection();
- _resources = new ComponentResourceManager(typeof(DropboxPlugin));
+ ///
+ /// Implementation of the IGreenshotPlugin.Initialize
+ ///
+ public bool Initialize()
+ {
+ // Register configuration (don't need the configuration itself)
+ _config = IniConfig.GetIniSection();
+ _resources = new ComponentResourceManager(typeof(DropboxPlugin));
SimpleServiceProvider.Current.AddService(new DropboxDestination(this));
- _itemPlugInConfig = new ToolStripMenuItem
- {
- Text = Language.GetString("dropbox", LangKey.Configure),
- Image = (Image)_resources.GetObject("Dropbox")
- };
- _itemPlugInConfig.Click += ConfigMenuClick;
+ _itemPlugInConfig = new ToolStripMenuItem
+ {
+ Text = Language.GetString("dropbox", LangKey.Configure),
+ Image = (Image) _resources.GetObject("Dropbox")
+ };
+ _itemPlugInConfig.Click += ConfigMenuClick;
- PluginUtils.AddToContextMenu(_itemPlugInConfig);
- Language.LanguageChanged += OnLanguageChanged;
- return true;
- }
+ PluginUtils.AddToContextMenu(_itemPlugInConfig);
+ Language.LanguageChanged += OnLanguageChanged;
+ return true;
+ }
- public void OnLanguageChanged(object sender, EventArgs e) {
- if (_itemPlugInConfig != null) {
- _itemPlugInConfig.Text = Language.GetString("dropbox", LangKey.Configure);
- }
- }
+ public void OnLanguageChanged(object sender, EventArgs e)
+ {
+ if (_itemPlugInConfig != null)
+ {
+ _itemPlugInConfig.Text = Language.GetString("dropbox", LangKey.Configure);
+ }
+ }
- public void Shutdown() {
- Log.Debug("Dropbox Plugin shutdown.");
- }
+ public void Shutdown()
+ {
+ Log.Debug("Dropbox Plugin shutdown.");
+ }
- ///
- /// Implementation of the IPlugin.Configure
- ///
- public void Configure() {
- _config.ShowConfigDialog();
- }
+ ///
+ /// Implementation of the IPlugin.Configure
+ ///
+ public void Configure()
+ {
+ _config.ShowConfigDialog();
+ }
- public void ConfigMenuClick(object sender, EventArgs eventArgs) {
- _config.ShowConfigDialog();
- }
+ public void ConfigMenuClick(object sender, EventArgs eventArgs)
+ {
+ _config.ShowConfigDialog();
+ }
- ///
- /// This will be called when the menu item in the Editor is clicked
- ///
- public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) {
- uploadUrl = null;
- SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false);
- try
+ ///
+ /// This will be called when the menu item in the Editor is clicked
+ ///
+ public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl)
+ {
+ uploadUrl = null;
+ SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false);
+ try
{
bool result = false;
- new PleaseWaitForm().ShowAndWait("Dropbox", Language.GetString("dropbox", LangKey.communication_wait),
- delegate
- {
- result = DropboxUtils.UploadToDropbox(surfaceToUpload, outputSettings, captureDetails);
- }
- );
+ new PleaseWaitForm().ShowAndWait("Dropbox", Language.GetString("dropbox", LangKey.communication_wait),
+ delegate { result = DropboxUtils.UploadToDropbox(surfaceToUpload, outputSettings, captureDetails); }
+ );
return result;
- } catch (Exception e) {
- Log.Error(e);
- MessageBox.Show(Language.GetString("dropbox", LangKey.upload_failure) + " " + e.Message);
- return false;
- }
- }
- }
-}
+ }
+ catch (Exception e)
+ {
+ Log.Error(e);
+ MessageBox.Show(Language.GetString("dropbox", LangKey.upload_failure) + " " + e.Message);
+ return false;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Dropbox/DropboxPluginConfiguration.cs b/src/Greenshot.Plugin.Dropbox/DropboxPluginConfiguration.cs
index 1b738cdeb..4a2bd95d0 100644
--- a/src/Greenshot.Plugin.Dropbox/DropboxPluginConfiguration.cs
+++ b/src/Greenshot.Plugin.Dropbox/DropboxPluginConfiguration.cs
@@ -25,25 +25,27 @@ using Greenshot.Plugin.Dropbox.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.Dropbox {
- ///
- /// Description of ImgurConfiguration.
- ///
- [IniSection("Dropbox", Description = "Greenshot Dropbox Plugin configuration")]
- public class DropboxPluginConfiguration : IniSection {
- [IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
- public OutputFormat UploadFormat { get; set; }
+namespace Greenshot.Plugin.Dropbox
+{
+ ///
+ /// Description of ImgurConfiguration.
+ ///
+ [IniSection("Dropbox", Description = "Greenshot Dropbox Plugin configuration")]
+ public class DropboxPluginConfiguration : IniSection
+ {
+ [IniProperty("UploadFormat", Description = "What file type to use for uploading", DefaultValue = "png")]
+ public OutputFormat UploadFormat { get; set; }
- [IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]
- public int UploadJpegQuality { get; set; }
+ [IniProperty("UploadJpegQuality", Description = "JPEG file save quality in %.", DefaultValue = "80")]
+ public int UploadJpegQuality { get; set; }
- [IniProperty("AfterUploadLinkToClipBoard", Description = "After upload send Dropbox link to clipboard.", DefaultValue = "true")]
- public bool AfterUploadLinkToClipBoard { get; set; }
+ [IniProperty("AfterUploadLinkToClipBoard", Description = "After upload send Dropbox link to clipboard.", DefaultValue = "true")]
+ public bool AfterUploadLinkToClipBoard { get; set; }
[IniProperty("RefreshToken", Description = "Dropbox refresh Token", Encrypted = true, ExcludeIfNull = true)]
public string RefreshToken { get; set; }
- ///
+ ///
/// AccessToken, not stored
///
public string AccessToken { get; set; }
@@ -53,16 +55,19 @@ namespace Greenshot.Plugin.Dropbox {
///
public DateTimeOffset AccessTokenExpires { get; set; }
- ///
- /// A form for token
- ///
- /// bool true if OK was pressed, false if cancel
- public bool ShowConfigDialog() {
- DialogResult result = new SettingsForm().ShowDialog();
- if (result == DialogResult.OK) {
- return true;
- }
- return false;
- }
- }
-}
+ ///
+ /// A form for token
+ ///
+ /// bool true if OK was pressed, false if cancel
+ public bool ShowConfigDialog()
+ {
+ DialogResult result = new SettingsForm().ShowDialog();
+ if (result == DialogResult.OK)
+ {
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Dropbox/DropboxUtils.cs b/src/Greenshot.Plugin.Dropbox/DropboxUtils.cs
index dd130c9bc..ebb7b2685 100644
--- a/src/Greenshot.Plugin.Dropbox/DropboxUtils.cs
+++ b/src/Greenshot.Plugin.Dropbox/DropboxUtils.cs
@@ -29,19 +29,22 @@ using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
using Newtonsoft.Json;
-namespace Greenshot.Plugin.Dropbox {
- ///
- /// Description of DropboxUtils.
- ///
- public class DropboxUtils {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(DropboxUtils));
- private static readonly DropboxPluginConfiguration DropboxConfig = IniConfig.GetIniSection();
+namespace Greenshot.Plugin.Dropbox
+{
+ ///
+ /// Description of DropboxUtils.
+ ///
+ public class DropboxUtils
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(DropboxUtils));
+ private static readonly DropboxPluginConfiguration DropboxConfig = IniConfig.GetIniSection();
- private DropboxUtils() {
- }
+ private DropboxUtils()
+ {
+ }
- public static bool UploadToDropbox(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, ICaptureDetails captureDetails)
- {
+ public static bool UploadToDropbox(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, ICaptureDetails captureDetails)
+ {
var oauth2Settings = new OAuth2Settings
{
AuthUrlPattern = "https://api.dropbox.com/oauth2/authorize?response_type=token&client_id={ClientId}&state={State}&redirect_uri={RedirectUrl}",
@@ -51,24 +54,32 @@ namespace Greenshot.Plugin.Dropbox {
ClientId = DropBoxCredentials.CONSUMER_KEY,
ClientSecret = DropBoxCredentials.CONSUMER_SECRET,
AuthorizeMode = OAuth2AuthorizeMode.JsonReceiver,
- RefreshToken = DropboxConfig.RefreshToken,
+ RefreshToken = DropboxConfig.RefreshToken,
AccessToken = DropboxConfig.AccessToken,
AccessTokenExpires = DropboxConfig.AccessTokenExpires
- };
+ };
try
- {
+ {
string filename = Path.GetFileName(FilenameHelper.GetFilename(DropboxConfig.UploadFormat, captureDetails));
SurfaceContainer image = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
IDictionary arguments = new Dictionary
{
- { "autorename", true },
- { "mute", true },
- { "path", "/" + filename.Replace(Path.DirectorySeparatorChar, '\\')}
+ {
+ "autorename", true
+ },
+ {
+ "mute", true
+ },
+ {
+ "path", "/" + filename.Replace(Path.DirectorySeparatorChar, '\\')
+ }
};
IDictionary headers = new Dictionary
{
- { "Dropbox-API-Arg", JsonConvert.SerializeObject(arguments)}
+ {
+ "Dropbox-API-Arg", JsonConvert.SerializeObject(arguments)
+ }
};
var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, "https://content.dropboxapi.com/2/files/upload", oauth2Settings);
@@ -78,16 +89,19 @@ namespace Greenshot.Plugin.Dropbox {
var response = JsonConvert.DeserializeObject>(responseString);
return response.ContainsKey("id");
}
- catch (Exception ex) {
- Log.Error("Upload error: ", ex);
- throw;
- } finally {
+ catch (Exception ex)
+ {
+ Log.Error("Upload error: ", ex);
+ throw;
+ }
+ finally
+ {
DropboxConfig.RefreshToken = oauth2Settings.RefreshToken;
DropboxConfig.AccessToken = oauth2Settings.AccessToken;
DropboxConfig.AccessTokenExpires = oauth2Settings.AccessTokenExpires;
DropboxConfig.IsDirty = true;
IniConfig.Save();
}
- }
- }
-}
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Dropbox/Forms/DropboxForm.cs b/src/Greenshot.Plugin.Dropbox/Forms/DropboxForm.cs
index c7aaecb1d..b39d1e14d 100644
--- a/src/Greenshot.Plugin.Dropbox/Forms/DropboxForm.cs
+++ b/src/Greenshot.Plugin.Dropbox/Forms/DropboxForm.cs
@@ -21,7 +21,9 @@
using GreenshotPlugin.Controls;
-namespace Greenshot.Plugin.Dropbox.Forms {
- public class DropboxForm : GreenshotForm {
- }
-}
+namespace Greenshot.Plugin.Dropbox.Forms
+{
+ public class DropboxForm : GreenshotForm
+ {
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Dropbox/Forms/SettingsForm.cs b/src/Greenshot.Plugin.Dropbox/Forms/SettingsForm.cs
index 9586c9ca7..c79844e6d 100644
--- a/src/Greenshot.Plugin.Dropbox/Forms/SettingsForm.cs
+++ b/src/Greenshot.Plugin.Dropbox/Forms/SettingsForm.cs
@@ -19,19 +19,21 @@
* along with this program. If not, see .
*/
-namespace Greenshot.Plugin.Dropbox.Forms {
- ///
- /// Description of PasswordRequestForm.
- ///
- public partial class SettingsForm : DropboxForm {
- public SettingsForm() {
- //
- // The InitializeComponent() call is required for Windows Forms designer support.
- //
- InitializeComponent();
- AcceptButton = buttonOK;
- CancelButton = buttonCancel;
- }
-
- }
-}
+namespace Greenshot.Plugin.Dropbox.Forms
+{
+ ///
+ /// Description of PasswordRequestForm.
+ ///
+ public partial class SettingsForm : DropboxForm
+ {
+ public SettingsForm()
+ {
+ //
+ // The InitializeComponent() call is required for Windows Forms designer support.
+ //
+ InitializeComponent();
+ AcceptButton = buttonOK;
+ CancelButton = buttonCancel;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Dropbox/LanguageKeys.cs b/src/Greenshot.Plugin.Dropbox/LanguageKeys.cs
index 9b42f6c75..37d6b50e3 100644
--- a/src/Greenshot.Plugin.Dropbox/LanguageKeys.cs
+++ b/src/Greenshot.Plugin.Dropbox/LanguageKeys.cs
@@ -18,11 +18,14 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
-namespace Greenshot.Plugin.Dropbox {
- public enum LangKey {
- upload_menu_item,
- upload_failure,
- communication_wait,
- Configure
+
+namespace Greenshot.Plugin.Dropbox
+{
+ public enum LangKey
+ {
+ upload_menu_item,
+ upload_failure,
+ communication_wait,
+ Configure
}
-}
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Dropbox/Properties/AssemblyInfo.cs b/src/Greenshot.Plugin.Dropbox/Properties/AssemblyInfo.cs
index 9e9b18e04..5870d89ea 100644
--- a/src/Greenshot.Plugin.Dropbox/Properties/AssemblyInfo.cs
+++ b/src/Greenshot.Plugin.Dropbox/Properties/AssemblyInfo.cs
@@ -29,4 +29,4 @@ using System.Runtime.InteropServices;
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
-[assembly: ComVisible(false)]
+[assembly: ComVisible(false)]
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs
index e4f345f47..8d677e200 100644
--- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs
+++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs
@@ -25,122 +25,140 @@ using System.IO;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.ExternalCommand {
- ///
- /// Description of FlickrConfiguration.
- ///
- [IniSection("ExternalCommand", Description="Greenshot ExternalCommand Plugin configuration")]
- public class ExternalCommandConfiguration : IniSection {
- [IniProperty("Commands", Description="The commands that are available.")]
- public List Commands { get; set; }
+namespace Greenshot.Plugin.ExternalCommand
+{
+ ///
+ /// Description of FlickrConfiguration.
+ ///
+ [IniSection("ExternalCommand", Description = "Greenshot ExternalCommand Plugin configuration")]
+ public class ExternalCommandConfiguration : IniSection
+ {
+ [IniProperty("Commands", Description = "The commands that are available.")]
+ public List Commands { get; set; }
- [IniProperty("RedirectStandardError", Description = "Redirect the standard error of all external commands, used to output as warning to the greenshot.log.", DefaultValue = "true")]
- public bool RedirectStandardError { get; set; }
+ [IniProperty("RedirectStandardError", Description = "Redirect the standard error of all external commands, used to output as warning to the greenshot.log.",
+ DefaultValue = "true")]
+ public bool RedirectStandardError { get; set; }
- [IniProperty("RedirectStandardOutput", Description = "Redirect the standard output of all external commands, used for different other functions (more below).", DefaultValue = "true")]
- public bool RedirectStandardOutput { get; set; }
+ [IniProperty("RedirectStandardOutput", Description = "Redirect the standard output of all external commands, used for different other functions (more below).",
+ DefaultValue = "true")]
+ public bool RedirectStandardOutput { get; set; }
- [IniProperty("ShowStandardOutputInLog", Description = "Depends on 'RedirectStandardOutput': Show standard output of all external commands to the Greenshot log, this can be usefull for debugging.", DefaultValue = "false")]
- public bool ShowStandardOutputInLog { get; set; }
+ [IniProperty("ShowStandardOutputInLog",
+ Description = "Depends on 'RedirectStandardOutput': Show standard output of all external commands to the Greenshot log, this can be usefull for debugging.",
+ DefaultValue = "false")]
+ public bool ShowStandardOutputInLog { get; set; }
- [IniProperty("ParseForUri", Description = "Depends on 'RedirectStandardOutput': Parse the output and take the first found URI, if a URI is found than clicking on the notify bubble goes there.", DefaultValue = "true")]
- public bool ParseOutputForUri { get; set; }
+ [IniProperty("ParseForUri",
+ Description = "Depends on 'RedirectStandardOutput': Parse the output and take the first found URI, if a URI is found than clicking on the notify bubble goes there.",
+ DefaultValue = "true")]
+ public bool ParseOutputForUri { get; set; }
- [IniProperty("OutputToClipboard", Description = "Depends on 'RedirectStandardOutput': Place the standard output on the clipboard.", DefaultValue = "false")]
- public bool OutputToClipboard { get; set; }
+ [IniProperty("OutputToClipboard", Description = "Depends on 'RedirectStandardOutput': Place the standard output on the clipboard.", DefaultValue = "false")]
+ public bool OutputToClipboard { get; set; }
- [IniProperty("UriToClipboard", Description = "Depends on 'RedirectStandardOutput' & 'ParseForUri': If an URI is found in the standard input, place it on the clipboard. (This overwrites the output from OutputToClipboard setting.)", DefaultValue = "true")]
- public bool UriToClipboard { get; set; }
+ [IniProperty("UriToClipboard",
+ Description =
+ "Depends on 'RedirectStandardOutput' & 'ParseForUri': If an URI is found in the standard input, place it on the clipboard. (This overwrites the output from OutputToClipboard setting.)",
+ DefaultValue = "true")]
+ public bool UriToClipboard { get; set; }
- [IniProperty("Commandline", Description="The commandline for the output command.")]
- public Dictionary Commandline { get; set; }
+ [IniProperty("Commandline", Description = "The commandline for the output command.")]
+ public Dictionary Commandline { get; set; }
- [IniProperty("Argument", Description="The arguments for the output command.")]
- public Dictionary Argument { get; set; }
+ [IniProperty("Argument", Description = "The arguments for the output command.")]
+ public Dictionary Argument { get; set; }
- [IniProperty("RunInbackground", Description = "Should the command be started in the background.")]
- public Dictionary RunInbackground { get; set; }
+ [IniProperty("RunInbackground", Description = "Should the command be started in the background.")]
+ public Dictionary RunInbackground { get; set; }
- [IniProperty("DeletedBuildInCommands", Description = "If a build in command was deleted manually, it should not be recreated.")]
- public List DeletedBuildInCommands { get; set; }
+ [IniProperty("DeletedBuildInCommands", Description = "If a build in command was deleted manually, it should not be recreated.")]
+ public List DeletedBuildInCommands { get; set; }
- private const string MsPaint = "MS Paint";
- private static readonly string PaintPath;
- private static readonly bool HasPaint;
+ private const string MsPaint = "MS Paint";
+ private static readonly string PaintPath;
+ private static readonly bool HasPaint;
- private const string PaintDotNet = "Paint.NET";
- private static readonly string PaintDotNetPath;
- private static readonly bool HasPaintDotNet;
- static ExternalCommandConfiguration() {
- try {
- PaintPath = PluginUtils.GetExePath("pbrush.exe");
- HasPaint = !string.IsNullOrEmpty(PaintPath) && File.Exists(PaintPath);
- } catch {
- // Ignore
- }
- try
- {
- PaintDotNetPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Paint.NET\PaintDotNet.exe");
- HasPaintDotNet = !string.IsNullOrEmpty(PaintDotNetPath) && File.Exists(PaintDotNetPath);
- }
- catch
- {
- // Ignore
- }
- }
+ private const string PaintDotNet = "Paint.NET";
+ private static readonly string PaintDotNetPath;
+ private static readonly bool HasPaintDotNet;
- ///
- /// Delete the configuration for the specified command
- ///
- /// string with command
- public void Delete(string command)
- {
- if (string.IsNullOrEmpty(command))
- {
- return;
- }
- Commands.Remove(command);
- Commandline.Remove(command);
- Argument.Remove(command);
- RunInbackground.Remove(command);
- if (MsPaint.Equals(command) || PaintDotNet.Equals(command))
- {
- if (!DeletedBuildInCommands.Contains(command))
- {
- DeletedBuildInCommands.Add(command);
- }
- }
- }
+ static ExternalCommandConfiguration()
+ {
+ try
+ {
+ PaintPath = PluginUtils.GetExePath("pbrush.exe");
+ HasPaint = !string.IsNullOrEmpty(PaintPath) && File.Exists(PaintPath);
+ }
+ catch
+ {
+ // Ignore
+ }
- public override void AfterLoad()
- {
- base.AfterLoad();
+ try
+ {
+ PaintDotNetPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Paint.NET\PaintDotNet.exe");
+ HasPaintDotNet = !string.IsNullOrEmpty(PaintDotNetPath) && File.Exists(PaintDotNetPath);
+ }
+ catch
+ {
+ // Ignore
+ }
+ }
- // Check if we need to add MsPaint
- if (HasPaint && !Commands.Contains(MsPaint) && !DeletedBuildInCommands.Contains(MsPaint))
- {
- Commands.Add(MsPaint);
- Commandline.Add(MsPaint, PaintPath);
- Argument.Add(MsPaint, "\"{0}\"");
- RunInbackground.Add(MsPaint, true);
- }
+ ///
+ /// Delete the configuration for the specified command
+ ///
+ /// string with command
+ public void Delete(string command)
+ {
+ if (string.IsNullOrEmpty(command))
+ {
+ return;
+ }
- // Check if we need to add Paint.NET
- if (HasPaintDotNet && !Commands.Contains(PaintDotNet) && !DeletedBuildInCommands.Contains(PaintDotNet))
- {
- Commands.Add(PaintDotNet);
- Commandline.Add(PaintDotNet, PaintDotNetPath);
- Argument.Add(PaintDotNet, "\"{0}\"");
- RunInbackground.Add(PaintDotNet, true);
- }
- }
+ Commands.Remove(command);
+ Commandline.Remove(command);
+ Argument.Remove(command);
+ RunInbackground.Remove(command);
+ if (MsPaint.Equals(command) || PaintDotNet.Equals(command))
+ {
+ if (!DeletedBuildInCommands.Contains(command))
+ {
+ DeletedBuildInCommands.Add(command);
+ }
+ }
+ }
- ///
- /// Supply values we can't put as defaults
- ///
- /// The property to return a default for
- /// object with the default value for the supplied property
- public override object GetDefault(string property) =>
+ public override void AfterLoad()
+ {
+ base.AfterLoad();
+
+ // Check if we need to add MsPaint
+ if (HasPaint && !Commands.Contains(MsPaint) && !DeletedBuildInCommands.Contains(MsPaint))
+ {
+ Commands.Add(MsPaint);
+ Commandline.Add(MsPaint, PaintPath);
+ Argument.Add(MsPaint, "\"{0}\"");
+ RunInbackground.Add(MsPaint, true);
+ }
+
+ // Check if we need to add Paint.NET
+ if (HasPaintDotNet && !Commands.Contains(PaintDotNet) && !DeletedBuildInCommands.Contains(PaintDotNet))
+ {
+ Commands.Add(PaintDotNet);
+ Commandline.Add(PaintDotNet, PaintDotNetPath);
+ Argument.Add(PaintDotNet, "\"{0}\"");
+ RunInbackground.Add(PaintDotNet, true);
+ }
+ }
+
+ ///
+ /// Supply values we can't put as defaults
+ ///
+ /// The property to return a default for
+ /// object with the default value for the supplied property
+ public override object GetDefault(string property) =>
property switch
{
nameof(DeletedBuildInCommands) => (object) new List(),
@@ -151,4 +169,4 @@ namespace Greenshot.Plugin.ExternalCommand {
_ => null
};
}
-}
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs
index df9b25352..c7ab3b957 100644
--- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs
+++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs
@@ -31,146 +31,184 @@ using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
-namespace Greenshot.Plugin.ExternalCommand {
- ///
- /// Description of OCRDestination.
- ///
- public class ExternalCommandDestination : AbstractDestination {
- private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExternalCommandDestination));
- private static readonly Regex URI_REGEXP = new Regex(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)");
- private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection();
- private readonly string _presetCommand;
-
- public ExternalCommandDestination(string commando) {
- _presetCommand = commando;
- }
+namespace Greenshot.Plugin.ExternalCommand
+{
+ ///
+ /// Description of OCRDestination.
+ ///
+ public class ExternalCommandDestination : AbstractDestination
+ {
+ private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExternalCommandDestination));
- public override string Designation => "External " + _presetCommand.Replace(',','_');
+ private static readonly Regex URI_REGEXP =
+ new Regex(
+ @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)");
- public override string Description => _presetCommand;
+ private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection();
+ private readonly string _presetCommand;
- public override IEnumerable DynamicDestinations() {
- yield break;
- }
+ public ExternalCommandDestination(string commando)
+ {
+ _presetCommand = commando;
+ }
- public override Image DisplayIcon => IconCache.IconForCommand(_presetCommand);
+ public override string Designation => "External " + _presetCommand.Replace(',', '_');
- public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
- ExportInformation exportInformation = new ExportInformation(Designation, Description);
- SurfaceOutputSettings outputSettings = new SurfaceOutputSettings();
- outputSettings.PreventGreenshotFormat();
+ public override string Description => _presetCommand;
- if (_presetCommand != null) {
- if (!config.RunInbackground.ContainsKey(_presetCommand)) {
- config.RunInbackground.Add(_presetCommand, true);
- }
- bool runInBackground = config.RunInbackground[_presetCommand];
- string fullPath = captureDetails.Filename ?? ImageOutput.SaveNamedTmpFile(surface, captureDetails, outputSettings);
+ public override IEnumerable DynamicDestinations()
+ {
+ yield break;
+ }
+
+ public override Image DisplayIcon => IconCache.IconForCommand(_presetCommand);
+
+ public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
+ {
+ ExportInformation exportInformation = new ExportInformation(Designation, Description);
+ SurfaceOutputSettings outputSettings = new SurfaceOutputSettings();
+ outputSettings.PreventGreenshotFormat();
+
+ if (_presetCommand != null)
+ {
+ if (!config.RunInbackground.ContainsKey(_presetCommand))
+ {
+ config.RunInbackground.Add(_presetCommand, true);
+ }
+
+ bool runInBackground = config.RunInbackground[_presetCommand];
+ string fullPath = captureDetails.Filename ?? ImageOutput.SaveNamedTmpFile(surface, captureDetails, outputSettings);
string output;
- string error;
- if (runInBackground) {
- Thread commandThread = new Thread(delegate()
- {
- CallExternalCommand(exportInformation, fullPath, out output, out error);
- ProcessExport(exportInformation, surface);
- })
- {
- Name = "Running " + _presetCommand,
- IsBackground = true
- };
- commandThread.SetApartmentState(ApartmentState.STA);
- commandThread.Start();
- exportInformation.ExportMade = true;
- } else {
- CallExternalCommand(exportInformation, fullPath, out output, out error);
- ProcessExport(exportInformation, surface);
- }
- }
- return exportInformation;
- }
+ string error;
+ if (runInBackground)
+ {
+ Thread commandThread = new Thread(delegate()
+ {
+ CallExternalCommand(exportInformation, fullPath, out output, out error);
+ ProcessExport(exportInformation, surface);
+ })
+ {
+ Name = "Running " + _presetCommand,
+ IsBackground = true
+ };
+ commandThread.SetApartmentState(ApartmentState.STA);
+ commandThread.Start();
+ exportInformation.ExportMade = true;
+ }
+ else
+ {
+ CallExternalCommand(exportInformation, fullPath, out output, out error);
+ ProcessExport(exportInformation, surface);
+ }
+ }
- ///
- /// Wrapper method for the background and normal call, this does all the logic:
- /// Call the external command, parse for URI, place to clipboard and set the export information
- ///
- ///
- ///
- ///
- ///
- private void CallExternalCommand(ExportInformation exportInformation, string fullPath, out string output, out string error) {
- output = null;
- error = null;
- try {
- if (CallExternalCommand(_presetCommand, fullPath, out output, out error) == 0) {
- exportInformation.ExportMade = true;
- if (!string.IsNullOrEmpty(output)) {
- MatchCollection uriMatches = URI_REGEXP.Matches(output);
- // Place output on the clipboard before the URI, so if one is found this overwrites
- if (config.OutputToClipboard) {
- ClipboardHelper.SetClipboardData(output);
- }
- if (uriMatches.Count > 0) {
- exportInformation.Uri = uriMatches[0].Groups[1].Value;
- LOG.InfoFormat("Got URI : {0} ", exportInformation.Uri);
- if (config.UriToClipboard) {
- ClipboardHelper.SetClipboardData(exportInformation.Uri);
- }
- }
- }
- } else {
- LOG.WarnFormat("Error calling external command: {0} ", output);
- exportInformation.ExportMade = false;
- exportInformation.ErrorMessage = error;
- }
- } catch (Exception ex) {
- exportInformation.ExportMade = false;
- exportInformation.ErrorMessage = ex.Message;
- LOG.WarnFormat("Error calling external command: {0} ", exportInformation.ErrorMessage);
- }
- }
+ return exportInformation;
+ }
- ///
- /// Wrapper to retry with a runas
- ///
- ///
- ///
- ///
- ///
- ///
- private int CallExternalCommand(string commando, string fullPath, out string output, out string error) {
- try {
- return CallExternalCommand(commando, fullPath, null, out output, out error);
- } catch (Win32Exception w32Ex) {
- try {
- return CallExternalCommand(commando, fullPath, "runas", out output, out error);
- } catch {
- w32Ex.Data.Add("commandline", config.Commandline[_presetCommand]);
- w32Ex.Data.Add("arguments", config.Argument[_presetCommand]);
- throw;
- }
- } catch (Exception ex) {
- ex.Data.Add("commandline", config.Commandline[_presetCommand]);
- ex.Data.Add("arguments", config.Argument[_presetCommand]);
- throw;
- }
- }
+ ///
+ /// Wrapper method for the background and normal call, this does all the logic:
+ /// Call the external command, parse for URI, place to clipboard and set the export information
+ ///
+ ///
+ ///
+ ///
+ ///
+ private void CallExternalCommand(ExportInformation exportInformation, string fullPath, out string output, out string error)
+ {
+ output = null;
+ error = null;
+ try
+ {
+ if (CallExternalCommand(_presetCommand, fullPath, out output, out error) == 0)
+ {
+ exportInformation.ExportMade = true;
+ if (!string.IsNullOrEmpty(output))
+ {
+ MatchCollection uriMatches = URI_REGEXP.Matches(output);
+ // Place output on the clipboard before the URI, so if one is found this overwrites
+ if (config.OutputToClipboard)
+ {
+ ClipboardHelper.SetClipboardData(output);
+ }
- ///
- /// The actual executing code for the external command
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- private int CallExternalCommand(string commando, string fullPath, string verb, out string output, out string error) {
- string commandline = config.Commandline[commando];
- string arguments = config.Argument[commando];
- output = null;
- error = null;
- if (!string.IsNullOrEmpty(commandline))
+ if (uriMatches.Count > 0)
+ {
+ exportInformation.Uri = uriMatches[0].Groups[1].Value;
+ LOG.InfoFormat("Got URI : {0} ", exportInformation.Uri);
+ if (config.UriToClipboard)
+ {
+ ClipboardHelper.SetClipboardData(exportInformation.Uri);
+ }
+ }
+ }
+ }
+ else
+ {
+ LOG.WarnFormat("Error calling external command: {0} ", output);
+ exportInformation.ExportMade = false;
+ exportInformation.ErrorMessage = error;
+ }
+ }
+ catch (Exception ex)
+ {
+ exportInformation.ExportMade = false;
+ exportInformation.ErrorMessage = ex.Message;
+ LOG.WarnFormat("Error calling external command: {0} ", exportInformation.ErrorMessage);
+ }
+ }
+
+ ///
+ /// Wrapper to retry with a runas
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ private int CallExternalCommand(string commando, string fullPath, out string output, out string error)
+ {
+ try
+ {
+ return CallExternalCommand(commando, fullPath, null, out output, out error);
+ }
+ catch (Win32Exception w32Ex)
+ {
+ try
+ {
+ return CallExternalCommand(commando, fullPath, "runas", out output, out error);
+ }
+ catch
+ {
+ w32Ex.Data.Add("commandline", config.Commandline[_presetCommand]);
+ w32Ex.Data.Add("arguments", config.Argument[_presetCommand]);
+ throw;
+ }
+ }
+ catch (Exception ex)
+ {
+ ex.Data.Add("commandline", config.Commandline[_presetCommand]);
+ ex.Data.Add("arguments", config.Argument[_presetCommand]);
+ throw;
+ }
+ }
+
+ ///
+ /// The actual executing code for the external command
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ private int CallExternalCommand(string commando, string fullPath, string verb, out string output, out string error)
+ {
+ string commandline = config.Commandline[commando];
+ string arguments = config.Argument[commando];
+ output = null;
+ error = null;
+ if (!string.IsNullOrEmpty(commandline))
{
using Process process = new Process();
// Fix variables
@@ -183,39 +221,52 @@ namespace Greenshot.Plugin.ExternalCommand {
process.StartInfo.FileName = FilenameHelper.FillCmdVariables(commandline, true);
process.StartInfo.Arguments = FormatArguments(arguments, fullPath);
process.StartInfo.UseShellExecute = false;
- if (config.RedirectStandardOutput) {
+ if (config.RedirectStandardOutput)
+ {
process.StartInfo.RedirectStandardOutput = true;
}
- if (config.RedirectStandardError) {
+
+ if (config.RedirectStandardError)
+ {
process.StartInfo.RedirectStandardError = true;
}
- if (verb != null) {
+
+ if (verb != null)
+ {
process.StartInfo.Verb = verb;
}
+
LOG.InfoFormat("Starting : {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
process.Start();
process.WaitForExit();
- if (config.RedirectStandardOutput) {
+ if (config.RedirectStandardOutput)
+ {
output = process.StandardOutput.ReadToEnd();
- if (config.ShowStandardOutputInLog && output.Trim().Length > 0) {
+ if (config.ShowStandardOutputInLog && output.Trim().Length > 0)
+ {
LOG.InfoFormat("Output:\n{0}", output);
}
}
- if (config.RedirectStandardError) {
+
+ if (config.RedirectStandardError)
+ {
error = process.StandardError.ReadToEnd();
- if (error.Trim().Length > 0) {
+ if (error.Trim().Length > 0)
+ {
LOG.WarnFormat("Error:\n{0}", error);
}
}
+
LOG.InfoFormat("Finished : {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
return process.ExitCode;
}
- return -1;
- }
- public static string FormatArguments(string arguments, string fullpath)
- {
- return string.Format(arguments, fullpath);
- }
- }
-}
+ return -1;
+ }
+
+ public static string FormatArguments(string arguments, string fullpath)
+ {
+ return string.Format(arguments, fullpath);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandForm.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandForm.cs
index 7167b954b..7fdfffa2a 100644
--- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandForm.cs
+++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandForm.cs
@@ -21,10 +21,12 @@
using GreenshotPlugin.Controls;
-namespace Greenshot.Plugin.ExternalCommand {
- ///
- /// This class is needed for design-time resolving of the language files
- ///
- public class ExternalCommandForm : GreenshotForm {
- }
+namespace Greenshot.Plugin.ExternalCommand
+{
+ ///
+ /// This class is needed for design-time resolving of the language files
+ ///
+ public class ExternalCommandForm : GreenshotForm
+ {
+ }
}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs
index eeb99ed41..43ae03f41 100644
--- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs
+++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs
@@ -55,6 +55,7 @@ namespace Greenshot.Plugin.ExternalCommand
_itemPlugInRoot.Dispose();
_itemPlugInRoot = null;
}
+
private IEnumerable Destinations()
{
foreach (string command in ExternalCommandConfig.Commands)
@@ -77,17 +78,20 @@ namespace Greenshot.Plugin.ExternalCommand
// Fix it
ExternalCommandConfig.RunInbackground.Add(command, true);
}
+
if (!ExternalCommandConfig.Argument.ContainsKey(command))
{
Log.WarnFormat("Found missing argument for {0}", command);
// Fix it
ExternalCommandConfig.Argument.Add(command, "{0}");
}
+
if (!ExternalCommandConfig.Commandline.ContainsKey(command))
{
Log.WarnFormat("Found missing commandline for {0}", command);
return false;
}
+
string commandline = FilenameHelper.FillVariables(ExternalCommandConfig.Commandline[command], true);
commandline = FilenameHelper.FillCmdVariables(commandline, true);
@@ -96,8 +100,10 @@ namespace Greenshot.Plugin.ExternalCommand
Log.WarnFormat("Found 'invalid' commandline {0} for command {1}", ExternalCommandConfig.Commandline[command], command);
return false;
}
+
return true;
}
+
///
/// Implementation of the IGreenshotPlugin.Initialize
///
@@ -114,11 +120,13 @@ namespace Greenshot.Plugin.ExternalCommand
commandsToDelete.Add(command);
}
}
+
// cleanup
foreach (string command in commandsToDelete)
{
ExternalCommandConfig.Delete(command);
}
+
SimpleServiceProvider.Current.AddService(Destinations());
_itemPlugInRoot = new ToolStripMenuItem();
diff --git a/src/Greenshot.Plugin.ExternalCommand/IconCache.cs b/src/Greenshot.Plugin.ExternalCommand/IconCache.cs
index 44ea0a84d..f1b854164 100644
--- a/src/Greenshot.Plugin.ExternalCommand/IconCache.cs
+++ b/src/Greenshot.Plugin.ExternalCommand/IconCache.cs
@@ -25,23 +25,32 @@ using System.IO;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.ExternalCommand {
- public static class IconCache {
- private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection();
- private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IconCache));
+namespace Greenshot.Plugin.ExternalCommand
+{
+ public static class IconCache
+ {
+ private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection();
+ private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IconCache));
- public static Image IconForCommand(string commandName) {
- Image icon = null;
- if (commandName != null) {
- if (config.Commandline.ContainsKey(commandName) && File.Exists(config.Commandline[commandName])) {
- try {
- icon = PluginUtils.GetCachedExeIcon(config.Commandline[commandName], 0);
- } catch (Exception ex) {
- LOG.Warn("Problem loading icon for " + config.Commandline[commandName], ex);
- }
- }
- }
- return icon;
- }
- }
-}
+ public static Image IconForCommand(string commandName)
+ {
+ Image icon = null;
+ if (commandName != null)
+ {
+ if (config.Commandline.ContainsKey(commandName) && File.Exists(config.Commandline[commandName]))
+ {
+ try
+ {
+ icon = PluginUtils.GetCachedExeIcon(config.Commandline[commandName], 0);
+ }
+ catch (Exception ex)
+ {
+ LOG.Warn("Problem loading icon for " + config.Commandline[commandName], ex);
+ }
+ }
+ }
+
+ return icon;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs b/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs
index c4cf9ca2b..49e872d7f 100644
--- a/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs
+++ b/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs
@@ -24,103 +24,129 @@ using System.Drawing;
using System.Windows.Forms;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.ExternalCommand {
- ///
- /// Description of SettingsForm.
- ///
- public partial class SettingsForm : ExternalCommandForm {
- private static readonly ExternalCommandConfiguration ExternalCommandConfig = IniConfig.GetIniSection();
+namespace Greenshot.Plugin.ExternalCommand
+{
+ ///
+ /// Description of SettingsForm.
+ ///
+ public partial class SettingsForm : ExternalCommandForm
+ {
+ private static readonly ExternalCommandConfiguration ExternalCommandConfig = IniConfig.GetIniSection();
- public SettingsForm() {
- //
- // The InitializeComponent() call is required for Windows Forms designer support.
- //
- InitializeComponent();
- AcceptButton = buttonOk;
- CancelButton = buttonCancel;
- UpdateView();
- }
+ public SettingsForm()
+ {
+ //
+ // The InitializeComponent() call is required for Windows Forms designer support.
+ //
+ InitializeComponent();
+ AcceptButton = buttonOk;
+ CancelButton = buttonCancel;
+ UpdateView();
+ }
- private void ButtonOkClick(object sender, EventArgs e) {
- IniConfig.Save();
- }
+ private void ButtonOkClick(object sender, EventArgs e)
+ {
+ IniConfig.Save();
+ }
- private void ButtonAddClick(object sender, EventArgs e) {
- var form = new SettingsFormDetail(null);
- form.ShowDialog();
+ private void ButtonAddClick(object sender, EventArgs e)
+ {
+ var form = new SettingsFormDetail(null);
+ form.ShowDialog();
- UpdateView();
- }
+ UpdateView();
+ }
- private void ButtonDeleteClick(object sender, EventArgs e) {
- foreach(ListViewItem item in listView1.SelectedItems) {
- string commando = item.Tag as string;
+ private void ButtonDeleteClick(object sender, EventArgs e)
+ {
+ foreach (ListViewItem item in listView1.SelectedItems)
+ {
+ string commando = item.Tag as string;
- ExternalCommandConfig.Delete(commando);
- }
- UpdateView();
- }
+ ExternalCommandConfig.Delete(commando);
+ }
- private void UpdateView() {
- listView1.Items.Clear();
- if(ExternalCommandConfig.Commands != null) {
- listView1.ListViewItemSorter = new ListviewComparer();
- ImageList imageList = new ImageList();
- listView1.SmallImageList = imageList;
- int imageNr = 0;
- foreach(string commando in ExternalCommandConfig.Commands) {
- ListViewItem item;
- Image iconForExe = IconCache.IconForCommand(commando);
- if(iconForExe != null) {
- imageList.Images.Add(iconForExe);
- item = new ListViewItem(commando, imageNr++);
- } else {
- item = new ListViewItem(commando);
- }
- item.Tag = commando;
- listView1.Items.Add(item);
- }
- }
- // Fix for bug #1484, getting an ArgumentOutOfRangeException as there is nothing selected but the edit button was still active.
- button_edit.Enabled = listView1.SelectedItems.Count > 0;
- }
+ UpdateView();
+ }
- private void ListView1ItemSelectionChanged(object sender, EventArgs e) {
- button_edit.Enabled = listView1.SelectedItems.Count > 0;
- }
+ private void UpdateView()
+ {
+ listView1.Items.Clear();
+ if (ExternalCommandConfig.Commands != null)
+ {
+ listView1.ListViewItemSorter = new ListviewComparer();
+ ImageList imageList = new ImageList();
+ listView1.SmallImageList = imageList;
+ int imageNr = 0;
+ foreach (string commando in ExternalCommandConfig.Commands)
+ {
+ ListViewItem item;
+ Image iconForExe = IconCache.IconForCommand(commando);
+ if (iconForExe != null)
+ {
+ imageList.Images.Add(iconForExe);
+ item = new ListViewItem(commando, imageNr++);
+ }
+ else
+ {
+ item = new ListViewItem(commando);
+ }
- private void ButtonEditClick(object sender, EventArgs e) {
- ListView1DoubleClick(sender, e);
- }
+ item.Tag = commando;
+ listView1.Items.Add(item);
+ }
+ }
- private void ListView1DoubleClick(object sender, EventArgs e) {
- // Safety check for bug #1484
- bool selectionActive = listView1.SelectedItems.Count > 0;
- if(!selectionActive) {
- button_edit.Enabled = false;
- return;
- }
- string commando = listView1.SelectedItems[0].Tag as string;
+ // Fix for bug #1484, getting an ArgumentOutOfRangeException as there is nothing selected but the edit button was still active.
+ button_edit.Enabled = listView1.SelectedItems.Count > 0;
+ }
- var form = new SettingsFormDetail(commando);
- form.ShowDialog();
+ private void ListView1ItemSelectionChanged(object sender, EventArgs e)
+ {
+ button_edit.Enabled = listView1.SelectedItems.Count > 0;
+ }
- UpdateView();
- }
- }
+ private void ButtonEditClick(object sender, EventArgs e)
+ {
+ ListView1DoubleClick(sender, e);
+ }
- public class ListviewComparer : System.Collections.IComparer {
- public int Compare(object x, object y) {
- if(!(x is ListViewItem)) {
- return (0);
- }
- if(!(y is ListViewItem)) {
- return (0);
- }
+ private void ListView1DoubleClick(object sender, EventArgs e)
+ {
+ // Safety check for bug #1484
+ bool selectionActive = listView1.SelectedItems.Count > 0;
+ if (!selectionActive)
+ {
+ button_edit.Enabled = false;
+ return;
+ }
- var l1 = (ListViewItem)x;
- var l2 = (ListViewItem)y;
- return string.Compare(l1.Text, l2.Text, StringComparison.Ordinal);
- }
- }
-}
+ string commando = listView1.SelectedItems[0].Tag as string;
+
+ var form = new SettingsFormDetail(commando);
+ form.ShowDialog();
+
+ UpdateView();
+ }
+ }
+
+ public class ListviewComparer : System.Collections.IComparer
+ {
+ public int Compare(object x, object y)
+ {
+ if (!(x is ListViewItem))
+ {
+ return (0);
+ }
+
+ if (!(y is ListViewItem))
+ {
+ return (0);
+ }
+
+ var l1 = (ListViewItem) x;
+ var l2 = (ListViewItem) y;
+ return string.Compare(l1.Text, l2.Text, StringComparison.Ordinal);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs b/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs
index 9c353b197..8aa235a67 100644
--- a/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs
+++ b/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs
@@ -26,141 +26,167 @@ using System.Windows.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.ExternalCommand {
- ///
- /// Description of SettingsFormDetail.
- ///
- public partial class SettingsFormDetail : ExternalCommandForm {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(SettingsFormDetail));
- private static readonly ExternalCommandConfiguration ExternalCommandConfig = IniConfig.GetIniSection();
+namespace Greenshot.Plugin.ExternalCommand
+{
+ ///
+ /// Description of SettingsFormDetail.
+ ///
+ public partial class SettingsFormDetail : ExternalCommandForm
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(SettingsFormDetail));
+ private static readonly ExternalCommandConfiguration ExternalCommandConfig = IniConfig.GetIniSection();
- private readonly string _commando;
- private readonly int _commandIndex;
+ private readonly string _commando;
+ private readonly int _commandIndex;
- public SettingsFormDetail(string commando) {
- InitializeComponent();
- AcceptButton = buttonOk;
- CancelButton = buttonCancel;
- _commando = commando;
+ public SettingsFormDetail(string commando)
+ {
+ InitializeComponent();
+ AcceptButton = buttonOk;
+ CancelButton = buttonCancel;
+ _commando = commando;
- if(commando != null) {
- textBox_name.Text = commando;
- textBox_commandline.Text = ExternalCommandConfig.Commandline[commando];
- textBox_arguments.Text = ExternalCommandConfig.Argument[commando];
- _commandIndex = ExternalCommandConfig.Commands.FindIndex(s => s == commando);
- } else {
- textBox_arguments.Text = "\"{0}\"";
- }
- OkButtonState();
- }
+ if (commando != null)
+ {
+ textBox_name.Text = commando;
+ textBox_commandline.Text = ExternalCommandConfig.Commandline[commando];
+ textBox_arguments.Text = ExternalCommandConfig.Argument[commando];
+ _commandIndex = ExternalCommandConfig.Commands.FindIndex(s => s == commando);
+ }
+ else
+ {
+ textBox_arguments.Text = "\"{0}\"";
+ }
- private void ButtonOkClick(object sender, EventArgs e) {
- string commandName = textBox_name.Text;
- string commandLine = textBox_commandline.Text;
- string arguments = textBox_arguments.Text;
- if(_commando != null) {
- ExternalCommandConfig.Commands[_commandIndex] = commandName;
- ExternalCommandConfig.Commandline.Remove(_commando);
- ExternalCommandConfig.Commandline.Add(commandName, commandLine);
- ExternalCommandConfig.Argument.Remove(_commando);
- ExternalCommandConfig.Argument.Add(commandName, arguments);
- } else {
- ExternalCommandConfig.Commands.Add(commandName);
- ExternalCommandConfig.Commandline.Add(commandName, commandLine);
- ExternalCommandConfig.Argument.Add(commandName, arguments);
- }
- }
+ OkButtonState();
+ }
- private void Button3Click(object sender, EventArgs e) {
- var openFileDialog = new OpenFileDialog
- {
- Filter = "Executables (*.exe, *.bat, *.com)|*.exe; *.bat; *.com|All files (*)|*",
- FilterIndex = 1,
- CheckFileExists = true,
- Multiselect = false
- };
- string initialPath = null;
- try
- {
- initialPath = Path.GetDirectoryName(textBox_commandline.Text);
- }
- catch (Exception ex)
- {
- Log.WarnFormat("Can't get the initial path via {0}", textBox_commandline.Text);
- Log.Warn("Exception: ", ex);
- }
- if(initialPath != null && Directory.Exists(initialPath)) {
- openFileDialog.InitialDirectory = initialPath;
- } else {
- initialPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
- openFileDialog.InitialDirectory = initialPath;
- }
- Log.DebugFormat("Starting OpenFileDialog at {0}", initialPath);
- if(openFileDialog.ShowDialog() == DialogResult.OK) {
- textBox_commandline.Text = openFileDialog.FileName;
- }
- }
+ private void ButtonOkClick(object sender, EventArgs e)
+ {
+ string commandName = textBox_name.Text;
+ string commandLine = textBox_commandline.Text;
+ string arguments = textBox_arguments.Text;
+ if (_commando != null)
+ {
+ ExternalCommandConfig.Commands[_commandIndex] = commandName;
+ ExternalCommandConfig.Commandline.Remove(_commando);
+ ExternalCommandConfig.Commandline.Add(commandName, commandLine);
+ ExternalCommandConfig.Argument.Remove(_commando);
+ ExternalCommandConfig.Argument.Add(commandName, arguments);
+ }
+ else
+ {
+ ExternalCommandConfig.Commands.Add(commandName);
+ ExternalCommandConfig.Commandline.Add(commandName, commandLine);
+ ExternalCommandConfig.Argument.Add(commandName, arguments);
+ }
+ }
- private void OkButtonState() {
- // Assume OK
- buttonOk.Enabled = true;
- textBox_name.BackColor = Color.White;
- textBox_commandline.BackColor = Color.White;
- textBox_arguments.BackColor = Color.White;
- // Is there a text in the name field
- if(string.IsNullOrEmpty(textBox_name.Text)) {
- buttonOk.Enabled = false;
- }
- // Check if commandname is unique
- if(_commando == null && !string.IsNullOrEmpty(textBox_name.Text) && ExternalCommandConfig.Commands.Contains(textBox_name.Text)) {
- buttonOk.Enabled = false;
- textBox_name.BackColor = Color.Red;
- }
- // Is there a text in the commandline field
- if(string.IsNullOrEmpty(textBox_commandline.Text)) {
- buttonOk.Enabled = false;
- }
+ private void Button3Click(object sender, EventArgs e)
+ {
+ var openFileDialog = new OpenFileDialog
+ {
+ Filter = "Executables (*.exe, *.bat, *.com)|*.exe; *.bat; *.com|All files (*)|*",
+ FilterIndex = 1,
+ CheckFileExists = true,
+ Multiselect = false
+ };
+ string initialPath = null;
+ try
+ {
+ initialPath = Path.GetDirectoryName(textBox_commandline.Text);
+ }
+ catch (Exception ex)
+ {
+ Log.WarnFormat("Can't get the initial path via {0}", textBox_commandline.Text);
+ Log.Warn("Exception: ", ex);
+ }
- if (!string.IsNullOrEmpty(textBox_commandline.Text))
- {
- // Added this to be more flexible, using the Greenshot var format
- string cmdPath = FilenameHelper.FillVariables(textBox_commandline.Text, true);
- // And also replace the "DOS" Variables
- cmdPath = FilenameHelper.FillCmdVariables(cmdPath, true);
- // Is the command available?
- if (!File.Exists(cmdPath))
- {
- buttonOk.Enabled = false;
- textBox_commandline.BackColor = Color.Red;
- }
- }
- // Are the arguments in a valid format?
- try
- {
- string arguments = FilenameHelper.FillVariables(textBox_arguments.Text, false);
- arguments = FilenameHelper.FillCmdVariables(arguments, false);
+ if (initialPath != null && Directory.Exists(initialPath))
+ {
+ openFileDialog.InitialDirectory = initialPath;
+ }
+ else
+ {
+ initialPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
+ openFileDialog.InitialDirectory = initialPath;
+ }
- ExternalCommandDestination.FormatArguments(arguments, string.Empty);
- }
- catch
- {
- buttonOk.Enabled = false;
- textBox_arguments.BackColor = Color.Red;
- }
- }
+ Log.DebugFormat("Starting OpenFileDialog at {0}", initialPath);
+ if (openFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ textBox_commandline.Text = openFileDialog.FileName;
+ }
+ }
- private void textBox_name_TextChanged(object sender, EventArgs e) {
- OkButtonState();
- }
+ private void OkButtonState()
+ {
+ // Assume OK
+ buttonOk.Enabled = true;
+ textBox_name.BackColor = Color.White;
+ textBox_commandline.BackColor = Color.White;
+ textBox_arguments.BackColor = Color.White;
+ // Is there a text in the name field
+ if (string.IsNullOrEmpty(textBox_name.Text))
+ {
+ buttonOk.Enabled = false;
+ }
- private void textBox_commandline_TextChanged(object sender, EventArgs e) {
- OkButtonState();
- }
+ // Check if commandname is unique
+ if (_commando == null && !string.IsNullOrEmpty(textBox_name.Text) && ExternalCommandConfig.Commands.Contains(textBox_name.Text))
+ {
+ buttonOk.Enabled = false;
+ textBox_name.BackColor = Color.Red;
+ }
- private void textBox_arguments_TextChanged(object sender, EventArgs e)
- {
- OkButtonState();
- }
+ // Is there a text in the commandline field
+ if (string.IsNullOrEmpty(textBox_commandline.Text))
+ {
+ buttonOk.Enabled = false;
+ }
- }
-}
+ if (!string.IsNullOrEmpty(textBox_commandline.Text))
+ {
+ // Added this to be more flexible, using the Greenshot var format
+ string cmdPath = FilenameHelper.FillVariables(textBox_commandline.Text, true);
+ // And also replace the "DOS" Variables
+ cmdPath = FilenameHelper.FillCmdVariables(cmdPath, true);
+ // Is the command available?
+ if (!File.Exists(cmdPath))
+ {
+ buttonOk.Enabled = false;
+ textBox_commandline.BackColor = Color.Red;
+ }
+ }
+
+ // Are the arguments in a valid format?
+ try
+ {
+ string arguments = FilenameHelper.FillVariables(textBox_arguments.Text, false);
+ arguments = FilenameHelper.FillCmdVariables(arguments, false);
+
+ ExternalCommandDestination.FormatArguments(arguments, string.Empty);
+ }
+ catch
+ {
+ buttonOk.Enabled = false;
+ textBox_arguments.BackColor = Color.Red;
+ }
+ }
+
+ private void textBox_name_TextChanged(object sender, EventArgs e)
+ {
+ OkButtonState();
+ }
+
+ private void textBox_commandline_TextChanged(object sender, EventArgs e)
+ {
+ OkButtonState();
+ }
+
+ private void textBox_arguments_TextChanged(object sender, EventArgs e)
+ {
+ OkButtonState();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Flickr/FlickrConfiguration.cs b/src/Greenshot.Plugin.Flickr/FlickrConfiguration.cs
index 600e61a47..68fc72a3e 100644
--- a/src/Greenshot.Plugin.Flickr/FlickrConfiguration.cs
+++ b/src/Greenshot.Plugin.Flickr/FlickrConfiguration.cs
@@ -24,59 +24,67 @@ using Greenshot.Plugin.Flickr.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.Flickr {
- public enum SafetyLevel {
- Safe = 1,
- Moderate = 2,
- Restricted = 3
- }
- ///
- /// Description of FlickrConfiguration.
- ///
- [IniSection("Flickr", Description = "Greenshot Flickr Plugin configuration")]
- public class FlickrConfiguration : IniSection {
- [IniProperty("flickrIsPublic", Description = "IsPublic.", DefaultValue = "true")]
- public bool IsPublic { get; set; }
+namespace Greenshot.Plugin.Flickr
+{
+ public enum SafetyLevel
+ {
+ Safe = 1,
+ Moderate = 2,
+ Restricted = 3
+ }
- [IniProperty("flickrIsFamily", Description = "IsFamily.", DefaultValue = "true")]
- public bool IsFamily { get; set; }
+ ///
+ /// Description of FlickrConfiguration.
+ ///
+ [IniSection("Flickr", Description = "Greenshot Flickr Plugin configuration")]
+ public class FlickrConfiguration : IniSection
+ {
+ [IniProperty("flickrIsPublic", Description = "IsPublic.", DefaultValue = "true")]
+ public bool IsPublic { get; set; }
- [IniProperty("flickrIsFriend", Description = "IsFriend.", DefaultValue = "true")]
- public bool IsFriend { get; set; }
+ [IniProperty("flickrIsFamily", Description = "IsFamily.", DefaultValue = "true")]
+ public bool IsFamily { get; set; }
- [IniProperty("SafetyLevel", Description = "Safety level", DefaultValue = "Safe")]
- public SafetyLevel SafetyLevel { get; set; }
+ [IniProperty("flickrIsFriend", Description = "IsFriend.", DefaultValue = "true")]
+ public bool IsFriend { get; set; }
- [IniProperty("HiddenFromSearch", Description = "Hidden from search", DefaultValue = "false")]
- public bool HiddenFromSearch { get; set; }
+ [IniProperty("SafetyLevel", Description = "Safety level", DefaultValue = "Safe")]
+ public SafetyLevel SafetyLevel { get; set; }
- [IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
- public OutputFormat UploadFormat { get; set; }
+ [IniProperty("HiddenFromSearch", Description = "Hidden from search", DefaultValue = "false")]
+ public bool HiddenFromSearch { get; set; }
- [IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]
- public int UploadJpegQuality { get; set; }
+ [IniProperty("UploadFormat", Description = "What file type to use for uploading", DefaultValue = "png")]
+ public OutputFormat UploadFormat { get; set; }
- [IniProperty("AfterUploadLinkToClipBoard", Description = "After upload send flickr link to clipboard.", DefaultValue = "true")]
- public bool AfterUploadLinkToClipBoard { get; set; }
+ [IniProperty("UploadJpegQuality", Description = "JPEG file save quality in %.", DefaultValue = "80")]
+ public int UploadJpegQuality { get; set; }
- [IniProperty("UsePageLink", Description = "Use pagelink instead of direct link on the clipboard", DefaultValue = "False")]
- public bool UsePageLink { get; set; }
+ [IniProperty("AfterUploadLinkToClipBoard", Description = "After upload send flickr link to clipboard.", DefaultValue = "true")]
+ public bool AfterUploadLinkToClipBoard { get; set; }
- [IniProperty("FlickrToken", Description = "The Flickr token", Encrypted = true, ExcludeIfNull = true)]
- public string FlickrToken { get; set; }
- [IniProperty("FlickrTokenSecret", Description = "The Flickr token secret", Encrypted = true, ExcludeIfNull = true)]
- public string FlickrTokenSecret { get; set; }
+ [IniProperty("UsePageLink", Description = "Use pagelink instead of direct link on the clipboard", DefaultValue = "False")]
+ public bool UsePageLink { get; set; }
- ///
- /// A form for token
- ///
- /// bool true if OK was pressed, false if cancel
- public bool ShowConfigDialog() {
- DialogResult result = new SettingsForm().ShowDialog();
- if (result == DialogResult.OK) {
- return true;
- }
- return false;
- }
- }
-}
+ [IniProperty("FlickrToken", Description = "The Flickr token", Encrypted = true, ExcludeIfNull = true)]
+ public string FlickrToken { get; set; }
+
+ [IniProperty("FlickrTokenSecret", Description = "The Flickr token secret", Encrypted = true, ExcludeIfNull = true)]
+ public string FlickrTokenSecret { get; set; }
+
+ ///
+ /// A form for token
+ ///
+ /// bool true if OK was pressed, false if cancel
+ public bool ShowConfigDialog()
+ {
+ DialogResult result = new SettingsForm().ShowDialog();
+ if (result == DialogResult.OK)
+ {
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Flickr/FlickrDestination.cs b/src/Greenshot.Plugin.Flickr/FlickrDestination.cs
index 340cf3c09..ec61f3b62 100644
--- a/src/Greenshot.Plugin.Flickr/FlickrDestination.cs
+++ b/src/Greenshot.Plugin.Flickr/FlickrDestination.cs
@@ -24,33 +24,42 @@ using System.Drawing;
using GreenshotPlugin.Core;
using GreenshotPlugin.Interfaces;
-namespace Greenshot.Plugin.Flickr {
- public class FlickrDestination : AbstractDestination {
- private readonly FlickrPlugin _plugin;
- public FlickrDestination(FlickrPlugin plugin) {
- _plugin = plugin;
- }
+namespace Greenshot.Plugin.Flickr
+{
+ public class FlickrDestination : AbstractDestination
+ {
+ private readonly FlickrPlugin _plugin;
- public override string Designation => "Flickr";
+ public FlickrDestination(FlickrPlugin plugin)
+ {
+ _plugin = plugin;
+ }
- public override string Description => Language.GetString("flickr", LangKey.upload_menu_item);
+ public override string Designation => "Flickr";
- public override Image DisplayIcon {
- get {
- ComponentResourceManager resources = new ComponentResourceManager(typeof(FlickrPlugin));
- return (Image)resources.GetObject("flickr");
- }
- }
+ public override string Description => Language.GetString("flickr", LangKey.upload_menu_item);
- public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
- ExportInformation exportInformation = new ExportInformation(Designation, Description);
+ public override Image DisplayIcon
+ {
+ get
+ {
+ ComponentResourceManager resources = new ComponentResourceManager(typeof(FlickrPlugin));
+ return (Image) resources.GetObject("flickr");
+ }
+ }
+
+ public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
+ {
+ ExportInformation exportInformation = new ExportInformation(Designation, Description);
bool uploaded = _plugin.Upload(captureDetails, surface, out var uploadUrl);
- if (uploaded) {
- exportInformation.ExportMade = true;
- exportInformation.Uri = uploadUrl;
- }
- ProcessExport(exportInformation, surface);
- return exportInformation;
- }
- }
-}
+ if (uploaded)
+ {
+ exportInformation.ExportMade = true;
+ exportInformation.Uri = uploadUrl;
+ }
+
+ ProcessExport(exportInformation, surface);
+ return exportInformation;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs b/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs
index 62f21a509..0ce2afaad 100644
--- a/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs
+++ b/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs
@@ -33,99 +33,122 @@ using log4net;
namespace Greenshot.Plugin.Flickr
{
- ///
- /// This is the Flickr base code
- ///
+ ///
+ /// This is the Flickr base code
+ ///
[Plugin("Flickr", true)]
- public class FlickrPlugin : IGreenshotPlugin {
- private static readonly ILog Log = LogManager.GetLogger(typeof(FlickrPlugin));
- private static FlickrConfiguration _config;
- private ComponentResourceManager _resources;
- private ToolStripMenuItem _itemPlugInConfig;
+ public class FlickrPlugin : IGreenshotPlugin
+ {
+ private static readonly ILog Log = LogManager.GetLogger(typeof(FlickrPlugin));
+ private static FlickrConfiguration _config;
+ private ComponentResourceManager _resources;
+ private ToolStripMenuItem _itemPlugInConfig;
- public void Dispose() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- protected void Dispose(bool disposing) {
- if (!disposing) {
- return;
- }
- if (_itemPlugInConfig == null) {
- return;
- }
- _itemPlugInConfig.Dispose();
- _itemPlugInConfig = null;
- }
+ protected void Dispose(bool disposing)
+ {
+ if (!disposing)
+ {
+ return;
+ }
- ///
- /// Implementation of the IGreenshotPlugin.Initialize
- ///
- public bool Initialize() {
- // Register configuration (don't need the configuration itself)
- _config = IniConfig.GetIniSection();
- _resources = new ComponentResourceManager(typeof(FlickrPlugin));
+ if (_itemPlugInConfig == null)
+ {
+ return;
+ }
- _itemPlugInConfig = new ToolStripMenuItem
- {
- Text = Language.GetString("flickr", LangKey.Configure),
- Image = (Image) _resources.GetObject("flickr")
- };
- _itemPlugInConfig.Click += ConfigMenuClick;
+ _itemPlugInConfig.Dispose();
+ _itemPlugInConfig = null;
+ }
+
+ ///
+ /// Implementation of the IGreenshotPlugin.Initialize
+ ///
+ public bool Initialize()
+ {
+ // Register configuration (don't need the configuration itself)
+ _config = IniConfig.GetIniSection();
+ _resources = new ComponentResourceManager(typeof(FlickrPlugin));
+
+ _itemPlugInConfig = new ToolStripMenuItem
+ {
+ Text = Language.GetString("flickr", LangKey.Configure),
+ Image = (Image) _resources.GetObject("flickr")
+ };
+ _itemPlugInConfig.Click += ConfigMenuClick;
SimpleServiceProvider.Current.AddService(new FlickrDestination(this));
- PluginUtils.AddToContextMenu(_itemPlugInConfig);
- Language.LanguageChanged += OnLanguageChanged;
- return true;
- }
+ PluginUtils.AddToContextMenu(_itemPlugInConfig);
+ Language.LanguageChanged += OnLanguageChanged;
+ return true;
+ }
- public void OnLanguageChanged(object sender, EventArgs e) {
- if (_itemPlugInConfig != null) {
- _itemPlugInConfig.Text = Language.GetString("flickr", LangKey.Configure);
- }
- }
+ public void OnLanguageChanged(object sender, EventArgs e)
+ {
+ if (_itemPlugInConfig != null)
+ {
+ _itemPlugInConfig.Text = Language.GetString("flickr", LangKey.Configure);
+ }
+ }
- public void Shutdown() {
- Log.Debug("Flickr Plugin shutdown.");
- }
+ public void Shutdown()
+ {
+ Log.Debug("Flickr Plugin shutdown.");
+ }
- ///
- /// Implementation of the IPlugin.Configure
- ///
- public void Configure() {
- _config.ShowConfigDialog();
- }
+ ///
+ /// Implementation of the IPlugin.Configure
+ ///
+ public void Configure()
+ {
+ _config.ShowConfigDialog();
+ }
- public void ConfigMenuClick(object sender, EventArgs eventArgs) {
- _config.ShowConfigDialog();
- }
+ public void ConfigMenuClick(object sender, EventArgs eventArgs)
+ {
+ _config.ShowConfigDialog();
+ }
- public bool Upload(ICaptureDetails captureDetails, ISurface surface, out string uploadUrl) {
- SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false);
- uploadUrl = null;
- try {
- string flickrUrl = null;
- new PleaseWaitForm().ShowAndWait("Flickr", Language.GetString("flickr", LangKey.communication_wait),
- delegate {
- string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails));
- flickrUrl = FlickrUtils.UploadToFlickr(surface, outputSettings, captureDetails.Title, filename);
- }
- );
-
- if (flickrUrl == null) {
- return false;
- }
- uploadUrl = flickrUrl;
+ public bool Upload(ICaptureDetails captureDetails, ISurface surface, out string uploadUrl)
+ {
+ SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, false);
+ uploadUrl = null;
+ try
+ {
+ string flickrUrl = null;
+ new PleaseWaitForm().ShowAndWait("Flickr", Language.GetString("flickr", LangKey.communication_wait),
+ delegate
+ {
+ string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails));
+ flickrUrl = FlickrUtils.UploadToFlickr(surface, outputSettings, captureDetails.Title, filename);
+ }
+ );
- if (_config.AfterUploadLinkToClipBoard) {
- ClipboardHelper.SetClipboardData(flickrUrl);
- }
- return true;
- } catch (Exception e) {
- Log.Error("Error uploading.", e);
- MessageBox.Show(Language.GetString("flickr", LangKey.upload_failure) + " " + e.Message);
- }
- return false;
- }
- }
-}
+ if (flickrUrl == null)
+ {
+ return false;
+ }
+
+ uploadUrl = flickrUrl;
+
+ if (_config.AfterUploadLinkToClipBoard)
+ {
+ ClipboardHelper.SetClipboardData(flickrUrl);
+ }
+
+ return true;
+ }
+ catch (Exception e)
+ {
+ Log.Error("Error uploading.", e);
+ MessageBox.Show(Language.GetString("flickr", LangKey.upload_failure) + " " + e.Message);
+ }
+
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Flickr/FlickrUtils.cs b/src/Greenshot.Plugin.Flickr/FlickrUtils.cs
index c6978a17d..582484433 100644
--- a/src/Greenshot.Plugin.Flickr/FlickrUtils.cs
+++ b/src/Greenshot.Plugin.Flickr/FlickrUtils.cs
@@ -30,140 +30,203 @@ using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
using log4net;
-namespace Greenshot.Plugin.Flickr {
- ///
- /// Description of FlickrUtils.
- ///
- public static class FlickrUtils {
- private static readonly ILog LOG = LogManager.GetLogger(typeof(FlickrUtils));
- private static readonly FlickrConfiguration config = IniConfig.GetIniSection();
- private const string FLICKR_API_BASE_URL = "https://api.flickr.com/services/";
- private const string FLICKR_UPLOAD_URL = FLICKR_API_BASE_URL + "upload/";
- // OAUTH
- private const string FLICKR_OAUTH_BASE_URL = FLICKR_API_BASE_URL + "oauth/";
- private const string FLICKR_ACCESS_TOKEN_URL = FLICKR_OAUTH_BASE_URL + "access_token";
- private const string FLICKR_AUTHORIZE_URL = FLICKR_OAUTH_BASE_URL + "authorize";
- private const string FLICKR_REQUEST_TOKEN_URL = FLICKR_OAUTH_BASE_URL + "request_token";
- private const string FLICKR_FARM_URL = "https://farm{0}.staticflickr.com/{1}/{2}_{3}_o.{4}";
- // REST
- private const string FLICKR_REST_URL = FLICKR_API_BASE_URL + "rest/";
- private const string FLICKR_GET_INFO_URL = FLICKR_REST_URL + "?method=flickr.photos.getInfo";
+namespace Greenshot.Plugin.Flickr
+{
+ ///
+ /// Description of FlickrUtils.
+ ///
+ public static class FlickrUtils
+ {
+ private static readonly ILog LOG = LogManager.GetLogger(typeof(FlickrUtils));
+ private static readonly FlickrConfiguration config = IniConfig.GetIniSection();
+ private const string FLICKR_API_BASE_URL = "https://api.flickr.com/services/";
- ///
- /// Do the actual upload to Flickr
- /// For more details on the available parameters, see: http://flickrnet.codeplex.com
- ///
- ///
- ///
- ///
- ///
- /// url to image
- public static string UploadToFlickr(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename) {
- var oAuth = new OAuthSession(FlickrCredentials.ConsumerKey, FlickrCredentials.ConsumerSecret)
- {
- BrowserSize = new Size(520, 800),
- CheckVerifier = false,
- AccessTokenUrl = FLICKR_ACCESS_TOKEN_URL,
- AuthorizeUrl = FLICKR_AUTHORIZE_URL,
- RequestTokenUrl = FLICKR_REQUEST_TOKEN_URL,
- LoginTitle = "Flickr authorization",
- Token = config.FlickrToken,
- TokenSecret = config.FlickrTokenSecret
- };
- if (string.IsNullOrEmpty(oAuth.Token)) {
- if (!oAuth.Authorize()) {
- return null;
- }
- if (!string.IsNullOrEmpty(oAuth.Token)) {
- config.FlickrToken = oAuth.Token;
- }
- if (!string.IsNullOrEmpty(oAuth.TokenSecret)) {
- config.FlickrTokenSecret = oAuth.TokenSecret;
- }
- IniConfig.Save();
- }
- try {
- IDictionary signedParameters = new Dictionary
- {
- { "content_type", "2" }, // Screenshot
- { "tags", "Greenshot" },
- { "is_public", config.IsPublic ? "1" : "0" },
- { "is_friend", config.IsFriend ? "1" : "0" },
- { "is_family", config.IsFamily ? "1" : "0" },
- { "safety_level", $"{(int)config.SafetyLevel}" },
- { "hidden", config.HiddenFromSearch ? "1" : "2" }
- };
- IDictionary otherParameters = new Dictionary
- {
- { "photo", new SurfaceContainer(surfaceToUpload, outputSettings, filename) }
- };
- string response = oAuth.MakeOAuthRequest(HTTPMethod.POST, FLICKR_UPLOAD_URL, signedParameters, otherParameters, null);
- string photoId = GetPhotoId(response);
+ private const string FLICKR_UPLOAD_URL = FLICKR_API_BASE_URL + "upload/";
- // Get Photo Info
- signedParameters = new Dictionary { { "photo_id", photoId } };
- string photoInfo = oAuth.MakeOAuthRequest(HTTPMethod.POST, FLICKR_GET_INFO_URL, signedParameters, null, null);
- return GetUrl(photoInfo);
- } catch (Exception ex) {
- LOG.Error("Upload error: ", ex);
- throw;
- } finally {
- if (!string.IsNullOrEmpty(oAuth.Token)) {
- config.FlickrToken = oAuth.Token;
- }
- if (!string.IsNullOrEmpty(oAuth.TokenSecret)) {
- config.FlickrTokenSecret = oAuth.TokenSecret;
- }
- }
- }
+ // OAUTH
+ private const string FLICKR_OAUTH_BASE_URL = FLICKR_API_BASE_URL + "oauth/";
+ private const string FLICKR_ACCESS_TOKEN_URL = FLICKR_OAUTH_BASE_URL + "access_token";
+ private const string FLICKR_AUTHORIZE_URL = FLICKR_OAUTH_BASE_URL + "authorize";
+ private const string FLICKR_REQUEST_TOKEN_URL = FLICKR_OAUTH_BASE_URL + "request_token";
- private static string GetUrl(string response) {
- try {
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(response);
- if (config.UsePageLink) {
- XmlNodeList nodes = doc.GetElementsByTagName("url");
- if (nodes.Count > 0) {
- var xmlNode = nodes.Item(0);
- if (xmlNode != null) {
- return xmlNode.InnerText;
- }
- }
- } else {
- XmlNodeList nodes = doc.GetElementsByTagName("photo");
- if (nodes.Count > 0) {
- var item = nodes.Item(0);
- if (item?.Attributes != null) {
- string farmId = item.Attributes["farm"].Value;
- string serverId = item.Attributes["server"].Value;
- string photoId = item.Attributes["id"].Value;
- string originalsecret = item.Attributes["originalsecret"].Value;
- string originalFormat = item.Attributes["originalformat"].Value;
- return string.Format(FLICKR_FARM_URL, farmId, serverId, photoId, originalsecret, originalFormat);
- }
- }
- }
- } catch (Exception ex) {
- LOG.Error("Error parsing Flickr Response.", ex);
- }
- return null;
- }
+ private const string FLICKR_FARM_URL = "https://farm{0}.staticflickr.com/{1}/{2}_{3}_o.{4}";
- private static string GetPhotoId(string response) {
- try {
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(response);
- XmlNodeList nodes = doc.GetElementsByTagName("photoid");
- if (nodes.Count > 0) {
- var xmlNode = nodes.Item(0);
- if (xmlNode != null) {
- return xmlNode.InnerText;
- }
- }
- } catch (Exception ex) {
- LOG.Error("Error parsing Flickr Response.", ex);
- }
- return null;
- }
- }
-}
+ // REST
+ private const string FLICKR_REST_URL = FLICKR_API_BASE_URL + "rest/";
+ private const string FLICKR_GET_INFO_URL = FLICKR_REST_URL + "?method=flickr.photos.getInfo";
+
+ ///
+ /// Do the actual upload to Flickr
+ /// For more details on the available parameters, see: http://flickrnet.codeplex.com
+ ///
+ ///
+ ///
+ ///
+ ///
+ /// url to image
+ public static string UploadToFlickr(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename)
+ {
+ var oAuth = new OAuthSession(FlickrCredentials.ConsumerKey, FlickrCredentials.ConsumerSecret)
+ {
+ BrowserSize = new Size(520, 800),
+ CheckVerifier = false,
+ AccessTokenUrl = FLICKR_ACCESS_TOKEN_URL,
+ AuthorizeUrl = FLICKR_AUTHORIZE_URL,
+ RequestTokenUrl = FLICKR_REQUEST_TOKEN_URL,
+ LoginTitle = "Flickr authorization",
+ Token = config.FlickrToken,
+ TokenSecret = config.FlickrTokenSecret
+ };
+ if (string.IsNullOrEmpty(oAuth.Token))
+ {
+ if (!oAuth.Authorize())
+ {
+ return null;
+ }
+
+ if (!string.IsNullOrEmpty(oAuth.Token))
+ {
+ config.FlickrToken = oAuth.Token;
+ }
+
+ if (!string.IsNullOrEmpty(oAuth.TokenSecret))
+ {
+ config.FlickrTokenSecret = oAuth.TokenSecret;
+ }
+
+ IniConfig.Save();
+ }
+
+ try
+ {
+ IDictionary signedParameters = new Dictionary
+ {
+ {
+ "content_type", "2"
+ }, // Screenshot
+ {
+ "tags", "Greenshot"
+ },
+ {
+ "is_public", config.IsPublic ? "1" : "0"
+ },
+ {
+ "is_friend", config.IsFriend ? "1" : "0"
+ },
+ {
+ "is_family", config.IsFamily ? "1" : "0"
+ },
+ {
+ "safety_level", $"{(int) config.SafetyLevel}"
+ },
+ {
+ "hidden", config.HiddenFromSearch ? "1" : "2"
+ }
+ };
+ IDictionary otherParameters = new Dictionary
+ {
+ {
+ "photo", new SurfaceContainer(surfaceToUpload, outputSettings, filename)
+ }
+ };
+ string response = oAuth.MakeOAuthRequest(HTTPMethod.POST, FLICKR_UPLOAD_URL, signedParameters, otherParameters, null);
+ string photoId = GetPhotoId(response);
+
+ // Get Photo Info
+ signedParameters = new Dictionary
+ {
+ {
+ "photo_id", photoId
+ }
+ };
+ string photoInfo = oAuth.MakeOAuthRequest(HTTPMethod.POST, FLICKR_GET_INFO_URL, signedParameters, null, null);
+ return GetUrl(photoInfo);
+ }
+ catch (Exception ex)
+ {
+ LOG.Error("Upload error: ", ex);
+ throw;
+ }
+ finally
+ {
+ if (!string.IsNullOrEmpty(oAuth.Token))
+ {
+ config.FlickrToken = oAuth.Token;
+ }
+
+ if (!string.IsNullOrEmpty(oAuth.TokenSecret))
+ {
+ config.FlickrTokenSecret = oAuth.TokenSecret;
+ }
+ }
+ }
+
+ private static string GetUrl(string response)
+ {
+ try
+ {
+ XmlDocument doc = new XmlDocument();
+ doc.LoadXml(response);
+ if (config.UsePageLink)
+ {
+ XmlNodeList nodes = doc.GetElementsByTagName("url");
+ if (nodes.Count > 0)
+ {
+ var xmlNode = nodes.Item(0);
+ if (xmlNode != null)
+ {
+ return xmlNode.InnerText;
+ }
+ }
+ }
+ else
+ {
+ XmlNodeList nodes = doc.GetElementsByTagName("photo");
+ if (nodes.Count > 0)
+ {
+ var item = nodes.Item(0);
+ if (item?.Attributes != null)
+ {
+ string farmId = item.Attributes["farm"].Value;
+ string serverId = item.Attributes["server"].Value;
+ string photoId = item.Attributes["id"].Value;
+ string originalsecret = item.Attributes["originalsecret"].Value;
+ string originalFormat = item.Attributes["originalformat"].Value;
+ return string.Format(FLICKR_FARM_URL, farmId, serverId, photoId, originalsecret, originalFormat);
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ LOG.Error("Error parsing Flickr Response.", ex);
+ }
+
+ return null;
+ }
+
+ private static string GetPhotoId(string response)
+ {
+ try
+ {
+ XmlDocument doc = new XmlDocument();
+ doc.LoadXml(response);
+ XmlNodeList nodes = doc.GetElementsByTagName("photoid");
+ if (nodes.Count > 0)
+ {
+ var xmlNode = nodes.Item(0);
+ if (xmlNode != null)
+ {
+ return xmlNode.InnerText;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ LOG.Error("Error parsing Flickr Response.", ex);
+ }
+
+ return null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Flickr/Forms/FlickrForm.cs b/src/Greenshot.Plugin.Flickr/Forms/FlickrForm.cs
index 74e032708..0c8f4130e 100644
--- a/src/Greenshot.Plugin.Flickr/Forms/FlickrForm.cs
+++ b/src/Greenshot.Plugin.Flickr/Forms/FlickrForm.cs
@@ -21,7 +21,9 @@
using GreenshotPlugin.Controls;
-namespace Greenshot.Plugin.Flickr.Forms {
- public class FlickrForm : GreenshotForm {
- }
+namespace Greenshot.Plugin.Flickr.Forms
+{
+ public class FlickrForm : GreenshotForm
+ {
+ }
}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Flickr/Forms/SettingsForm.cs b/src/Greenshot.Plugin.Flickr/Forms/SettingsForm.cs
index eba638160..332f28664 100644
--- a/src/Greenshot.Plugin.Flickr/Forms/SettingsForm.cs
+++ b/src/Greenshot.Plugin.Flickr/Forms/SettingsForm.cs
@@ -19,19 +19,21 @@
* along with this program. If not, see .
*/
-namespace Greenshot.Plugin.Flickr.Forms {
- ///
- /// Description of PasswordRequestForm.
- ///
- public partial class SettingsForm : FlickrForm {
- public SettingsForm() {
- //
- // The InitializeComponent() call is required for Windows Forms designer support.
- //
- InitializeComponent();
- CancelButton = buttonCancel;
- AcceptButton = buttonOK;
- }
-
- }
-}
+namespace Greenshot.Plugin.Flickr.Forms
+{
+ ///
+ /// Description of PasswordRequestForm.
+ ///
+ public partial class SettingsForm : FlickrForm
+ {
+ public SettingsForm()
+ {
+ //
+ // The InitializeComponent() call is required for Windows Forms designer support.
+ //
+ InitializeComponent();
+ CancelButton = buttonCancel;
+ AcceptButton = buttonOK;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Flickr/LanguageKeys.cs b/src/Greenshot.Plugin.Flickr/LanguageKeys.cs
index d347faa0a..da634aabe 100644
--- a/src/Greenshot.Plugin.Flickr/LanguageKeys.cs
+++ b/src/Greenshot.Plugin.Flickr/LanguageKeys.cs
@@ -18,11 +18,14 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
-namespace Greenshot.Plugin.Flickr {
- public enum LangKey {
- upload_menu_item,
- upload_failure,
- communication_wait,
- Configure
+
+namespace Greenshot.Plugin.Flickr
+{
+ public enum LangKey
+ {
+ upload_menu_item,
+ upload_failure,
+ communication_wait,
+ Configure
}
-}
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Flickr/Properties/AssemblyInfo.cs b/src/Greenshot.Plugin.Flickr/Properties/AssemblyInfo.cs
index 7cc8b4a3a..84938a6ab 100644
--- a/src/Greenshot.Plugin.Flickr/Properties/AssemblyInfo.cs
+++ b/src/Greenshot.Plugin.Flickr/Properties/AssemblyInfo.cs
@@ -29,4 +29,4 @@ using System.Runtime.InteropServices;
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
-[assembly: ComVisible(false)]
+[assembly: ComVisible(false)]
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.GooglePhotos/Forms/GooglePhotosForm.cs b/src/Greenshot.Plugin.GooglePhotos/Forms/GooglePhotosForm.cs
index 1b3c76816..616398591 100644
--- a/src/Greenshot.Plugin.GooglePhotos/Forms/GooglePhotosForm.cs
+++ b/src/Greenshot.Plugin.GooglePhotos/Forms/GooglePhotosForm.cs
@@ -20,7 +20,9 @@
using GreenshotPlugin.Controls;
-namespace Greenshot.Plugin.GooglePhotos.Forms {
- public class GooglePhotosForm : GreenshotForm {
- }
-}
+namespace Greenshot.Plugin.GooglePhotos.Forms
+{
+ public class GooglePhotosForm : GreenshotForm
+ {
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.GooglePhotos/Forms/SettingsForm.cs b/src/Greenshot.Plugin.GooglePhotos/Forms/SettingsForm.cs
index 3946baf1b..6029212f9 100644
--- a/src/Greenshot.Plugin.GooglePhotos/Forms/SettingsForm.cs
+++ b/src/Greenshot.Plugin.GooglePhotos/Forms/SettingsForm.cs
@@ -18,21 +18,21 @@
* along with this program. If not, see .
*/
-namespace Greenshot.Plugin.GooglePhotos.Forms {
- ///
- /// Description of PasswordRequestForm.
- ///
- public partial class SettingsForm : GooglePhotosForm {
-
- public SettingsForm()
- {
- //
- // The InitializeComponent() call is required for Windows Forms designer support.
- //
- InitializeComponent();
- CancelButton = buttonCancel;
- AcceptButton = buttonOK;
- }
-
- }
-}
+namespace Greenshot.Plugin.GooglePhotos.Forms
+{
+ ///
+ /// Description of PasswordRequestForm.
+ ///
+ public partial class SettingsForm : GooglePhotosForm
+ {
+ public SettingsForm()
+ {
+ //
+ // The InitializeComponent() call is required for Windows Forms designer support.
+ //
+ InitializeComponent();
+ CancelButton = buttonCancel;
+ AcceptButton = buttonOK;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosConfiguration.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosConfiguration.cs
index d11d797d1..411cf6ba9 100644
--- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosConfiguration.cs
+++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosConfiguration.cs
@@ -24,71 +24,58 @@ using Greenshot.Plugin.GooglePhotos.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.GooglePhotos {
- ///
- /// Description of GooglePhotosConfiguration.
- ///
- [IniSection("GooglePhotos", Description = "Greenshot GooglePhotos Plugin configuration")]
- public class GooglePhotosConfiguration : IniSection {
- [IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
- public OutputFormat UploadFormat { get; set; }
+namespace Greenshot.Plugin.GooglePhotos
+{
+ ///
+ /// Description of GooglePhotosConfiguration.
+ ///
+ [IniSection("GooglePhotos", Description = "Greenshot GooglePhotos Plugin configuration")]
+ public class GooglePhotosConfiguration : IniSection
+ {
+ [IniProperty("UploadFormat", Description = "What file type to use for uploading", DefaultValue = "png")]
+ public OutputFormat UploadFormat { get; set; }
- [IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]
- public int UploadJpegQuality { get; set; }
+ [IniProperty("UploadJpegQuality", Description = "JPEG file save quality in %.", DefaultValue = "80")]
+ public int UploadJpegQuality { get; set; }
- [IniProperty("AfterUploadLinkToClipBoard", Description = "After upload send GooglePhotos link to clipboard.", DefaultValue = "true")]
- public bool AfterUploadLinkToClipBoard { get; set; }
- [IniProperty("AddFilename", Description = "Is the filename passed on to GooglePhotos", DefaultValue = "False")]
- public bool AddFilename {
- get;
- set;
- }
+ [IniProperty("AfterUploadLinkToClipBoard", Description = "After upload send GooglePhotos link to clipboard.", DefaultValue = "true")]
+ public bool AfterUploadLinkToClipBoard { get; set; }
- [IniProperty("UploadUser", Description = "The GooglePhotos user to upload to", DefaultValue = "default")]
- public string UploadUser {
- get;
- set;
- }
+ [IniProperty("AddFilename", Description = "Is the filename passed on to GooglePhotos", DefaultValue = "False")]
+ public bool AddFilename { get; set; }
- [IniProperty("UploadAlbum", Description = "The GooglePhotos album to upload to", DefaultValue = "default")]
- public string UploadAlbum {
- get;
- set;
- }
+ [IniProperty("UploadUser", Description = "The GooglePhotos user to upload to", DefaultValue = "default")]
+ public string UploadUser { get; set; }
- [IniProperty("RefreshToken", Description = "GooglePhotos authorization refresh Token", Encrypted = true)]
- public string RefreshToken {
- get;
- set;
- }
+ [IniProperty("UploadAlbum", Description = "The GooglePhotos album to upload to", DefaultValue = "default")]
+ public string UploadAlbum { get; set; }
- ///
- /// Not stored
- ///
- public string AccessToken {
- get;
- set;
- }
+ [IniProperty("RefreshToken", Description = "GooglePhotos authorization refresh Token", Encrypted = true)]
+ public string RefreshToken { get; set; }
- ///
- /// Not stored
- ///
- public DateTimeOffset AccessTokenExpires {
- get;
- set;
- }
+ ///
+ /// Not stored
+ ///
+ public string AccessToken { get; set; }
- ///
- /// A form for token
- ///
- /// bool true if OK was pressed, false if cancel
- public bool ShowConfigDialog() {
- DialogResult result = new SettingsForm().ShowDialog();
- if (result == DialogResult.OK) {
- return true;
- }
- return false;
- }
+ ///
+ /// Not stored
+ ///
+ public DateTimeOffset AccessTokenExpires { get; set; }
- }
-}
+ ///
+ /// A form for token
+ ///
+ /// bool true if OK was pressed, false if cancel
+ public bool ShowConfigDialog()
+ {
+ DialogResult result = new SettingsForm().ShowDialog();
+ if (result == DialogResult.OK)
+ {
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs
index 2948773ce..8a66faef7 100644
--- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs
+++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs
@@ -23,33 +23,42 @@ using System.Drawing;
using GreenshotPlugin.Core;
using GreenshotPlugin.Interfaces;
-namespace Greenshot.Plugin.GooglePhotos {
- public class GooglePhotosDestination : AbstractDestination {
- private readonly GooglePhotosPlugin _plugin;
- public GooglePhotosDestination(GooglePhotosPlugin plugin) {
- _plugin = plugin;
- }
-
- public override string Designation => "GooglePhotos";
+namespace Greenshot.Plugin.GooglePhotos
+{
+ public class GooglePhotosDestination : AbstractDestination
+ {
+ private readonly GooglePhotosPlugin _plugin;
- public override string Description => Language.GetString("googlephotos", LangKey.upload_menu_item);
+ public GooglePhotosDestination(GooglePhotosPlugin plugin)
+ {
+ _plugin = plugin;
+ }
- public override Image DisplayIcon {
- get {
- ComponentResourceManager resources = new ComponentResourceManager(typeof(GooglePhotosPlugin));
- return (Image)resources.GetObject("GooglePhotos");
- }
- }
+ public override string Designation => "GooglePhotos";
- public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
- ExportInformation exportInformation = new ExportInformation(Designation, Description);
+ public override string Description => Language.GetString("googlephotos", LangKey.upload_menu_item);
+
+ public override Image DisplayIcon
+ {
+ get
+ {
+ ComponentResourceManager resources = new ComponentResourceManager(typeof(GooglePhotosPlugin));
+ return (Image) resources.GetObject("GooglePhotos");
+ }
+ }
+
+ public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
+ {
+ ExportInformation exportInformation = new ExportInformation(Designation, Description);
bool uploaded = _plugin.Upload(captureDetails, surface, out var uploadUrl);
- if (uploaded) {
- exportInformation.ExportMade = true;
- exportInformation.Uri = uploadUrl;
- }
- ProcessExport(exportInformation, surface);
- return exportInformation;
- }
- }
-}
+ if (uploaded)
+ {
+ exportInformation.ExportMade = true;
+ exportInformation.Uri = uploadUrl;
+ }
+
+ ProcessExport(exportInformation, surface);
+ return exportInformation;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs
index ed1727c05..91978b8ef 100644
--- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs
+++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs
@@ -29,97 +29,113 @@ using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
-namespace Greenshot.Plugin.GooglePhotos {
- ///
- /// This is the GooglePhotos base code
- ///
- [Plugin("GooglePhotos", true)]
- public class GooglePhotosPlugin : IGreenshotPlugin {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(GooglePhotosPlugin));
- private static GooglePhotosConfiguration _config;
- private ComponentResourceManager _resources;
- private ToolStripMenuItem _itemPlugInRoot;
+namespace Greenshot.Plugin.GooglePhotos
+{
+ ///
+ /// This is the GooglePhotos base code
+ ///
+ [Plugin("GooglePhotos", true)]
+ public class GooglePhotosPlugin : IGreenshotPlugin
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(GooglePhotosPlugin));
+ private static GooglePhotosConfiguration _config;
+ private ComponentResourceManager _resources;
+ private ToolStripMenuItem _itemPlugInRoot;
- public void Dispose() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- private void Dispose(bool disposing)
- {
- if (!disposing) return;
- if (_itemPlugInRoot == null) return;
- _itemPlugInRoot.Dispose();
- _itemPlugInRoot = null;
- }
+ private void Dispose(bool disposing)
+ {
+ if (!disposing) return;
+ if (_itemPlugInRoot == null) return;
+ _itemPlugInRoot.Dispose();
+ _itemPlugInRoot = null;
+ }
- ///
- /// Implementation of the IGreenshotPlugin.Initialize
- ///
- public bool Initialize() {
- SimpleServiceProvider.Current.AddService(new GooglePhotosDestination(this));
+ ///
+ /// Implementation of the IGreenshotPlugin.Initialize
+ ///
+ public bool Initialize()
+ {
+ SimpleServiceProvider.Current.AddService(new GooglePhotosDestination(this));
- // Get configuration
- _config = IniConfig.GetIniSection();
- _resources = new ComponentResourceManager(typeof(GooglePhotosPlugin));
+ // Get configuration
+ _config = IniConfig.GetIniSection();
+ _resources = new ComponentResourceManager(typeof(GooglePhotosPlugin));
- _itemPlugInRoot = new ToolStripMenuItem
- {
- Text = Language.GetString("googlephotos", LangKey.Configure),
- Image = (Image) _resources.GetObject("GooglePhotos")
- };
- _itemPlugInRoot.Click += ConfigMenuClick;
- PluginUtils.AddToContextMenu(_itemPlugInRoot);
- Language.LanguageChanged += OnLanguageChanged;
- return true;
- }
+ _itemPlugInRoot = new ToolStripMenuItem
+ {
+ Text = Language.GetString("googlephotos", LangKey.Configure),
+ Image = (Image) _resources.GetObject("GooglePhotos")
+ };
+ _itemPlugInRoot.Click += ConfigMenuClick;
+ PluginUtils.AddToContextMenu(_itemPlugInRoot);
+ Language.LanguageChanged += OnLanguageChanged;
+ return true;
+ }
- public void OnLanguageChanged(object sender, EventArgs e) {
- if (_itemPlugInRoot != null) {
- _itemPlugInRoot.Text = Language.GetString("googlephotos", LangKey.Configure);
- }
- }
+ public void OnLanguageChanged(object sender, EventArgs e)
+ {
+ if (_itemPlugInRoot != null)
+ {
+ _itemPlugInRoot.Text = Language.GetString("googlephotos", LangKey.Configure);
+ }
+ }
- public void Shutdown() {
- Log.Debug("GooglePhotos Plugin shutdown.");
- Language.LanguageChanged -= OnLanguageChanged;
- //host.OnImageEditorOpen -= new OnImageEditorOpenHandler(ImageEditorOpened);
- }
+ public void Shutdown()
+ {
+ Log.Debug("GooglePhotos Plugin shutdown.");
+ Language.LanguageChanged -= OnLanguageChanged;
+ //host.OnImageEditorOpen -= new OnImageEditorOpenHandler(ImageEditorOpened);
+ }
- ///
- /// Implementation of the IPlugin.Configure
- ///
- public void Configure() {
- _config.ShowConfigDialog();
- }
+ ///
+ /// Implementation of the IPlugin.Configure
+ ///
+ public void Configure()
+ {
+ _config.ShowConfigDialog();
+ }
- public void ConfigMenuClick(object sender, EventArgs eventArgs) {
- Configure();
- }
+ public void ConfigMenuClick(object sender, EventArgs eventArgs)
+ {
+ Configure();
+ }
- public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) {
- SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality);
- try {
- string url = null;
- new PleaseWaitForm().ShowAndWait("GooglePhotos", Language.GetString("googlephotos", LangKey.communication_wait),
- delegate
- {
- string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails));
- url = GooglePhotosUtils.UploadToGooglePhotos(surfaceToUpload, outputSettings, captureDetails.Title, filename);
- }
- );
- uploadUrl = url;
+ public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl)
+ {
+ SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality);
+ try
+ {
+ string url = null;
+ new PleaseWaitForm().ShowAndWait("GooglePhotos", Language.GetString("googlephotos", LangKey.communication_wait),
+ delegate
+ {
+ string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails));
+ url = GooglePhotosUtils.UploadToGooglePhotos(surfaceToUpload, outputSettings, captureDetails.Title, filename);
+ }
+ );
+ uploadUrl = url;
- if (uploadUrl != null && _config.AfterUploadLinkToClipBoard) {
- ClipboardHelper.SetClipboardData(uploadUrl);
- }
- return true;
- } catch (Exception e) {
- Log.Error("Error uploading.", e);
- MessageBox.Show(Language.GetString("googlephotos", LangKey.upload_failure) + " " + e.Message);
- }
- uploadUrl = null;
- return false;
- }
- }
-}
+ if (uploadUrl != null && _config.AfterUploadLinkToClipBoard)
+ {
+ ClipboardHelper.SetClipboardData(uploadUrl);
+ }
+
+ return true;
+ }
+ catch (Exception e)
+ {
+ Log.Error("Error uploading.", e);
+ MessageBox.Show(Language.GetString("googlephotos", LangKey.upload_failure) + " " + e.Message);
+ }
+
+ uploadUrl = null;
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosUtils.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosUtils.cs
index a11edf090..2b4638839 100644
--- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosUtils.cs
+++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosUtils.cs
@@ -26,95 +26,118 @@ using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
-namespace Greenshot.Plugin.GooglePhotos {
- ///
- /// Description of GooglePhotosUtils.
- ///
- public static class GooglePhotosUtils {
- private const string GooglePhotosScope = "https://picasaweb.google.com/data/";
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(GooglePhotosUtils));
- private static readonly GooglePhotosConfiguration Config = IniConfig.GetIniSection();
- private const string AuthUrl = "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={ClientId}&redirect_uri={RedirectUrl}&state={State}&scope=" + GooglePhotosScope;
- private const string TokenUrl = "https://www.googleapis.com/oauth2/v3/token";
- private const string UploadUrl = "https://picasaweb.google.com/data/feed/api/user/{0}/albumid/{1}";
+namespace Greenshot.Plugin.GooglePhotos
+{
+ ///
+ /// Description of GooglePhotosUtils.
+ ///
+ public static class GooglePhotosUtils
+ {
+ private const string GooglePhotosScope = "https://picasaweb.google.com/data/";
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(GooglePhotosUtils));
+ private static readonly GooglePhotosConfiguration Config = IniConfig.GetIniSection();
- ///
- /// Do the actual upload to GooglePhotos
- ///
- /// Image to upload
- /// SurfaceOutputSettings
- /// string
- /// string
- /// GooglePhotosResponse
- public static string UploadToGooglePhotos(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename) {
- // Fill the OAuth2Settings
- var settings = new OAuth2Settings
- {
- AuthUrlPattern = AuthUrl,
- TokenUrl = TokenUrl,
- CloudServiceName = "GooglePhotos",
- ClientId = GooglePhotosCredentials.ClientId,
- ClientSecret = GooglePhotosCredentials.ClientSecret,
- AuthorizeMode = OAuth2AuthorizeMode.JsonReceiver,
- RefreshToken = Config.RefreshToken,
- AccessToken = Config.AccessToken,
- AccessTokenExpires = Config.AccessTokenExpires
- };
+ private const string AuthUrl = "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={ClientId}&redirect_uri={RedirectUrl}&state={State}&scope=" +
+ GooglePhotosScope;
- // Copy the settings from the config, which is kept in memory and on the disk
+ private const string TokenUrl = "https://www.googleapis.com/oauth2/v3/token";
+ private const string UploadUrl = "https://picasaweb.google.com/data/feed/api/user/{0}/albumid/{1}";
- try {
- var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, string.Format(UploadUrl, Config.UploadUser, Config.UploadAlbum), settings);
- if (Config.AddFilename) {
- webRequest.Headers.Add("Slug", NetworkHelper.EscapeDataString(filename));
- }
- SurfaceContainer container = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
- container.Upload(webRequest);
-
- string response = NetworkHelper.GetResponseAsString(webRequest);
+ ///
+ /// Do the actual upload to GooglePhotos
+ ///
+ /// Image to upload
+ /// SurfaceOutputSettings
+ /// string
+ /// string
+ /// GooglePhotosResponse
+ public static string UploadToGooglePhotos(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename)
+ {
+ // Fill the OAuth2Settings
+ var settings = new OAuth2Settings
+ {
+ AuthUrlPattern = AuthUrl,
+ TokenUrl = TokenUrl,
+ CloudServiceName = "GooglePhotos",
+ ClientId = GooglePhotosCredentials.ClientId,
+ ClientSecret = GooglePhotosCredentials.ClientSecret,
+ AuthorizeMode = OAuth2AuthorizeMode.JsonReceiver,
+ RefreshToken = Config.RefreshToken,
+ AccessToken = Config.AccessToken,
+ AccessTokenExpires = Config.AccessTokenExpires
+ };
- return ParseResponse(response);
- } finally {
- // Copy the settings back to the config, so they are stored.
- Config.RefreshToken = settings.RefreshToken;
- Config.AccessToken = settings.AccessToken;
- Config.AccessTokenExpires = settings.AccessTokenExpires;
- Config.IsDirty = true;
- IniConfig.Save();
- }
- }
-
- ///
- /// Parse the upload URL from the response
- ///
- ///
- ///
- public static string ParseResponse(string response) {
- if (response == null) {
- return null;
- }
- try {
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(response);
- XmlNodeList nodes = doc.GetElementsByTagName("link", "*");
- if(nodes.Count > 0) {
- string url = null;
- foreach(XmlNode node in nodes) {
- if (node.Attributes != null) {
- url = node.Attributes["href"].Value;
- string rel = node.Attributes["rel"].Value;
- // Pictures with rel="http://schemas.google.com/photos/2007#canonical" are the direct link
- if (rel != null && rel.EndsWith("canonical")) {
- break;
- }
- }
- }
- return url;
- }
- } catch(Exception e) {
- Log.ErrorFormat("Could not parse GooglePhotos response due to error {0}, response was: {1}", e.Message, response);
- }
- return null;
- }
- }
-}
+ // Copy the settings from the config, which is kept in memory and on the disk
+
+ try
+ {
+ var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, string.Format(UploadUrl, Config.UploadUser, Config.UploadAlbum), settings);
+ if (Config.AddFilename)
+ {
+ webRequest.Headers.Add("Slug", NetworkHelper.EscapeDataString(filename));
+ }
+
+ SurfaceContainer container = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
+ container.Upload(webRequest);
+
+ string response = NetworkHelper.GetResponseAsString(webRequest);
+
+ return ParseResponse(response);
+ }
+ finally
+ {
+ // Copy the settings back to the config, so they are stored.
+ Config.RefreshToken = settings.RefreshToken;
+ Config.AccessToken = settings.AccessToken;
+ Config.AccessTokenExpires = settings.AccessTokenExpires;
+ Config.IsDirty = true;
+ IniConfig.Save();
+ }
+ }
+
+ ///
+ /// Parse the upload URL from the response
+ ///
+ ///
+ ///
+ public static string ParseResponse(string response)
+ {
+ if (response == null)
+ {
+ return null;
+ }
+
+ try
+ {
+ XmlDocument doc = new XmlDocument();
+ doc.LoadXml(response);
+ XmlNodeList nodes = doc.GetElementsByTagName("link", "*");
+ if (nodes.Count > 0)
+ {
+ string url = null;
+ foreach (XmlNode node in nodes)
+ {
+ if (node.Attributes != null)
+ {
+ url = node.Attributes["href"].Value;
+ string rel = node.Attributes["rel"].Value;
+ // Pictures with rel="http://schemas.google.com/photos/2007#canonical" are the direct link
+ if (rel != null && rel.EndsWith("canonical"))
+ {
+ break;
+ }
+ }
+ }
+
+ return url;
+ }
+ }
+ catch (Exception e)
+ {
+ Log.ErrorFormat("Could not parse GooglePhotos response due to error {0}, response was: {1}", e.Message, response);
+ }
+
+ return null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.GooglePhotos/LanguageKeys.cs b/src/Greenshot.Plugin.GooglePhotos/LanguageKeys.cs
index 34feda885..7eaab1020 100644
--- a/src/Greenshot.Plugin.GooglePhotos/LanguageKeys.cs
+++ b/src/Greenshot.Plugin.GooglePhotos/LanguageKeys.cs
@@ -18,12 +18,13 @@
* along with this program. If not, see .
*/
-namespace Greenshot.Plugin.GooglePhotos {
- public enum LangKey
- {
- upload_menu_item,
- upload_failure,
- communication_wait,
- Configure
- }
-}
+namespace Greenshot.Plugin.GooglePhotos
+{
+ public enum LangKey
+ {
+ upload_menu_item,
+ upload_failure,
+ communication_wait,
+ Configure
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.GooglePhotos/Properties/AssemblyInfo.cs b/src/Greenshot.Plugin.GooglePhotos/Properties/AssemblyInfo.cs
index d4fa2878a..d04662538 100644
--- a/src/Greenshot.Plugin.GooglePhotos/Properties/AssemblyInfo.cs
+++ b/src/Greenshot.Plugin.GooglePhotos/Properties/AssemblyInfo.cs
@@ -29,4 +29,4 @@ using System.Runtime.InteropServices;
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
-[assembly: ComVisible(false)]
+[assembly: ComVisible(false)]
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Imgur/Forms/ImgurForm.cs b/src/Greenshot.Plugin.Imgur/Forms/ImgurForm.cs
index c4fb88791..c94f6d1eb 100644
--- a/src/Greenshot.Plugin.Imgur/Forms/ImgurForm.cs
+++ b/src/Greenshot.Plugin.Imgur/Forms/ImgurForm.cs
@@ -21,10 +21,12 @@
using GreenshotPlugin.Controls;
-namespace Greenshot.Plugin.Imgur.Forms {
- ///
- /// This class is needed for design-time resolving of the language files
- ///
- public class ImgurForm : GreenshotForm {
- }
-}
+namespace Greenshot.Plugin.Imgur.Forms
+{
+ ///
+ /// This class is needed for design-time resolving of the language files
+ ///
+ public class ImgurForm : GreenshotForm
+ {
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs
index 3b2efcd48..417f5e7d5 100644
--- a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs
+++ b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs
@@ -27,195 +27,237 @@ using GreenshotPlugin.Controls;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.Imgur.Forms {
- ///
- /// Imgur history form
- ///
- public sealed partial class ImgurHistory : ImgurForm {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurHistory));
- private readonly GreenshotColumnSorter _columnSorter;
- private static readonly object Lock = new object();
- private static readonly ImgurConfiguration Config = IniConfig.GetIniSection();
- private static ImgurHistory _instance;
-
- public static void ShowHistory() {
- lock (Lock)
- {
- if (ImgurUtils.IsHistoryLoadingNeeded())
- {
- // Run upload in the background
- new PleaseWaitForm().ShowAndWait("Imgur " + Language.GetString("imgur", LangKey.history), Language.GetString("imgur", LangKey.communication_wait),
- ImgurUtils.LoadHistory
- );
- }
+namespace Greenshot.Plugin.Imgur.Forms
+{
+ ///
+ /// Imgur history form
+ ///
+ public sealed partial class ImgurHistory : ImgurForm
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurHistory));
+ private readonly GreenshotColumnSorter _columnSorter;
+ private static readonly object Lock = new object();
+ private static readonly ImgurConfiguration Config = IniConfig.GetIniSection();
+ private static ImgurHistory _instance;
- // Make sure the history is loaded, will be done only once
- if (_instance == null)
- {
- _instance = new ImgurHistory();
- }
- if (!_instance.Visible)
- {
- _instance.Show();
- }
- _instance.Redraw();
- }
- }
-
- private ImgurHistory() {
- ManualLanguageApply = true;
- //
- // The InitializeComponent() call is required for Windows Forms designer support.
- //
- InitializeComponent();
- AcceptButton = finishedButton;
- CancelButton = finishedButton;
- // Init sorting
- _columnSorter = new GreenshotColumnSorter();
- listview_imgur_uploads.ListViewItemSorter = _columnSorter;
- _columnSorter.SortColumn = 3;
- _columnSorter.Order = SortOrder.Descending;
- Redraw();
- if (listview_imgur_uploads.Items.Count > 0) {
- listview_imgur_uploads.Items[0].Selected = true;
- }
- ApplyLanguage();
- if (Config.Credits > 0) {
- Text = Text + " (" + Config.Credits + " credits)";
- }
- }
+ public static void ShowHistory()
+ {
+ lock (Lock)
+ {
+ if (ImgurUtils.IsHistoryLoadingNeeded())
+ {
+ // Run upload in the background
+ new PleaseWaitForm().ShowAndWait("Imgur " + Language.GetString("imgur", LangKey.history), Language.GetString("imgur", LangKey.communication_wait),
+ ImgurUtils.LoadHistory
+ );
+ }
- private void Redraw() {
- // Should fix Bug #3378699
- pictureBox1.Image = pictureBox1.ErrorImage;
- listview_imgur_uploads.BeginUpdate();
- listview_imgur_uploads.Items.Clear();
- listview_imgur_uploads.Columns.Clear();
- string[] columns = { "hash", "title", "deleteHash", "Date"};
- foreach (string column in columns) {
- listview_imgur_uploads.Columns.Add(column);
- }
- foreach (ImgurInfo imgurInfo in Config.runtimeImgurHistory.Values) {
- var item = new ListViewItem(imgurInfo.Hash)
- {
- Tag = imgurInfo
- };
- item.SubItems.Add(imgurInfo.Title);
- item.SubItems.Add(imgurInfo.DeleteHash);
- item.SubItems.Add(imgurInfo.Timestamp.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo));
- listview_imgur_uploads.Items.Add(item);
- }
- for (int i = 0; i < columns.Length; i++) {
- listview_imgur_uploads.AutoResizeColumn(i, ColumnHeaderAutoResizeStyle.ColumnContent);
- }
-
- listview_imgur_uploads.EndUpdate();
- listview_imgur_uploads.Refresh();
- deleteButton.Enabled = false;
- openButton.Enabled = false;
- clipboardButton.Enabled = false;
- }
+ // Make sure the history is loaded, will be done only once
+ if (_instance == null)
+ {
+ _instance = new ImgurHistory();
+ }
- private void Listview_imgur_uploadsSelectedIndexChanged(object sender, EventArgs e) {
- pictureBox1.Image = pictureBox1.ErrorImage;
- if (listview_imgur_uploads.SelectedItems.Count > 0) {
- deleteButton.Enabled = true;
- openButton.Enabled = true;
- clipboardButton.Enabled = true;
- if (listview_imgur_uploads.SelectedItems.Count == 1) {
- ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[0].Tag;
- pictureBox1.Image = imgurInfo.Image;
- }
- } else {
- pictureBox1.Image = pictureBox1.ErrorImage;
- deleteButton.Enabled = false;
- openButton.Enabled = false;
- clipboardButton.Enabled = false;
- }
- }
+ if (!_instance.Visible)
+ {
+ _instance.Show();
+ }
- private void DeleteButtonClick(object sender, EventArgs e) {
- if (listview_imgur_uploads.SelectedItems.Count > 0) {
- for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) {
- ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag;
- 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)
- {
- continue;
- }
- // Should fix Bug #3378699
- pictureBox1.Image = pictureBox1.ErrorImage;
- try {
- new PleaseWaitForm().ShowAndWait("Imgur", Language.GetString("imgur", LangKey.communication_wait),
- delegate {
- ImgurUtils.DeleteImgurImage(imgurInfo);
- }
- );
- } catch (Exception ex) {
- Log.Warn("Problem communicating with Imgur: ", ex);
- }
+ _instance.Redraw();
+ }
+ }
- imgurInfo.Dispose();
- }
- }
- Redraw();
- }
+ private ImgurHistory()
+ {
+ ManualLanguageApply = true;
+ //
+ // The InitializeComponent() call is required for Windows Forms designer support.
+ //
+ InitializeComponent();
+ AcceptButton = finishedButton;
+ CancelButton = finishedButton;
+ // Init sorting
+ _columnSorter = new GreenshotColumnSorter();
+ listview_imgur_uploads.ListViewItemSorter = _columnSorter;
+ _columnSorter.SortColumn = 3;
+ _columnSorter.Order = SortOrder.Descending;
+ Redraw();
+ if (listview_imgur_uploads.Items.Count > 0)
+ {
+ listview_imgur_uploads.Items[0].Selected = true;
+ }
- private void ClipboardButtonClick(object sender, EventArgs e) {
- StringBuilder links = new StringBuilder();
- if (listview_imgur_uploads.SelectedItems.Count > 0) {
- for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++)
- {
- ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag;
- links.AppendLine(Config.UsePageLink ? imgurInfo.Page : imgurInfo.Original);
- }
- }
- ClipboardHelper.SetClipboardData(links.ToString());
- }
+ ApplyLanguage();
+ if (Config.Credits > 0)
+ {
+ Text = Text + " (" + Config.Credits + " credits)";
+ }
+ }
- private void ClearHistoryButtonClick(object sender, EventArgs e) {
- DialogResult result = MessageBox.Show(Language.GetString("imgur", LangKey.clear_question), "Imgur", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
- if (result == DialogResult.Yes) {
- Config.runtimeImgurHistory.Clear();
- Config.ImgurUploadHistory.Clear();
- IniConfig.Save();
- Redraw();
- }
- }
+ private void Redraw()
+ {
+ // Should fix Bug #3378699
+ pictureBox1.Image = pictureBox1.ErrorImage;
+ listview_imgur_uploads.BeginUpdate();
+ listview_imgur_uploads.Items.Clear();
+ listview_imgur_uploads.Columns.Clear();
+ string[] columns =
+ {
+ "hash", "title", "deleteHash", "Date"
+ };
+ foreach (string column in columns)
+ {
+ listview_imgur_uploads.Columns.Add(column);
+ }
- private void FinishedButtonClick(object sender, EventArgs e)
- {
- Hide();
- }
+ foreach (ImgurInfo imgurInfo in Config.runtimeImgurHistory.Values)
+ {
+ var item = new ListViewItem(imgurInfo.Hash)
+ {
+ Tag = imgurInfo
+ };
+ item.SubItems.Add(imgurInfo.Title);
+ item.SubItems.Add(imgurInfo.DeleteHash);
+ item.SubItems.Add(imgurInfo.Timestamp.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo));
+ listview_imgur_uploads.Items.Add(item);
+ }
- private void OpenButtonClick(object sender, EventArgs e) {
- if (listview_imgur_uploads.SelectedItems.Count > 0) {
- for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) {
- ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag;
- System.Diagnostics.Process.Start(imgurInfo.Page);
- }
- }
- }
-
- private void listview_imgur_uploads_ColumnClick(object sender, ColumnClickEventArgs e) {
- // Determine if clicked column is already the column that is being sorted.
- if (e.Column == _columnSorter.SortColumn) {
- // Reverse the current sort direction for this column.
- _columnSorter.Order = _columnSorter.Order == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
- } else {
- // Set the column number that is to be sorted; default to ascending.
- _columnSorter.SortColumn = e.Column;
- _columnSorter.Order = SortOrder.Ascending;
- }
+ for (int i = 0; i < columns.Length; i++)
+ {
+ listview_imgur_uploads.AutoResizeColumn(i, ColumnHeaderAutoResizeStyle.ColumnContent);
+ }
- // Perform the sort with these new sort options.
- listview_imgur_uploads.Sort();
- }
+ listview_imgur_uploads.EndUpdate();
+ listview_imgur_uploads.Refresh();
+ deleteButton.Enabled = false;
+ openButton.Enabled = false;
+ clipboardButton.Enabled = false;
+ }
+
+ private void Listview_imgur_uploadsSelectedIndexChanged(object sender, EventArgs e)
+ {
+ pictureBox1.Image = pictureBox1.ErrorImage;
+ if (listview_imgur_uploads.SelectedItems.Count > 0)
+ {
+ deleteButton.Enabled = true;
+ openButton.Enabled = true;
+ clipboardButton.Enabled = true;
+ if (listview_imgur_uploads.SelectedItems.Count == 1)
+ {
+ ImgurInfo imgurInfo = (ImgurInfo) listview_imgur_uploads.SelectedItems[0].Tag;
+ pictureBox1.Image = imgurInfo.Image;
+ }
+ }
+ else
+ {
+ pictureBox1.Image = pictureBox1.ErrorImage;
+ deleteButton.Enabled = false;
+ openButton.Enabled = false;
+ clipboardButton.Enabled = false;
+ }
+ }
+
+ private void DeleteButtonClick(object sender, EventArgs e)
+ {
+ if (listview_imgur_uploads.SelectedItems.Count > 0)
+ {
+ for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++)
+ {
+ ImgurInfo imgurInfo = (ImgurInfo) listview_imgur_uploads.SelectedItems[i].Tag;
+ 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)
+ {
+ continue;
+ }
+
+ // Should fix Bug #3378699
+ pictureBox1.Image = pictureBox1.ErrorImage;
+ try
+ {
+ new PleaseWaitForm().ShowAndWait("Imgur", Language.GetString("imgur", LangKey.communication_wait),
+ delegate { ImgurUtils.DeleteImgurImage(imgurInfo); }
+ );
+ }
+ catch (Exception ex)
+ {
+ Log.Warn("Problem communicating with Imgur: ", ex);
+ }
+
+ imgurInfo.Dispose();
+ }
+ }
+
+ Redraw();
+ }
+
+ private void ClipboardButtonClick(object sender, EventArgs e)
+ {
+ StringBuilder links = new StringBuilder();
+ if (listview_imgur_uploads.SelectedItems.Count > 0)
+ {
+ for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++)
+ {
+ ImgurInfo imgurInfo = (ImgurInfo) listview_imgur_uploads.SelectedItems[i].Tag;
+ links.AppendLine(Config.UsePageLink ? imgurInfo.Page : imgurInfo.Original);
+ }
+ }
+
+ ClipboardHelper.SetClipboardData(links.ToString());
+ }
+
+ private void ClearHistoryButtonClick(object sender, EventArgs e)
+ {
+ DialogResult result = MessageBox.Show(Language.GetString("imgur", LangKey.clear_question), "Imgur", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
+ if (result == DialogResult.Yes)
+ {
+ Config.runtimeImgurHistory.Clear();
+ Config.ImgurUploadHistory.Clear();
+ IniConfig.Save();
+ Redraw();
+ }
+ }
+
+ private void FinishedButtonClick(object sender, EventArgs e)
+ {
+ Hide();
+ }
+
+ private void OpenButtonClick(object sender, EventArgs e)
+ {
+ if (listview_imgur_uploads.SelectedItems.Count > 0)
+ {
+ for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++)
+ {
+ ImgurInfo imgurInfo = (ImgurInfo) listview_imgur_uploads.SelectedItems[i].Tag;
+ System.Diagnostics.Process.Start(imgurInfo.Page);
+ }
+ }
+ }
+
+ private void listview_imgur_uploads_ColumnClick(object sender, ColumnClickEventArgs e)
+ {
+ // Determine if clicked column is already the column that is being sorted.
+ if (e.Column == _columnSorter.SortColumn)
+ {
+ // Reverse the current sort direction for this column.
+ _columnSorter.Order = _columnSorter.Order == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
+ }
+ else
+ {
+ // Set the column number that is to be sorted; default to ascending.
+ _columnSorter.SortColumn = e.Column;
+ _columnSorter.Order = SortOrder.Ascending;
+ }
+
+ // Perform the sort with these new sort options.
+ listview_imgur_uploads.Sort();
+ }
- private void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e)
- {
- _instance = null;
- }
- }
-}
+ private void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e)
+ {
+ _instance = null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs b/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs
index 1ece15fb9..4958f897c 100644
--- a/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs
+++ b/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs
@@ -21,25 +21,28 @@
using System;
-namespace Greenshot.Plugin.Imgur.Forms {
- ///
- /// Description of PasswordRequestForm.
- ///
- public partial class SettingsForm : ImgurForm {
- public SettingsForm()
- {
- //
- // The InitializeComponent() call is required for Windows Forms designer support.
- //
- InitializeComponent();
- CancelButton = buttonCancel;
- AcceptButton = buttonOK;
-
- historyButton.Enabled = ImgurUtils.IsHistoryLoadingNeeded();
- }
+namespace Greenshot.Plugin.Imgur.Forms
+{
+ ///
+ /// Description of PasswordRequestForm.
+ ///
+ public partial class SettingsForm : ImgurForm
+ {
+ public SettingsForm()
+ {
+ //
+ // The InitializeComponent() call is required for Windows Forms designer support.
+ //
+ InitializeComponent();
+ CancelButton = buttonCancel;
+ AcceptButton = buttonOK;
- private void ButtonHistoryClick(object sender, EventArgs e) {
- ImgurHistory.ShowHistory();
- }
- }
-}
+ historyButton.Enabled = ImgurUtils.IsHistoryLoadingNeeded();
+ }
+
+ private void ButtonHistoryClick(object sender, EventArgs e)
+ {
+ ImgurHistory.ShowHistory();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs b/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs
index e9725a2d2..fdac54ee3 100644
--- a/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs
+++ b/src/Greenshot.Plugin.Imgur/ImgurConfiguration.cs
@@ -26,64 +26,70 @@ using Greenshot.Plugin.Imgur.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile;
-namespace Greenshot.Plugin.Imgur {
- ///
- /// Description of ImgurConfiguration.
- ///
- [IniSection("Imgur", Description="Greenshot Imgur Plugin configuration")]
- public class ImgurConfiguration : IniSection {
- [IniProperty("ImgurApi3Url", Description = "Url to Imgur system.", DefaultValue = "https://api.imgur.com/3")]
- public string ImgurApi3Url { get; set; }
+namespace Greenshot.Plugin.Imgur
+{
+ ///
+ /// Description of ImgurConfiguration.
+ ///
+ [IniSection("Imgur", Description = "Greenshot Imgur Plugin configuration")]
+ public class ImgurConfiguration : IniSection
+ {
+ [IniProperty("ImgurApi3Url", Description = "Url to Imgur system.", DefaultValue = "https://api.imgur.com/3")]
+ public string ImgurApi3Url { get; set; }
- [IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
- public OutputFormat UploadFormat { get; set; }
- [IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]
- public int UploadJpegQuality { get; set; }
- [IniProperty("UploadReduceColors", Description="Reduce color amount of the uploaded image to 256", DefaultValue="False")]
- public bool UploadReduceColors { get; set; }
- [IniProperty("CopyLinkToClipboard", Description = "Copy the link, which one is controlled by the UsePageLink, on the clipboard", DefaultValue = "True")]
- public bool CopyLinkToClipboard { get; set; }
- [IniProperty("UsePageLink", Description = "Use pagelink instead of direct link on the clipboard", DefaultValue = "False")]
- public bool UsePageLink { get; set; }
- [IniProperty("AnonymousAccess", Description = "Use anonymous access to Imgur", DefaultValue="true")]
- public bool AnonymousAccess { get; set; }
+ [IniProperty("UploadFormat", Description = "What file type to use for uploading", DefaultValue = "png")]
+ public OutputFormat UploadFormat { get; set; }
- [IniProperty("RefreshToken", Description = "Imgur refresh Token", Encrypted = true, ExcludeIfNull = true)]
- public string RefreshToken { get; set; }
+ [IniProperty("UploadJpegQuality", Description = "JPEG file save quality in %.", DefaultValue = "80")]
+ public int UploadJpegQuality { get; set; }
- ///
- /// AccessToken, not stored
- ///
- public string AccessToken { get; set; }
+ [IniProperty("UploadReduceColors", Description = "Reduce color amount of the uploaded image to 256", DefaultValue = "False")]
+ public bool UploadReduceColors { get; set; }
- ///
- /// AccessTokenExpires, not stored
- ///
- public DateTimeOffset AccessTokenExpires { get; set; }
+ [IniProperty("CopyLinkToClipboard", Description = "Copy the link, which one is controlled by the UsePageLink, on the clipboard", DefaultValue = "True")]
+ public bool CopyLinkToClipboard { get; set; }
- [IniProperty("AddTitle", Description = "Is the title passed on to Imgur", DefaultValue = "False")]
- public bool AddTitle { get; set; }
- [IniProperty("AddFilename", Description = "Is the filename passed on to Imgur", DefaultValue = "False")]
- public bool AddFilename { get; set; }
- [IniProperty("FilenamePattern", Description = "Filename for the Imgur upload", DefaultValue = "${capturetime:d\"yyyyMMdd-HHmm\"}")]
- public string FilenamePattern { get; set; }
+ [IniProperty("UsePageLink", Description = "Use pagelink instead of direct link on the clipboard", DefaultValue = "False")]
+ public bool UsePageLink { get; set; }
- [IniProperty("ImgurUploadHistory", Description="Imgur upload history (ImgurUploadHistory.hash=deleteHash)")]
- public Dictionary ImgurUploadHistory { get; set; }
+ [IniProperty("AnonymousAccess", Description = "Use anonymous access to Imgur", DefaultValue = "true")]
+ public bool AnonymousAccess { get; set; }
- // Not stored, only run-time!
- public Dictionary runtimeImgurHistory = new Dictionary();
- public int Credits {
- get;
- set;
- }
+ [IniProperty("RefreshToken", Description = "Imgur refresh Token", Encrypted = true, ExcludeIfNull = true)]
+ public string RefreshToken { get; set; }
- ///
- /// Supply values we can't put as defaults
- ///
- /// The property to return a default for
- /// object with the default value for the supplied property
- public override object GetDefault(string property) =>
+ ///
+ /// AccessToken, not stored
+ ///
+ public string AccessToken { get; set; }
+
+ ///
+ /// AccessTokenExpires, not stored
+ ///
+ public DateTimeOffset AccessTokenExpires { get; set; }
+
+ [IniProperty("AddTitle", Description = "Is the title passed on to Imgur", DefaultValue = "False")]
+ public bool AddTitle { get; set; }
+
+ [IniProperty("AddFilename", Description = "Is the filename passed on to Imgur", DefaultValue = "False")]
+ public bool AddFilename { get; set; }
+
+ [IniProperty("FilenamePattern", Description = "Filename for the Imgur upload", DefaultValue = "${capturetime:d\"yyyyMMdd-HHmm\"}")]
+ public string FilenamePattern { get; set; }
+
+ [IniProperty("ImgurUploadHistory", Description = "Imgur upload history (ImgurUploadHistory.hash=deleteHash)")]
+ public Dictionary ImgurUploadHistory { get; set; }
+
+ // Not stored, only run-time!
+ public Dictionary runtimeImgurHistory = new Dictionary();
+ public int Credits { get; set; }
+
+ ///
+ /// Supply values we can't put as defaults
+ ///
+ /// The property to return a default for
+ /// object with the default value for the supplied property
+ public override object GetDefault(string property) =>
property switch
{
"ImgurUploadHistory" => new Dictionary(),
@@ -91,13 +97,14 @@ namespace Greenshot.Plugin.Imgur {
};
///
- /// A form for username/password
- ///
- /// bool true if OK was pressed, false if cancel
- public bool ShowConfigDialog() {
- SettingsForm settingsForm = new SettingsForm();
- DialogResult result = settingsForm.ShowDialog();
- return result == DialogResult.OK;
- }
- }
-}
+ /// A form for username/password
+ ///
+ /// bool true if OK was pressed, false if cancel
+ public bool ShowConfigDialog()
+ {
+ SettingsForm settingsForm = new SettingsForm();
+ DialogResult result = settingsForm.ShowDialog();
+ return result == DialogResult.OK;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Imgur/ImgurDestination.cs b/src/Greenshot.Plugin.Imgur/ImgurDestination.cs
index aa24ad68c..a0d069f1a 100644
--- a/src/Greenshot.Plugin.Imgur/ImgurDestination.cs
+++ b/src/Greenshot.Plugin.Imgur/ImgurDestination.cs
@@ -24,35 +24,42 @@ using System.Drawing;
using GreenshotPlugin.Core;
using GreenshotPlugin.Interfaces;
-namespace Greenshot.Plugin.Imgur {
- ///
- /// Description of ImgurDestination.
- ///
- public class ImgurDestination : AbstractDestination {
- private readonly ImgurPlugin _plugin;
+namespace Greenshot.Plugin.Imgur
+{
+ ///
+ /// Description of ImgurDestination.
+ ///
+ public class ImgurDestination : AbstractDestination
+ {
+ private readonly ImgurPlugin _plugin;
- public ImgurDestination(ImgurPlugin plugin) {
- _plugin = plugin;
- }
-
- public override string Designation => "Imgur";
+ public ImgurDestination(ImgurPlugin plugin)
+ {
+ _plugin = plugin;
+ }
- public override string Description => Language.GetString("imgur", LangKey.upload_menu_item);
+ public override string Designation => "Imgur";
- public override Image DisplayIcon {
- get {
- ComponentResourceManager resources = new ComponentResourceManager(typeof(ImgurPlugin));
- return (Image)resources.GetObject("Imgur");
- }
- }
+ public override string Description => Language.GetString("imgur", LangKey.upload_menu_item);
- public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
+ public override Image DisplayIcon
+ {
+ get
+ {
+ ComponentResourceManager resources = new ComponentResourceManager(typeof(ImgurPlugin));
+ return (Image) resources.GetObject("Imgur");
+ }
+ }
+
+ public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
+ {
ExportInformation exportInformation = new ExportInformation(Designation, Description)
{
- ExportMade = _plugin.Upload(captureDetails, surface, out var uploadUrl), Uri = uploadUrl
+ ExportMade = _plugin.Upload(captureDetails, surface, out var uploadUrl),
+ Uri = uploadUrl
};
ProcessExport(exportInformation, surface);
- return exportInformation;
- }
- }
-}
+ return exportInformation;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs
index 5dc82ec2a..4fdfb7a86 100644
--- a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs
+++ b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs
@@ -25,194 +25,172 @@ using System.Xml;
namespace Greenshot.Plugin.Imgur
{
- ///
- /// Description of ImgurInfo.
- ///
- public class ImgurInfo : IDisposable
- {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurInfo));
+ ///
+ /// Description of ImgurInfo.
+ ///
+ public class ImgurInfo : IDisposable
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurInfo));
- public string Hash
- {
- get;
- set;
- }
+ public string Hash { get; set; }
- private string _deleteHash;
- public string DeleteHash
- {
- get { return _deleteHash; }
- set
- {
- _deleteHash = value;
- DeletePage = "https://imgur.com/delete/" + value;
- }
- }
+ private string _deleteHash;
- public string Title
- {
- get;
- set;
- }
+ public string DeleteHash
+ {
+ get { return _deleteHash; }
+ set
+ {
+ _deleteHash = value;
+ DeletePage = "https://imgur.com/delete/" + value;
+ }
+ }
- public string ImageType
- {
- get;
- set;
- }
+ public string Title { get; set; }
- public DateTime Timestamp
- {
- get;
- set;
- }
+ public string ImageType { get; set; }
- public string Original
- {
- get;
- set;
- }
+ public DateTime Timestamp { get; set; }
- public string Page
- {
- get;
- set;
- }
+ public string Original { get; set; }
- public string SmallSquare
- {
- get;
- set;
- }
+ public string Page { get; set; }
- public string LargeThumbnail
- {
- get;
- set;
- }
+ public string SmallSquare { get; set; }
- public string DeletePage
- {
- get;
- set;
- }
+ public string LargeThumbnail { get; set; }
- private Image _image;
- public Image Image
- {
- get { return _image; }
- set
- {
- _image?.Dispose();
- _image = value;
- }
- }
+ public string DeletePage { get; set; }
- ///
- /// The public accessible Dispose
- /// Will call the GarbageCollector to SuppressFinalize, preventing being cleaned twice
- ///
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
+ private Image _image;
- ///
- /// This Dispose is called from the Dispose and the Destructor.
- /// When disposing==true all non-managed resources should be freed too!
- ///
- ///
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- _image?.Dispose();
- }
- _image = null;
- }
- public static ImgurInfo ParseResponse(string response)
- {
- Log.Debug(response);
- // This is actually a hack for BUG-1695
- // The problem is the (C) sign, we send it HTML encoded "®" 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.
- response = response.Replace("¢", "¢");
- response = response.Replace("£", "£");
- response = response.Replace("¥", "¥");
- response = response.Replace("€", "€");
- response = response.Replace("©", "©");
- response = response.Replace("®", "®");
+ public Image Image
+ {
+ get { return _image; }
+ set
+ {
+ _image?.Dispose();
+ _image = value;
+ }
+ }
- ImgurInfo imgurInfo = new ImgurInfo();
- try
- {
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(response);
- XmlNodeList nodes = doc.GetElementsByTagName("id");
- if (nodes.Count > 0)
- {
- imgurInfo.Hash = nodes.Item(0)?.InnerText;
- }
- nodes = doc.GetElementsByTagName("hash");
- if (nodes.Count > 0)
- {
- imgurInfo.Hash = nodes.Item(0)?.InnerText;
- }
- nodes = doc.GetElementsByTagName("deletehash");
- if (nodes.Count > 0)
- {
- imgurInfo.DeleteHash = nodes.Item(0)?.InnerText;
- }
- nodes = doc.GetElementsByTagName("type");
- if (nodes.Count > 0)
- {
- imgurInfo.ImageType = nodes.Item(0)?.InnerText;
- }
- nodes = doc.GetElementsByTagName("title");
- if (nodes.Count > 0)
- {
- imgurInfo.Title = nodes.Item(0)?.InnerText;
- }
- nodes = doc.GetElementsByTagName("datetime");
- if (nodes.Count > 0)
- {
- // Version 3 has seconds since Epoch
+ ///
+ /// The public accessible Dispose
+ /// Will call the GarbageCollector to SuppressFinalize, preventing being cleaned twice
+ ///
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// This Dispose is called from the Dispose and the Destructor.
+ /// When disposing==true all non-managed resources should be freed too!
+ ///
+ ///
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _image?.Dispose();
+ }
+
+ _image = null;
+ }
+
+ public static ImgurInfo ParseResponse(string response)
+ {
+ Log.Debug(response);
+ // This is actually a hack for BUG-1695
+ // The problem is the (C) sign, we send it HTML encoded "®" 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.
+ response = response.Replace("¢", "¢");
+ response = response.Replace("£", "£");
+ response = response.Replace("¥", "¥");
+ response = response.Replace("€", "€");
+ response = response.Replace("©", "©");
+ response = response.Replace("®", "®");
+
+ ImgurInfo imgurInfo = new ImgurInfo();
+ try
+ {
+ XmlDocument doc = new XmlDocument();
+ doc.LoadXml(response);
+ XmlNodeList nodes = doc.GetElementsByTagName("id");
+ if (nodes.Count > 0)
+ {
+ imgurInfo.Hash = nodes.Item(0)?.InnerText;
+ }
+
+ nodes = doc.GetElementsByTagName("hash");
+ if (nodes.Count > 0)
+ {
+ imgurInfo.Hash = nodes.Item(0)?.InnerText;
+ }
+
+ nodes = doc.GetElementsByTagName("deletehash");
+ if (nodes.Count > 0)
+ {
+ imgurInfo.DeleteHash = nodes.Item(0)?.InnerText;
+ }
+
+ nodes = doc.GetElementsByTagName("type");
+ if (nodes.Count > 0)
+ {
+ imgurInfo.ImageType = nodes.Item(0)?.InnerText;
+ }
+
+ nodes = doc.GetElementsByTagName("title");
+ if (nodes.Count > 0)
+ {
+ imgurInfo.Title = nodes.Item(0)?.InnerText;
+ }
+
+ nodes = doc.GetElementsByTagName("datetime");
+ if (nodes.Count > 0)
+ {
+ // Version 3 has seconds since Epoch
if (double.TryParse(nodes.Item(0)?.InnerText, out var secondsSince))
- {
- var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
- imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime;
- }
- }
- nodes = doc.GetElementsByTagName("original");
- if (nodes.Count > 0)
- {
- imgurInfo.Original = nodes.Item(0)?.InnerText.Replace("http:", "https:");
- }
- // Version 3 API only has Link
- nodes = doc.GetElementsByTagName("link");
- if (nodes.Count > 0)
- {
- imgurInfo.Original = nodes.Item(0)?.InnerText.Replace("http:", "https:");
- }
- nodes = doc.GetElementsByTagName("imgur_page");
- if (nodes.Count > 0)
- {
- imgurInfo.Page = nodes.Item(0)?.InnerText.Replace("http:", "https:");
- }
- else
- {
- // Version 3 doesn't have a page link in the response
- imgurInfo.Page = $"https://imgur.com/{imgurInfo.Hash}";
- }
- nodes = doc.GetElementsByTagName("small_square");
- imgurInfo.SmallSquare = nodes.Count > 0 ? nodes.Item(0)?.InnerText : $"http://i.imgur.com/{imgurInfo.Hash}s.png";
- }
- catch (Exception e)
- {
- Log.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
- }
- return imgurInfo;
- }
- }
-}
+ {
+ var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
+ imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime;
+ }
+ }
+
+ nodes = doc.GetElementsByTagName("original");
+ if (nodes.Count > 0)
+ {
+ imgurInfo.Original = nodes.Item(0)?.InnerText.Replace("http:", "https:");
+ }
+
+ // Version 3 API only has Link
+ nodes = doc.GetElementsByTagName("link");
+ if (nodes.Count > 0)
+ {
+ imgurInfo.Original = nodes.Item(0)?.InnerText.Replace("http:", "https:");
+ }
+
+ nodes = doc.GetElementsByTagName("imgur_page");
+ if (nodes.Count > 0)
+ {
+ imgurInfo.Page = nodes.Item(0)?.InnerText.Replace("http:", "https:");
+ }
+ else
+ {
+ // Version 3 doesn't have a page link in the response
+ imgurInfo.Page = $"https://imgur.com/{imgurInfo.Hash}";
+ }
+
+ nodes = doc.GetElementsByTagName("small_square");
+ imgurInfo.SmallSquare = nodes.Count > 0 ? nodes.Item(0)?.InnerText : $"http://i.imgur.com/{imgurInfo.Hash}s.png";
+ }
+ catch (Exception e)
+ {
+ Log.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
+ }
+
+ return imgurInfo;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs
index ef2edfe4b..a936c80d7 100644
--- a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs
+++ b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs
@@ -32,186 +32,216 @@ using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
-namespace Greenshot.Plugin.Imgur {
- ///
- /// This is the ImgurPlugin code
- ///
+namespace Greenshot.Plugin.Imgur
+{
+ ///
+ /// This is the ImgurPlugin code
+ ///
[Plugin("Imgur", true)]
- public class ImgurPlugin : IGreenshotPlugin {
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurPlugin));
- private static ImgurConfiguration _config;
- private ComponentResourceManager _resources;
- private ToolStripMenuItem _historyMenuItem;
- private ToolStripMenuItem _itemPlugInConfig;
+ public class ImgurPlugin : IGreenshotPlugin
+ {
+ private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurPlugin));
+ private static ImgurConfiguration _config;
+ private ComponentResourceManager _resources;
+ private ToolStripMenuItem _historyMenuItem;
+ private ToolStripMenuItem _itemPlugInConfig;
- public void Dispose() {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- protected virtual void Dispose(bool disposing) {
- if (disposing) {
- if (_historyMenuItem != null) {
- _historyMenuItem.Dispose();
- _historyMenuItem = null;
- }
- if (_itemPlugInConfig != null) {
- _itemPlugInConfig.Dispose();
- _itemPlugInConfig = null;
- }
- }
- }
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ if (_historyMenuItem != null)
+ {
+ _historyMenuItem.Dispose();
+ _historyMenuItem = null;
+ }
- private IEnumerable Destinations() {
- yield return new ImgurDestination(this);
- }
+ if (_itemPlugInConfig != null)
+ {
+ _itemPlugInConfig.Dispose();
+ _itemPlugInConfig = null;
+ }
+ }
+ }
- ///
- /// Implementation of the IGreenshotPlugin.Initialize
- ///
- /// true if plugin is initialized, false if not (doesn't show)
- public bool Initialize() {
- // Get configuration
- _config = IniConfig.GetIniSection();
- _resources = new ComponentResourceManager(typeof(ImgurPlugin));
+ private IEnumerable Destinations()
+ {
+ yield return new ImgurDestination(this);
+ }
- ToolStripMenuItem itemPlugInRoot = new ToolStripMenuItem("Imgur")
- {
- Image = (Image) _resources.GetObject("Imgur")
- };
+ ///
+ /// Implementation of the IGreenshotPlugin.Initialize
+ ///
+ /// true if plugin is initialized, false if not (doesn't show)
+ public bool Initialize()
+ {
+ // Get configuration
+ _config = IniConfig.GetIniSection();
+ _resources = new ComponentResourceManager(typeof(ImgurPlugin));
+
+ ToolStripMenuItem itemPlugInRoot = new ToolStripMenuItem("Imgur")
+ {
+ Image = (Image) _resources.GetObject("Imgur")
+ };
// Provide the IDestination
SimpleServiceProvider.Current.AddService(Destinations());
_historyMenuItem = new ToolStripMenuItem(Language.GetString("imgur", LangKey.history));
- _historyMenuItem.Click += delegate {
- ImgurHistory.ShowHistory();
- };
- itemPlugInRoot.DropDownItems.Add(_historyMenuItem);
+ _historyMenuItem.Click += delegate { ImgurHistory.ShowHistory(); };
+ itemPlugInRoot.DropDownItems.Add(_historyMenuItem);
_itemPlugInConfig = new ToolStripMenuItem(Language.GetString("imgur", LangKey.configure));
- _itemPlugInConfig.Click += delegate {
- _config.ShowConfigDialog();
- };
- itemPlugInRoot.DropDownItems.Add(_itemPlugInConfig);
+ _itemPlugInConfig.Click += delegate { _config.ShowConfigDialog(); };
+ itemPlugInRoot.DropDownItems.Add(_itemPlugInConfig);
- PluginUtils.AddToContextMenu(itemPlugInRoot);
- Language.LanguageChanged += OnLanguageChanged;
+ PluginUtils.AddToContextMenu(itemPlugInRoot);
+ Language.LanguageChanged += OnLanguageChanged;
- // Enable history if there are items available
- UpdateHistoryMenuItem();
- return true;
- }
+ // Enable history if there are items available
+ UpdateHistoryMenuItem();
+ return true;
+ }
- public void OnLanguageChanged(object sender, EventArgs e) {
- if (_itemPlugInConfig != null) {
- _itemPlugInConfig.Text = Language.GetString("imgur", LangKey.configure);
- }
- if (_historyMenuItem != null) {
- _historyMenuItem.Text = Language.GetString("imgur", LangKey.history);
- }
- }
+ public void OnLanguageChanged(object sender, EventArgs e)
+ {
+ if (_itemPlugInConfig != null)
+ {
+ _itemPlugInConfig.Text = Language.GetString("imgur", LangKey.configure);
+ }
- private void UpdateHistoryMenuItem() {
- if (_historyMenuItem == null)
- {
- return;
- }
- try
+ if (_historyMenuItem != null)
+ {
+ _historyMenuItem.Text = Language.GetString("imgur", LangKey.history);
+ }
+ }
+
+ private void UpdateHistoryMenuItem()
+ {
+ if (_historyMenuItem == null)
+ {
+ return;
+ }
+
+ try
{
var form = SimpleServiceProvider.Current.GetInstance