Code quality changes, and added the possibility to set the amount of colors for the Quantizer.

This commit is contained in:
RKrom 2014-05-11 11:23:56 +02:00
parent 3b1560390b
commit 77a92d98c3
92 changed files with 690 additions and 653 deletions

View file

@ -55,9 +55,8 @@ namespace Greenshot.Destinations {
get { get {
if (editor == null) { if (editor == null) {
return Language.GetString(LangKey.settings_destination_editor); return Language.GetString(LangKey.settings_destination_editor);
} else {
return Language.GetString(LangKey.settings_destination_editor) + " - " + editor.CaptureDetails.Title;
} }
return Language.GetString(LangKey.settings_destination_editor) + " - " + editor.CaptureDetails.Title;
} }
} }

View file

@ -57,9 +57,8 @@ namespace Greenshot.Destinations {
get { get {
if (printerName != null) { if (printerName != null) {
return Language.GetString(LangKey.settings_destination_printer) + " - " + printerName; return Language.GetString(LangKey.settings_destination_printer) + " - " + printerName;
} else {
return Language.GetString(LangKey.settings_destination_printer);
} }
return Language.GetString(LangKey.settings_destination_printer);
} }
} }

View file

@ -108,9 +108,8 @@ namespace Greenshot.Drawing {
return drawingBounds; return drawingBounds;
} }
} }
} else {
return Rectangle.Empty;
} }
return Rectangle.Empty;
} }
} }
@ -125,9 +124,8 @@ namespace Greenshot.Drawing {
return path.IsOutlineVisible(x, y, pen); return path.IsOutlineVisible(x, y, pen);
} }
} }
} else {
return false;
} }
return false;
} }
} }
} }

View file

@ -31,7 +31,7 @@ namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// Description of CursorContainer. /// Description of CursorContainer.
/// </summary> /// </summary>
[Serializable()] [Serializable]
public class CursorContainer : DrawableContainer, ICursorContainer { public class CursorContainer : DrawableContainer, ICursorContainer {
private static ILog LOG = LogManager.GetLogger(typeof(CursorContainer)); private static ILog LOG = LogManager.GetLogger(typeof(CursorContainer));
@ -73,22 +73,24 @@ namespace Greenshot.Drawing {
} }
public void Load(string filename) { public void Load(string filename) {
if (File.Exists(filename)) { if (!File.Exists(filename)) {
using (Cursor fileCursor = new Cursor(filename)) { return;
Cursor = fileCursor; }
LOG.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width); using (Cursor fileCursor = new Cursor(filename)) {
} Cursor = fileCursor;
LOG.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width);
} }
} }
public override void Draw(Graphics graphics, RenderMode rm) { public override void Draw(Graphics graphics, RenderMode rm) {
if (cursor != null) { if (cursor == null) {
graphics.SmoothingMode = SmoothingMode.HighQuality; return;
graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
graphics.CompositingQuality = CompositingQuality.Default;
graphics.PixelOffsetMode = PixelOffsetMode.None;
cursor.DrawStretched(graphics, Bounds);
} }
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
graphics.CompositingQuality = CompositingQuality.Default;
graphics.PixelOffsetMode = PixelOffsetMode.None;
cursor.DrawStretched(graphics, Bounds);
} }
public override Size DefaultSize { public override Size DefaultSize {

View file

@ -225,14 +225,14 @@ namespace Greenshot.Drawing {
private int round(float f) { private int round(float f) {
if(float.IsPositiveInfinity(f) || f>int.MaxValue/2) return int.MaxValue/2; if(float.IsPositiveInfinity(f) || f>int.MaxValue/2) return int.MaxValue/2;
else if (float.IsNegativeInfinity(f) || f<int.MinValue/2) return int.MinValue/2; if (float.IsNegativeInfinity(f) || f<int.MinValue/2) return int.MinValue/2;
return (int)Math.Round(f); return (int)Math.Round(f);
} }
private int round(double d) { private int round(double d) {
if(Double.IsPositiveInfinity(d) || d>int.MaxValue/2) return int.MaxValue/2; if(Double.IsPositiveInfinity(d) || d>int.MaxValue/2) return int.MaxValue/2;
else if (Double.IsNegativeInfinity(d) || d<int.MinValue/2) return int.MinValue/2; if (Double.IsNegativeInfinity(d) || d<int.MinValue/2) return int.MinValue/2;
else return (int)Math.Round(d); return (int)Math.Round(d);
} }
private bool accountForShadowChange = false; private bool accountForShadowChange = false;

View file

@ -29,17 +29,15 @@ using Greenshot.Plugin;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.IniFile;
using Greenshot.Configuration; using Greenshot.Configuration;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// Dispatches most of a DrawableContainer's public properties and methods to a list of DrawableContainers. /// Dispatches most of a DrawableContainer's public properties and methods to a list of DrawableContainers.
/// </summary> /// </summary>
[Serializable()] [Serializable]
public class DrawableContainerList : List<IDrawableContainer> { public class DrawableContainerList : List<IDrawableContainer> {
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly ComponentResourceManager editorFormResources = new ComponentResourceManager(typeof(ImageEditorForm));
private static ComponentResourceManager editorFormResources = new ComponentResourceManager(typeof(ImageEditorForm));
public Guid ParentID { public Guid ParentID {
get; get;
@ -58,7 +56,7 @@ namespace Greenshot.Drawing {
return this[Count-1].Status; return this[Count-1].Status;
} }
set { set {
foreach (DrawableContainer dc in this) { foreach (var dc in this) {
dc.Status = value; dc.Status = value;
} }
} }
@ -79,13 +77,13 @@ namespace Greenshot.Drawing {
public bool Selected { public bool Selected {
get { get {
bool ret = true; bool ret = true;
foreach(DrawableContainer dc in this) { foreach(var dc in this) {
ret &= dc.Selected; ret &= dc.Selected;
} }
return ret; return ret;
} }
set { set {
foreach(DrawableContainer dc in this) { foreach(var dc in this) {
dc.Selected = value; dc.Selected = value;
} }
} }
@ -104,7 +102,8 @@ namespace Greenshot.Drawing {
} }
set { set {
ParentID = value.ID; ParentID = value.ID;
foreach(DrawableContainer dc in this) { foreach(var drawableContainer in this) {
var dc = (DrawableContainer) drawableContainer;
dc.Parent = value; dc.Parent = value;
} }
} }
@ -137,7 +136,7 @@ namespace Greenshot.Drawing {
// Invalidate before moving, otherwise the old locations aren't refreshed // Invalidate before moving, otherwise the old locations aren't refreshed
Invalidate(); Invalidate();
foreach(DrawableContainer dc in this) { foreach(var dc in this) {
dc.Left += dx; dc.Left += dx;
dc.Top += dy; dc.Top += dy;
modified = true; modified = true;
@ -155,7 +154,7 @@ namespace Greenshot.Drawing {
/// Hides the grippers of all elements in the list. /// Hides the grippers of all elements in the list.
/// </summary> /// </summary>
public void HideGrippers() { public void HideGrippers() {
foreach(DrawableContainer dc in this) { foreach(var dc in this) {
dc.HideGrippers(); dc.HideGrippers();
dc.Invalidate(); dc.Invalidate();
} }
@ -165,7 +164,7 @@ namespace Greenshot.Drawing {
/// Shows the grippers of all elements in the list. /// Shows the grippers of all elements in the list.
/// </summary> /// </summary>
public void ShowGrippers() { public void ShowGrippers() {
foreach(DrawableContainer dc in this) { foreach(var dc in this) {
dc.ShowGrippers(); dc.ShowGrippers();
dc.Invalidate(); dc.Invalidate();
} }
@ -179,7 +178,7 @@ namespace Greenshot.Drawing {
/// <returns>true if one of the elements in the list is clickable at the given location, false otherwise</returns> /// <returns>true if one of the elements in the list is clickable at the given location, false otherwise</returns>
public bool ClickableAt(int x, int y) { public bool ClickableAt(int x, int y) {
bool ret = false; bool ret = false;
foreach(DrawableContainer dc in this) { foreach(var dc in this) {
ret |= dc.ClickableAt(x, y); ret |= dc.ClickableAt(x, y);
} }
return ret; return ret;
@ -204,7 +203,8 @@ namespace Greenshot.Drawing {
/// Dispatches OnDoubleClick to all elements in the list. /// Dispatches OnDoubleClick to all elements in the list.
/// </summary> /// </summary>
public void OnDoubleClick() { public void OnDoubleClick() {
foreach(DrawableContainer dc in this) { foreach(var drawableContainer in this) {
var dc = (DrawableContainer) drawableContainer;
dc.OnDoubleClick(); dc.OnDoubleClick();
} }
} }
@ -214,8 +214,8 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="clipRectangle"></param> /// <param name="clipRectangle"></param>
/// <returns>true if an filter intersects</returns> /// <returns>true if an filter intersects</returns>
public bool hasIntersectingFilters(Rectangle clipRectangle) { public bool HasIntersectingFilters(Rectangle clipRectangle) {
foreach(DrawableContainer dc in this) { foreach(var dc in this) {
if (dc.DrawingBounds.IntersectsWith(clipRectangle) && dc.hasFilters && dc.Status == EditStatus.IDLE) { if (dc.DrawingBounds.IntersectsWith(clipRectangle) && dc.hasFilters && dc.Status == EditStatus.IDLE) {
return true; return true;
} }
@ -229,7 +229,7 @@ namespace Greenshot.Drawing {
/// <param name="clipRectangle"></param> /// <param name="clipRectangle"></param>
/// <returns></returns> /// <returns></returns>
public bool IntersectsWith(Rectangle clipRectangle) { public bool IntersectsWith(Rectangle clipRectangle) {
foreach(DrawableContainer dc in this) { foreach(var dc in this) {
if (dc.DrawingBounds.IntersectsWith(clipRectangle)) { if (dc.DrawingBounds.IntersectsWith(clipRectangle)) {
return true; return true;
} }
@ -240,10 +240,13 @@ namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// Triggers all elements in the list ot be redrawn. /// Triggers all elements in the list ot be redrawn.
/// </summary> /// </summary>
/// <param name="g">the related Graphics object</param> /// <param name="g">the to the bitmap related Graphics object</param>
/// <param name="bitmap">Bitmap to draw</param>
/// <param name="renderMode">the rendermode in which the element is to be drawn</param> /// <param name="renderMode">the rendermode in which the element is to be drawn</param>
/// <param name="clipRectangle"></param>
public void Draw(Graphics g, Bitmap bitmap, RenderMode renderMode, Rectangle clipRectangle) { public void Draw(Graphics g, Bitmap bitmap, RenderMode renderMode, Rectangle clipRectangle) {
foreach(DrawableContainer dc in this) { foreach(var drawableContainer in this) {
var dc = (DrawableContainer) drawableContainer;
if (dc.DrawingBounds.IntersectsWith(clipRectangle)) { if (dc.DrawingBounds.IntersectsWith(clipRectangle)) {
dc.DrawContent(g, bitmap, renderMode, clipRectangle); dc.DrawContent(g, bitmap, renderMode, clipRectangle);
} }
@ -256,7 +259,8 @@ namespace Greenshot.Drawing {
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
public void HandleFieldChangedEvent(object sender, FieldChangedEventArgs e) { public void HandleFieldChangedEvent(object sender, FieldChangedEventArgs e) {
foreach(DrawableContainer dc in this) { foreach(var drawableContainer in this) {
var dc = (DrawableContainer) drawableContainer;
dc.HandleFieldChanged(sender, e); dc.HandleFieldChanged(sender, e);
} }
} }
@ -265,7 +269,7 @@ namespace Greenshot.Drawing {
/// Invalidate the bounds of all the DC's in this list /// Invalidate the bounds of all the DC's in this list
/// </summary> /// </summary>
public void Invalidate() { public void Invalidate() {
foreach(DrawableContainer dc in this) { foreach(var dc in this) {
dc.Invalidate(); dc.Invalidate();
} }
} }
@ -279,7 +283,7 @@ namespace Greenshot.Drawing {
if (elements.Count == 0 || elements.Count == Count) { if (elements.Count == 0 || elements.Count == Count) {
return false; return false;
} }
foreach(DrawableContainer element in elements) { foreach(var element in elements) {
if (IndexOf(element) < Count - elements.Count) { if (IndexOf(element) < Count - elements.Count) {
return true; return true;
} }
@ -293,11 +297,12 @@ namespace Greenshot.Drawing {
/// <param name="elements">list of elements to pull up</param> /// <param name="elements">list of elements to pull up</param>
public void PullElementsUp(DrawableContainerList elements) { public void PullElementsUp(DrawableContainerList elements) {
for(int i=Count-1; i>=0; i--) { for(int i=Count-1; i>=0; i--) {
IDrawableContainer dc = this[i]; var dc = this[i];
if (elements.Contains(dc)) { if (!elements.Contains(dc)) {
if (Count > (i+1) && !elements.Contains(this[i+1])) { continue;
SwapElements(i,i+1); }
} if (Count > (i+1) && !elements.Contains(this[i+1])) {
SwapElements(i,i+1);
} }
} }
} }
@ -307,14 +312,15 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="elements">of elements to pull to top</param> /// <param name="elements">of elements to pull to top</param>
public void PullElementsToTop(DrawableContainerList elements) { public void PullElementsToTop(DrawableContainerList elements) {
IDrawableContainer[] dcs = ToArray(); var dcs = ToArray();
for(int i=0; i<dcs.Length; i++) { for(int i=0; i<dcs.Length; i++) {
IDrawableContainer dc = dcs[i]; var dc = dcs[i];
if (elements.Contains(dc)) { if (!elements.Contains(dc)) {
Remove(dc); continue;
Add(dc);
Parent.Modified = true;
} }
Remove(dc);
Add(dc);
Parent.Modified = true;
} }
} }
@ -328,7 +334,7 @@ namespace Greenshot.Drawing {
if (elements.Count == 0 || elements.Count == Count) { if (elements.Count == 0 || elements.Count == Count) {
return false; return false;
} }
foreach(DrawableContainer element in elements) { foreach(var element in elements) {
if (IndexOf(element) >= elements.Count) { if (IndexOf(element) >= elements.Count) {
return true; return true;
} }
@ -342,11 +348,12 @@ namespace Greenshot.Drawing {
/// <param name="elements">list of elements to push down</param> /// <param name="elements">list of elements to push down</param>
public void PushElementsDown(DrawableContainerList elements) { public void PushElementsDown(DrawableContainerList elements) {
for(int i=0; i<Count; i++) { for(int i=0; i<Count; i++) {
IDrawableContainer dc = this[i]; var dc = this[i];
if(elements.Contains(dc)) { if (!elements.Contains(dc)) {
if((i>0) && !elements.Contains(this[i-1])) { continue;
SwapElements(i,i-1); }
} if((i>0) && !elements.Contains(this[i-1])) {
SwapElements(i,i-1);
} }
} }
} }
@ -356,14 +363,15 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="elements">of elements to push to bottom</param> /// <param name="elements">of elements to push to bottom</param>
public void PushElementsToBottom(DrawableContainerList elements) { public void PushElementsToBottom(DrawableContainerList elements) {
IDrawableContainer[] dcs = ToArray(); var dcs = ToArray();
for(int i=dcs.Length-1; i>=0; i--) { for(int i=dcs.Length-1; i>=0; i--) {
IDrawableContainer dc = dcs[i]; var dc = dcs[i];
if(elements.Contains(dc)) { if (!elements.Contains(dc)) {
Remove(dc); continue;
Insert(0, dc);
Parent.Modified = true;
} }
Remove(dc);
Insert(0, dc);
Parent.Modified = true;
} }
} }
@ -374,18 +382,20 @@ namespace Greenshot.Drawing {
/// <param name="index1">index of the 1st element</param> /// <param name="index1">index of the 1st element</param>
/// <param name="index2">index of the 2nd element</param> /// <param name="index2">index of the 2nd element</param>
private void SwapElements(int index1, int index2) { private void SwapElements(int index1, int index2) {
if(index1 >= 0 && index1 < Count && index2 >= 0 && index2 < Count && index1 != index2) { if (index1 < 0 || index1 >= Count || index2 < 0 || index2 >= Count || index1 == index2) {
IDrawableContainer dc = this[index1]; return;
this[index1] = this[index2];
this[index2] = dc;
Parent.Modified = true;
} }
var dc = this[index1];
this[index1] = this[index2];
this[index2] = dc;
Parent.Modified = true;
} }
/// <summary> /// <summary>
/// Add items to a context menu for the selected item /// Add items to a context menu for the selected item
/// </summary> /// </summary>
/// <param name="menu"></param> /// <param name="menu"></param>
/// <param name="surface"></param>
public virtual void AddContextMenuItems(ContextMenuStrip menu, Surface surface) { public virtual void AddContextMenuItems(ContextMenuStrip menu, Surface surface) {
bool push = surface.Elements.CanPushDown(this); bool push = surface.Elements.CanPushDown(this);
bool pull = surface.Elements.CanPullUp(this); bool pull = surface.Elements.CanPullUp(this);
@ -449,10 +459,11 @@ namespace Greenshot.Drawing {
item.Click += delegate { item.Click += delegate {
ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this);
List<DrawableContainer> containersToDelete = new List<DrawableContainer>(); List<DrawableContainer> containersToDelete = new List<DrawableContainer>();
foreach (DrawableContainer container in this) { foreach (var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer;
containersToDelete.Add(container); containersToDelete.Add(container);
} }
foreach (DrawableContainer container in containersToDelete) { foreach (var container in containersToDelete) {
surface.RemoveElement(container, true); surface.RemoveElement(container, true);
} }
}; };
@ -463,7 +474,8 @@ namespace Greenshot.Drawing {
item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image")));
item.Click += delegate { item.Click += delegate {
List<DrawableContainer> containersToDelete = new List<DrawableContainer>(); List<DrawableContainer> containersToDelete = new List<DrawableContainer>();
foreach(DrawableContainer container in this) { foreach(var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer;
containersToDelete.Add(container); containersToDelete.Add(container);
} }
foreach (DrawableContainer container in containersToDelete) { foreach (DrawableContainer container in containersToDelete) {
@ -474,7 +486,8 @@ namespace Greenshot.Drawing {
// Reset // Reset
bool canReset = false; bool canReset = false;
foreach (DrawableContainer container in this) { foreach (var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer;
if (container.hasDefaultSize) { if (container.hasDefaultSize) {
canReset = true; canReset = true;
} }
@ -483,15 +496,17 @@ namespace Greenshot.Drawing {
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_resetsize)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_resetsize));
//item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); //item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image")));
item.Click += delegate { item.Click += delegate {
foreach (DrawableContainer container in this) { foreach (var drawableContainer in this) {
if (container.hasDefaultSize) { var container = (DrawableContainer) drawableContainer;
Size defaultSize = container.DefaultSize; if (!container.hasDefaultSize) {
container.Invalidate(); continue;
container.MakeBoundsChangeUndoable(false);
container.Width = defaultSize.Width;
container.Height = defaultSize.Height;
container.Invalidate();
} }
Size defaultSize = container.DefaultSize;
container.Invalidate();
container.MakeBoundsChangeUndoable(false);
container.Width = defaultSize.Width;
container.Height = defaultSize.Height;
container.Invalidate();
} }
}; };
menu.Items.Add(item); menu.Items.Add(item);
@ -500,11 +515,13 @@ namespace Greenshot.Drawing {
public virtual void ShowContextMenu(MouseEventArgs e, Surface surface) { public virtual void ShowContextMenu(MouseEventArgs e, Surface surface) {
bool hasMenu = false; bool hasMenu = false;
foreach (DrawableContainer container in this) { foreach (var drawableContainer in this) {
if (container.hasContextMenu) { var container = (DrawableContainer) drawableContainer;
hasMenu = true; if (!container.hasContextMenu) {
break; continue;
} }
hasMenu = true;
break;
} }
if (hasMenu) { if (hasMenu) {
ContextMenuStrip menu = new ContextMenuStrip(); ContextMenuStrip menu = new ContextMenuStrip();

View file

@ -107,9 +107,8 @@ namespace Greenshot.Drawing {
return path.IsOutlineVisible(x, y, pen); return path.IsOutlineVisible(x, y, pen);
} }
} }
} else {
return false;
} }
return false;
} }
} }
} }

View file

@ -31,15 +31,16 @@ namespace Greenshot.Drawing.Fields.Binding {
public object convert(object o) { public object convert(object o) {
if(o == null) { if(o == null) {
return null; return null;
} else if(o is T1) {
return convert((T1)o);
} else if(o is T2) {
return convert((T2)o);
} else {
throw new ArgumentException("Cannot handle argument of type "+o.GetType());
} }
if(o is T1) {
return convert((T1)o);
}
if(o is T2) {
return convert((T2)o);
}
throw new ArgumentException("Cannot handle argument of type "+o.GetType());
} }
protected abstract T2 convert(T1 o); protected abstract T2 convert(T1 o);
protected abstract T1 convert(T2 o); protected abstract T1 convert(T2 o);

View file

@ -228,9 +228,8 @@ namespace Greenshot.Drawing {
int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS)); int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS));
int safetymargin = 10; int safetymargin = 10;
return new Rectangle((myBounds.Left + Left) - (safetymargin+lineThickness), (myBounds.Top + Top) - (safetymargin+lineThickness), myBounds.Width + (2*(lineThickness+safetymargin)), myBounds.Height + (2*(lineThickness+safetymargin))); return new Rectangle((myBounds.Left + Left) - (safetymargin+lineThickness), (myBounds.Top + Top) - (safetymargin+lineThickness), myBounds.Width + (2*(lineThickness+safetymargin)), myBounds.Height + (2*(lineThickness+safetymargin)));
} else {
return new Rectangle(0, 0, parent.Width, parent.Height);
} }
return new Rectangle(0, 0, parent.Width, parent.Height);
} }
} }

View file

@ -29,34 +29,35 @@ namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// Description of ObfuscateContainer. /// Description of ObfuscateContainer.
/// </summary> /// </summary>
[Serializable()] [Serializable]
public class HighlightContainer : FilterContainer { public class HighlightContainer : FilterContainer {
public HighlightContainer(Surface parent) : base(parent) { public HighlightContainer(Surface parent) : base(parent) {
AddField(GetType(), FieldType.LINE_THICKNESS, 0); AddField(GetType(), FieldType.LINE_THICKNESS, 0);
AddField(GetType(), FieldType.LINE_COLOR, Color.Red); AddField(GetType(), FieldType.LINE_COLOR, Color.Red);
AddField(GetType(), FieldType.SHADOW, false); AddField(GetType(), FieldType.SHADOW, false);
AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT); AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT);
init(); Init();
} }
[OnDeserialized()] [OnDeserialized]
private void OnDeserialized(StreamingContext context) { private void OnDeserialized(StreamingContext context) {
init(); Init();
} }
private void init() { private void Init() {
FieldChanged += HighlightContainer_OnFieldChanged; FieldChanged += HighlightContainer_OnFieldChanged;
ConfigurePreparedFilters(); ConfigurePreparedFilters();
} }
protected void HighlightContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { protected void HighlightContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) {
if(sender.Equals(this)) { if (!sender.Equals(this)) {
if (e.Field.FieldType == FieldType.PREPARED_FILTER_HIGHLIGHT) { return;
ConfigurePreparedFilters(); }
} if (e.Field.FieldType == FieldType.PREPARED_FILTER_HIGHLIGHT) {
ConfigurePreparedFilters();
} }
} }
private void ConfigurePreparedFilters() { private void ConfigurePreparedFilters() {
PreparedFilter preset = (PreparedFilter)GetFieldValue(FieldType.PREPARED_FILTER_HIGHLIGHT); PreparedFilter preset = (PreparedFilter)GetFieldValue(FieldType.PREPARED_FILTER_HIGHLIGHT);
while(Filters.Count>0) { while(Filters.Count>0) {

View file

@ -29,7 +29,7 @@ namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// Description of IconContainer. /// Description of IconContainer.
/// </summary> /// </summary>
[Serializable()] [Serializable]
public class IconContainer : DrawableContainer, IIconContainer { public class IconContainer : DrawableContainer, IIconContainer {
private static ILog LOG = LogManager.GetLogger(typeof(IconContainer)); private static ILog LOG = LogManager.GetLogger(typeof(IconContainer));

View file

@ -32,7 +32,7 @@ namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// Description of BitmapContainer. /// Description of BitmapContainer.
/// </summary> /// </summary>
[Serializable()] [Serializable]
public class ImageContainer : DrawableContainer, IImageContainer { public class ImageContainer : DrawableContainer, IImageContainer {
private static ILog LOG = LogManager.GetLogger(typeof(ImageContainer)); private static ILog LOG = LogManager.GetLogger(typeof(ImageContainer));
@ -43,14 +43,14 @@ namespace Greenshot.Drawing {
/// Do not serialize, as the shadow is recreated from the original bitmap if it's not available /// Do not serialize, as the shadow is recreated from the original bitmap if it's not available
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
private Image shadowBitmap = null; private Image _shadowBitmap;
/// <summary> /// <summary>
/// This is the offset for the shadow version of the bitmap /// This is the offset for the shadow version of the bitmap
/// Do not serialize, as the offset is recreated /// Do not serialize, as the offset is recreated
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
private Point shadowOffset = new Point(-1, -1); private Point _shadowOffset = new Point(-1, -1);
public ImageContainer(Surface parent, string filename) : this(parent) { public ImageContainer(Surface parent, string filename) : this(parent) {
Load(filename); Load(filename);
@ -72,17 +72,17 @@ namespace Greenshot.Drawing {
public void ChangeShadowField() { public void ChangeShadowField() {
bool shadow = GetFieldValueAsBool(FieldType.SHADOW); bool shadow = GetFieldValueAsBool(FieldType.SHADOW);
if (shadow) { if (shadow) {
CheckShadow(shadow); CheckShadow(true);
Width = shadowBitmap.Width; Width = _shadowBitmap.Width;
Height = shadowBitmap.Height; Height = _shadowBitmap.Height;
Left = Left - shadowOffset.X; Left = Left - _shadowOffset.X;
Top = Top - shadowOffset.Y; Top = Top - _shadowOffset.Y;
} else { } else {
Width = image.Width; Width = image.Width;
Height = image.Height; Height = image.Height;
if (shadowBitmap != null) { if (_shadowBitmap != null) {
Left = Left + shadowOffset.X; Left = Left + _shadowOffset.X;
Top = Top + shadowOffset.Y; Top = Top + _shadowOffset.Y;
} }
} }
} }
@ -90,7 +90,7 @@ namespace Greenshot.Drawing {
public Image Image { public Image Image {
set { set {
// Remove all current bitmaps // Remove all current bitmaps
disposeImages(); DisposeImages();
image = ImageHelper.Clone(value); image = ImageHelper.Clone(value);
bool shadow = GetFieldValueAsBool(FieldType.SHADOW); bool shadow = GetFieldValueAsBool(FieldType.SHADOW);
CheckShadow(shadow); CheckShadow(shadow);
@ -98,10 +98,10 @@ namespace Greenshot.Drawing {
Width = image.Width; Width = image.Width;
Height = image.Height; Height = image.Height;
} else { } else {
Width = shadowBitmap.Width; Width = _shadowBitmap.Width;
Height = shadowBitmap.Height; Height = _shadowBitmap.Height;
Left = Left - shadowOffset.X; Left = Left - _shadowOffset.X;
Top = Top - shadowOffset.Y; Top = Top - _shadowOffset.Y;
} }
} }
get { return image; } get { return image; }
@ -115,22 +115,22 @@ namespace Greenshot.Drawing {
/// <param name="disposing"></param> /// <param name="disposing"></param>
protected override void Dispose(bool disposing) { protected override void Dispose(bool disposing) {
if (disposing) { if (disposing) {
disposeImages(); DisposeImages();
} }
image = null; image = null;
shadowBitmap = null; _shadowBitmap = null;
base.Dispose(disposing); base.Dispose(disposing);
} }
private void disposeImages() { private void DisposeImages() {
if (image != null) { if (image != null) {
image.Dispose(); image.Dispose();
} }
if (shadowBitmap != null) { if (_shadowBitmap != null) {
shadowBitmap.Dispose(); _shadowBitmap.Dispose();
} }
image = null; image = null;
shadowBitmap = null; _shadowBitmap = null;
} }
/// <summary> /// <summary>
@ -153,10 +153,10 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="rotateFlipType"></param> /// <param name="rotateFlipType"></param>
public override void Rotate(RotateFlipType rotateFlipType) { public override void Rotate(RotateFlipType rotateFlipType) {
Image newImage = ImageHelper.RotateFlip((Bitmap)image, rotateFlipType); Image newImage = ImageHelper.RotateFlip(image, rotateFlipType);
if (newImage != null) { if (newImage != null) {
// Remove all current bitmaps, also the shadow (will be recreated) // Remove all current bitmaps, also the shadow (will be recreated)
disposeImages(); DisposeImages();
image = newImage; image = newImage;
} }
base.Rotate(rotateFlipType); base.Rotate(rotateFlipType);
@ -167,8 +167,8 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="shadow"></param> /// <param name="shadow"></param>
private void CheckShadow(bool shadow) { private void CheckShadow(bool shadow) {
if (shadow && shadowBitmap == null) { if (shadow && _shadowBitmap == null) {
shadowBitmap = ImageHelper.ApplyEffect(image, new DropShadowEffect(), out shadowOffset); _shadowBitmap = ImageHelper.ApplyEffect(image, new DropShadowEffect(), out _shadowOffset);
} }
} }
@ -186,8 +186,8 @@ namespace Greenshot.Drawing {
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
if (shadow) { if (shadow) {
CheckShadow(shadow); CheckShadow(true);
graphics.DrawImage(shadowBitmap, Bounds); graphics.DrawImage(_shadowBitmap, Bounds);
} else { } else {
graphics.DrawImage(image, Bounds); graphics.DrawImage(image, Bounds);
} }

View file

@ -104,9 +104,8 @@ namespace Greenshot.Drawing {
return path.IsOutlineVisible(x, y, pen); return path.IsOutlineVisible(x, y, pen);
} }
} }
} else {
return false;
} }
return false;
} }
protected override ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() { protected override ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() {

View file

@ -27,19 +27,19 @@ namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// Description of ObfuscateContainer. /// Description of ObfuscateContainer.
/// </summary> /// </summary>
[Serializable()] [Serializable]
public class ObfuscateContainer : FilterContainer { public class ObfuscateContainer : FilterContainer {
public ObfuscateContainer(Surface parent) : base(parent) { public ObfuscateContainer(Surface parent) : base(parent) {
AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE); AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE);
init(); Init();
} }
[OnDeserialized()] [OnDeserialized]
private void OnDeserialized(StreamingContext context) { private void OnDeserialized(StreamingContext context) {
init(); Init();
} }
private void init() { private void Init() {
FieldChanged += ObfuscateContainer_OnFieldChanged; FieldChanged += ObfuscateContainer_OnFieldChanged;
ConfigurePreparedFilters(); ConfigurePreparedFilters();
} }

View file

@ -110,9 +110,8 @@ namespace Greenshot.Drawing {
return path.IsOutlineVisible(x, y, pen); return path.IsOutlineVisible(x, y, pen);
} }
} }
} else {
return false;
} }
return false;
} }
} }
} }

View file

@ -534,9 +534,8 @@ namespace Greenshot.Drawing {
get { get {
if (CanUndo) { if (CanUndo) {
return undoStack.Peek().ActionLanguageKey; return undoStack.Peek().ActionLanguageKey;
} else {
return LangKey.none;
} }
return LangKey.none;
} }
} }
@ -547,9 +546,8 @@ namespace Greenshot.Drawing {
get { get {
if (CanRedo) { if (CanRedo) {
return redoStack.Peek().ActionLanguageKey; return redoStack.Peek().ActionLanguageKey;
} else {
return LangKey.none;
} }
return LangKey.none;
} }
} }
@ -1186,7 +1184,7 @@ namespace Greenshot.Drawing {
return; return;
} }
if (elements.hasIntersectingFilters(clipRectangle)) { if (elements.HasIntersectingFilters(clipRectangle)) {
if (buffer != null) { if (buffer != null) {
if (buffer.Width != Image.Width || buffer.Height != Image.Height || buffer.PixelFormat != Image.PixelFormat) { if (buffer.Width != Image.Width || buffer.Height != Image.Height || buffer.PixelFormat != Image.PixelFormat) {
buffer.Dispose(); buffer.Dispose();

View file

@ -40,7 +40,7 @@ namespace Greenshot.Drawing {
private bool fontInvalidated = true; private bool fontInvalidated = true;
// If makeUndoable is true the next text-change will make the change undoable. // If makeUndoable is true the next text-change will make the change undoable.
// This is set to true AFTER the first change is made, as there is already a "add element" on the undo stack // This is set to true AFTER the first change is made, as there is already a "add element" on the undo stack
private bool makeUndoable = false; private bool makeUndoable;
private Font font; private Font font;
/// <summary> /// <summary>

View file

@ -77,7 +77,11 @@ namespace Greenshot {
LOG.Info("Starting: " + EnvironmentInfo.EnvironmentToString(false)); LOG.Info("Starting: " + EnvironmentInfo.EnvironmentToString(false));
// Upgrade if needed // Upgrade if needed
AppConfig.UpgradeToIni(); try {
AppConfig.UpgradeToIni();
} catch {
LOG.Warn("Couldn't upgrade the config.dat to geenshot.ini.");
}
// Read configuration // Read configuration
_conf = IniConfig.GetIniSection<CoreConfiguration>(); _conf = IniConfig.GetIniSection<CoreConfiguration>();
@ -274,7 +278,7 @@ namespace Greenshot {
transport.AddCommand(CommandEnum.FirstLaunch); transport.AddCommand(CommandEnum.FirstLaunch);
} }
new MainForm(transport); _instance = new MainForm(transport);
Application.Run(); Application.Run();
} catch(Exception ex) { } catch(Exception ex) {
LOG.Error("Exception in startup.", ex); LOG.Error("Exception in startup.", ex);
@ -443,13 +447,15 @@ namespace Greenshot {
notifyIcon.BalloonTipClicked += balloonTipClickedHandler; notifyIcon.BalloonTipClicked += balloonTipClickedHandler;
notifyIcon.BalloonTipClosed += balloonTipClosedHandler; notifyIcon.BalloonTipClosed += balloonTipClosedHandler;
notifyIcon.ShowBalloonTip(2000, "Greenshot", Language.GetFormattedString(LangKey.tooltip_firststart, HotkeyControl.GetLocalizedHotkeyStringFromString(_conf.RegionHotkey)), ToolTipIcon.Info); notifyIcon.ShowBalloonTip(2000, "Greenshot", Language.GetFormattedString(LangKey.tooltip_firststart, HotkeyControl.GetLocalizedHotkeyStringFromString(_conf.RegionHotkey)), ToolTipIcon.Info);
} catch {} } catch (Exception ex) {
LOG.Warn("Exception while showing first launch: ", ex);
}
break; break;
case CommandEnum.ReloadConfig: case CommandEnum.ReloadConfig:
LOG.Info("Reload requested"); LOG.Info("Reload requested");
try { try {
IniConfig.Reload(); IniConfig.Reload();
Invoke((MethodInvoker)delegate { Invoke((MethodInvoker) delegate {
// Even update language when needed // Even update language when needed
UpdateUI(); UpdateUI();
// Update the hotkey // Update the hotkey
@ -457,7 +463,9 @@ namespace Greenshot {
HotkeyControl.UnregisterHotkeys(); HotkeyControl.UnregisterHotkeys();
RegisterHotkeys(); RegisterHotkeys();
}); });
} catch {} } catch (Exception ex) {
LOG.Warn("Exception while reloading configuration: ", ex);
}
break; break;
case CommandEnum.OpenFile: case CommandEnum.OpenFile:
string filename = command.Value; string filename = command.Value;
@ -508,9 +516,8 @@ namespace Greenshot {
} }
failedKeys.Append(hotkeyString); failedKeys.Append(hotkeyString);
return false; return false;
} else {
LOG.DebugFormat("Registered {0} to hotkey: {1}", functionName, hotkeyString);
} }
LOG.DebugFormat("Registered {0} to hotkey: {1}", functionName, hotkeyString);
} else { } else {
LOG.InfoFormat("Skipping hotkey registration for {0}, no hotkey set!", functionName); LOG.InfoFormat("Skipping hotkey registration for {0}, no hotkey set!", functionName);
} }
@ -522,7 +529,7 @@ namespace Greenshot {
try { try {
bool success = RegisterHotkey(failedKeys, functionName, hotkeyValue.Value.ToString(), handler); bool success = RegisterHotkey(failedKeys, functionName, hotkeyValue.Value.ToString(), handler);
if (!success && ignoreFailedRegistration) { if (!success && ignoreFailedRegistration) {
LOG.DebugFormat("Ignoring failed hotkey registration, resetting to 'None'.", functionName, hotkeyValue); LOG.DebugFormat("Ignoring failed hotkey registration for {0}, with value '{1}', resetting to 'None'.", functionName, hotkeyValue);
_conf.Values[configurationKey].Value = Keys.None.ToString(); _conf.Values[configurationKey].Value = Keys.None.ToString();
_conf.IsDirty = true; _conf.IsDirty = true;
} }
@ -580,7 +587,9 @@ namespace Greenshot {
success = HandleFailedHotkeyRegistration(failedKeys.ToString()); success = HandleFailedHotkeyRegistration(failedKeys.ToString());
} else { } else {
// if failures have been ignored, the config has probably been updated // if failures have been ignored, the config has probably been updated
if (_conf.IsDirty) IniConfig.Save(); if (_conf.IsDirty) {
IniConfig.Save();
}
} }
} }
return success || ignoreFailedRegistration; return success || ignoreFailedRegistration;
@ -641,12 +650,8 @@ namespace Greenshot {
CaptureHelper.CaptureRegion(true); CaptureHelper.CaptureRegion(true);
} }
void CaptureClipboard() {
CaptureHelper.CaptureClipboard();
}
void CaptureFile() { void CaptureFile() {
OpenFileDialog openFileDialog = new OpenFileDialog(); var openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Image files (*.greenshot, *.png, *.jpg, *.gif, *.bmp, *.ico, *.tiff, *.wmf)|*.greenshot; *.png; *.jpg; *.jpeg; *.gif; *.bmp; *.ico; *.tiff; *.tif; *.wmf"; openFileDialog.Filter = "Image files (*.greenshot, *.png, *.jpg, *.gif, *.bmp, *.ico, *.tiff, *.wmf)|*.greenshot; *.png; *.jpg; *.jpeg; *.gif; *.bmp; *.ico; *.tiff; *.tif; *.wmf";
if (openFileDialog.ShowDialog() == DialogResult.OK) { if (openFileDialog.ShowDialog() == DialogResult.OK) {
if (File.Exists(openFileDialog.FileName)) { if (File.Exists(openFileDialog.FileName)) {
@ -739,12 +744,7 @@ namespace Greenshot {
title = title.Substring(0, Math.Min(title.Length, _conf.MaxMenuItemLength)); title = title.Substring(0, Math.Min(title.Length, _conf.MaxMenuItemLength));
} }
ToolStripItem captureIETabItem = contextmenu_captureiefromlist.DropDownItems.Add(title); ToolStripItem captureIETabItem = contextmenu_captureiefromlist.DropDownItems.Add(title);
int index; int index = counter.ContainsKey(tabData.Key) ? counter[tabData.Key] : 0;
if (counter.ContainsKey(tabData.Key)) {
index = counter[tabData.Key];
} else {
index = 0;
}
captureIETabItem.Image = tabData.Key.DisplayIcon; captureIETabItem.Image = tabData.Key.DisplayIcon;
captureIETabItem.Tag = new KeyValuePair<WindowDetails, int>(tabData.Key, index++); captureIETabItem.Tag = new KeyValuePair<WindowDetails, int>(tabData.Key, index++);
captureIETabItem.Click += Contextmenu_captureiefromlist_Click; captureIETabItem.Click += Contextmenu_captureiefromlist_Click;

View file

@ -75,7 +75,7 @@ namespace Greenshot.Help
return res.StatusCode; return res.StatusCode;
} catch(WebException e) { } catch(WebException e) {
if(e.Response != null) return ((HttpWebResponse)e.Response).StatusCode; if(e.Response != null) return ((HttpWebResponse)e.Response).StatusCode;
else return null; return null;
} }
} }
} }

View file

@ -278,7 +278,8 @@ namespace Greenshot.Helpers {
returnDocument2 = document2; returnDocument2 = document2;
returnWindow = new WindowDetails(contentWindowHandle); returnWindow = new WindowDetails(contentWindowHandle);
break; break;
} else if (ieAccessible != null && returnWindow == null && document2.title.Equals(ieAccessible.IEActiveTabCaption) ) { }
if (ieAccessible != null && returnWindow == null && document2.title.Equals(ieAccessible.IEActiveTabCaption) ) {
LOG.DebugFormat("Title: {0}", document2.title); LOG.DebugFormat("Title: {0}", document2.title);
returnDocument2 = document2; returnDocument2 = document2;
returnWindow = new WindowDetails(contentWindowHandle); returnWindow = new WindowDetails(contentWindowHandle);

View file

@ -287,22 +287,21 @@ namespace Greenshot.Helpers {
LOG.InfoFormat("Skipping (as the duplicate is newer or same version) the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); LOG.InfoFormat("Skipping (as the duplicate is newer or same version) the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
} }
continue; continue;
} else {
if (conf.ExcludePlugins != null && conf.ExcludePlugins.Contains(pluginAttribute.Name)) {
LOG.WarnFormat("Exclude list: {0}", conf.ExcludePlugins.ToArray());
LOG.WarnFormat("Skipping the excluded plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
continue;
}
if (conf.IncludePlugins != null && conf.IncludePlugins.Count > 0 && !conf.IncludePlugins.Contains(pluginAttribute.Name)) {
// Whitelist is set
LOG.WarnFormat("Include list: {0}", conf.IncludePlugins.ToArray());
LOG.WarnFormat("Skipping the not included plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
continue;
}
LOG.InfoFormat("Loading the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
tmpAttributes[pluginAttribute.Name] = pluginAttribute;
tmpAssemblies[pluginAttribute.Name] = assembly;
} }
if (conf.ExcludePlugins != null && conf.ExcludePlugins.Contains(pluginAttribute.Name)) {
LOG.WarnFormat("Exclude list: {0}", conf.ExcludePlugins.ToArray());
LOG.WarnFormat("Skipping the excluded plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
continue;
}
if (conf.IncludePlugins != null && conf.IncludePlugins.Count > 0 && !conf.IncludePlugins.Contains(pluginAttribute.Name)) {
// Whitelist is set
LOG.WarnFormat("Include list: {0}", conf.IncludePlugins.ToArray());
LOG.WarnFormat("Skipping the not included plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
continue;
}
LOG.InfoFormat("Loading the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile);
tmpAttributes[pluginAttribute.Name] = pluginAttribute;
tmpAssemblies[pluginAttribute.Name] = assembly;
} else { } else {
LOG.ErrorFormat("Can't find the needed Plugin Attribute ({0}) in the assembly of the file \"{1}\", skipping this file.", typeof(PluginAttribute), pluginFile); LOG.ErrorFormat("Can't find the needed Plugin Attribute ({0}) in the assembly of the file \"{1}\", skipping this file.", typeof(PluginAttribute), pluginFile);
} }

View file

@ -58,9 +58,8 @@ namespace Greenshot.Experimental {
if (DateTime.Now.CompareTo(checkTime) < 0) { if (DateTime.Now.CompareTo(checkTime) < 0) {
LOG.DebugFormat("No need to check RSS feed for updates, feed check will be after {0}", checkTime); LOG.DebugFormat("No need to check RSS feed for updates, feed check will be after {0}", checkTime);
return false; return false;
} else {
LOG.DebugFormat("Update check is due, last check was {0} check needs to be made after {1} (which is one {2} later)", conf.LastUpdateCheck, checkTime, conf.UpdateCheckInterval);
} }
LOG.DebugFormat("Update check is due, last check was {0} check needs to be made after {1} (which is one {2} later)", conf.LastUpdateCheck, checkTime, conf.UpdateCheckInterval);
} }
} }
return true; return true;

View file

@ -87,7 +87,7 @@ namespace GreenshotPlugin.Controls {
/// Initialize the animation /// Initialize the animation
/// </summary> /// </summary>
protected AnimatingForm() { protected AnimatingForm() {
this.Load += delegate { Load += delegate {
if (EnableAnimation) { if (EnableAnimation) {
timer = new Timer(); timer = new Timer();
timer.Interval = 1000 / VRefresh; timer.Interval = 1000 / VRefresh;
@ -97,7 +97,7 @@ namespace GreenshotPlugin.Controls {
}; };
// Unregister at close // Unregister at close
this.FormClosing += delegate { FormClosing += delegate {
if (timer != null) { if (timer != null) {
timer.Stop(); timer.Stop();
} }

View file

@ -22,6 +22,7 @@ using System;
using System.Drawing; using System.Drawing;
using System.Threading; using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using GreenshotPlugin.Core;
namespace GreenshotPlugin.Controls { namespace GreenshotPlugin.Controls {
/// <summary> /// <summary>
@ -31,7 +32,7 @@ namespace GreenshotPlugin.Controls {
private volatile bool shouldClose = false; private volatile bool shouldClose = false;
private void BackgroundShowDialog() { private void BackgroundShowDialog() {
this.ShowDialog(); ShowDialog();
} }
public static BackgroundForm ShowAndWait(string title, string text) { public static BackgroundForm ShowAndWait(string title, string text) {
@ -50,11 +51,11 @@ namespace GreenshotPlugin.Controls {
// The InitializeComponent() call is required for Windows Forms designer support. // The InitializeComponent() call is required for Windows Forms designer support.
// //
InitializeComponent(); InitializeComponent();
this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); Icon = GreenshotResources.getGreenshotIcon();
shouldClose = false; shouldClose = false;
this.Text = title; Text = title;
this.label_pleasewait.Text = text; label_pleasewait.Text = text;
this.FormClosing += PreventFormClose; FormClosing += PreventFormClose;
timer_checkforclose.Start(); timer_checkforclose.Start();
} }
@ -65,12 +66,12 @@ namespace GreenshotPlugin.Controls {
foreach(Screen screen in Screen.AllScreens) { foreach(Screen screen in Screen.AllScreens) {
if (screen.Bounds.Contains(Cursor.Position)) { if (screen.Bounds.Contains(Cursor.Position)) {
positioned = true; positioned = true;
this.Location = new Point(screen.Bounds.X + (screen.Bounds.Width / 2) - (this.Width / 2), screen.Bounds.Y + (screen.Bounds.Height / 2) - (this.Height / 2)); Location = new Point(screen.Bounds.X + (screen.Bounds.Width / 2) - (Width / 2), screen.Bounds.Y + (screen.Bounds.Height / 2) - (Height / 2));
break; break;
} }
} }
if (!positioned) { if (!positioned) {
this.Location = new Point(Cursor.Position.X - this.Width / 2, Cursor.Position.Y - this.Height / 2); Location = new Point(Cursor.Position.X - Width / 2, Cursor.Position.Y - Height / 2);
} }
} }
@ -83,7 +84,7 @@ namespace GreenshotPlugin.Controls {
private void Timer_checkforcloseTick(object sender, EventArgs e) { private void Timer_checkforcloseTick(object sender, EventArgs e) {
if (shouldClose) { if (shouldClose) {
timer_checkforclose.Stop(); timer_checkforclose.Stop();
this.BeginInvoke(new EventHandler( delegate {this.Close();})); BeginInvoke(new EventHandler( delegate {Close();}));
} }
} }

View file

@ -45,7 +45,7 @@ namespace GreenshotPlugin.Controls {
} }
public GreenshotComboBox() { public GreenshotComboBox() {
this.SelectedIndexChanged += delegate { SelectedIndexChanged += delegate {
StoreSelectedEnum(); StoreSelectedEnum();
}; };
} }
@ -53,7 +53,7 @@ namespace GreenshotPlugin.Controls {
public void SetValue(Enum currentValue) { public void SetValue(Enum currentValue) {
if (currentValue != null) { if (currentValue != null) {
selectedEnum = currentValue; selectedEnum = currentValue;
this.SelectedItem = Language.Translate(currentValue); SelectedItem = Language.Translate(currentValue);
} }
} }
@ -67,10 +67,10 @@ namespace GreenshotPlugin.Controls {
this.enumType = enumType; this.enumType = enumType;
var availableValues = Enum.GetValues(enumType); var availableValues = Enum.GetValues(enumType);
this.Items.Clear(); Items.Clear();
string enumTypeName = enumType.Name; string enumTypeName = enumType.Name;
foreach (var enumValue in availableValues) { foreach (var enumValue in availableValues) {
this.Items.Add(Language.Translate((Enum)enumValue)); Items.Add(Language.Translate((Enum)enumValue));
} }
} }
@ -79,7 +79,7 @@ namespace GreenshotPlugin.Controls {
/// </summary> /// </summary>
private void StoreSelectedEnum() { private void StoreSelectedEnum() {
string enumTypeName = enumType.Name; string enumTypeName = enumType.Name;
string selectedValue = this.SelectedItem as string; string selectedValue = SelectedItem as string;
var availableValues = Enum.GetValues(enumType); var availableValues = Enum.GetValues(enumType);
object returnValue = null; object returnValue = null;

View file

@ -27,13 +27,14 @@ using Greenshot.IniFile;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.Design; using System.ComponentModel.Design;
using System.IO; using System.IO;
using log4net;
namespace GreenshotPlugin.Controls { namespace GreenshotPlugin.Controls {
/// <summary> /// <summary>
/// This form is used for automatically binding the elements of the form to the language /// This form is used for automatically binding the elements of the form to the language
/// </summary> /// </summary>
public class GreenshotForm : Form, IGreenshotLanguageBindable { public class GreenshotForm : Form, IGreenshotLanguageBindable {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(GreenshotForm)); private static ILog LOG = LogManager.GetLogger(typeof(GreenshotForm));
protected static CoreConfiguration coreConfiguration; protected static CoreConfiguration coreConfiguration;
private static IDictionary<Type, FieldInfo[]> reflectionCache = new Dictionary<Type, FieldInfo[]>(); private static IDictionary<Type, FieldInfo[]> reflectionCache = new Dictionary<Type, FieldInfo[]>();
private IComponentChangeService m_changeService; private IComponentChangeService m_changeService;
@ -87,7 +88,7 @@ namespace GreenshotPlugin.Controls {
/// Code to initialize the language etc during design time /// Code to initialize the language etc during design time
/// </summary> /// </summary>
protected void InitializeForDesigner() { protected void InitializeForDesigner() {
if (this.DesignMode) { if (DesignMode) {
designTimeControls = new Dictionary<string, Control>(); designTimeControls = new Dictionary<string, Control>();
designTimeToolStripItems = new Dictionary<string, ToolStripItem>(); designTimeToolStripItems = new Dictionary<string, ToolStripItem>();
try { try {
@ -97,7 +98,7 @@ namespace GreenshotPlugin.Controls {
// Language.AddLanguageFilePath(@"C:\Greenshot\Greenshot\Languages"); // Language.AddLanguageFilePath(@"C:\Greenshot\Greenshot\Languages");
// this "type" // this "type"
Assembly currentAssembly = this.GetType().Assembly; Assembly currentAssembly = GetType().Assembly;
string assemblyPath = typeResService.GetPathOfAssembly(currentAssembly.GetName()); string assemblyPath = typeResService.GetPathOfAssembly(currentAssembly.GetName());
string assemblyDirectory = Path.GetDirectoryName(assemblyPath); string assemblyDirectory = Path.GetDirectoryName(assemblyPath);
if (!Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\Greenshot\Languages\"))) { if (!Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\Greenshot\Languages\"))) {
@ -117,7 +118,7 @@ namespace GreenshotPlugin.Controls {
/// </summary> /// </summary>
/// <param name="e"></param> /// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e) { protected override void OnPaint(PaintEventArgs e) {
if (this.DesignMode) { if (DesignMode) {
if (!isDesignModeLanguageSet) { if (!isDesignModeLanguageSet) {
isDesignModeLanguageSet = true; isDesignModeLanguageSet = true;
try { try {
@ -130,7 +131,7 @@ namespace GreenshotPlugin.Controls {
} }
protected override void OnLoad(EventArgs e) { protected override void OnLoad(EventArgs e) {
if (!this.DesignMode) { if (!DesignMode) {
if (!applyLanguageManually) { if (!applyLanguageManually) {
ApplyLanguage(); ApplyLanguage();
} }
@ -149,7 +150,7 @@ namespace GreenshotPlugin.Controls {
/// </summary> /// </summary>
/// <param name="e"></param> /// <param name="e"></param>
protected override void OnClosed(EventArgs e) { protected override void OnClosed(EventArgs e) {
if (!this.DesignMode && !storeFieldsManually) { if (!DesignMode && !storeFieldsManually) {
if (DialogResult == DialogResult.OK) { if (DialogResult == DialogResult.OK) {
LOG.Info("Form was closed with OK: storing field values."); LOG.Info("Form was closed with OK: storing field values.");
StoreFields(); StoreFields();
@ -267,7 +268,7 @@ namespace GreenshotPlugin.Controls {
applyTo.Text = langString; applyTo.Text = langString;
return; return;
} }
if (!this.DesignMode) { if (!DesignMode) {
LOG.DebugFormat("Greenshot control without language key: {0}", applyTo.Name); LOG.DebugFormat("Greenshot control without language key: {0}", applyTo.Name);
} }
} }
@ -331,15 +332,15 @@ namespace GreenshotPlugin.Controls {
/// </summary> /// </summary>
protected void ApplyLanguage() { protected void ApplyLanguage() {
string langString = null; string langString = null;
this.SuspendLayout(); SuspendLayout();
try { try {
// Set title of the form // Set title of the form
if (!string.IsNullOrEmpty(LanguageKey) && Language.TryGetString(LanguageKey, out langString)) { if (!string.IsNullOrEmpty(LanguageKey) && Language.TryGetString(LanguageKey, out langString)) {
this.Text = langString; Text = langString;
} }
// Reset the text values for all GreenshotControls // Reset the text values for all GreenshotControls
foreach (FieldInfo field in GetCachedFields(this.GetType())) { foreach (FieldInfo field in GetCachedFields(GetType())) {
Object controlObject = field.GetValue(this); Object controlObject = field.GetValue(this);
if (controlObject == null) { if (controlObject == null) {
LOG.DebugFormat("No value: {0}", field.Name); LOG.DebugFormat("No value: {0}", field.Name);
@ -367,7 +368,7 @@ namespace GreenshotPlugin.Controls {
} }
} }
} finally { } finally {
this.ResumeLayout(); ResumeLayout();
} }
} }
@ -388,7 +389,7 @@ namespace GreenshotPlugin.Controls {
applyTo.Text = langString; applyTo.Text = langString;
return; return;
} }
if (!this.DesignMode) { if (!DesignMode) {
LOG.DebugFormat("Greenshot control without language key: {0}", applyTo.Name); LOG.DebugFormat("Greenshot control without language key: {0}", applyTo.Name);
} }
} }
@ -398,7 +399,7 @@ namespace GreenshotPlugin.Controls {
/// Fill all GreenshotControls with the values from the configuration /// Fill all GreenshotControls with the values from the configuration
/// </summary> /// </summary>
protected void FillFields() { protected void FillFields() {
foreach (FieldInfo field in GetCachedFields(this.GetType())) { foreach (FieldInfo field in GetCachedFields(GetType())) {
Object controlObject = field.GetValue(this); Object controlObject = field.GetValue(this);
if (controlObject == null) { if (controlObject == null) {
continue; continue;
@ -466,7 +467,7 @@ namespace GreenshotPlugin.Controls {
/// </summary> /// </summary>
protected void StoreFields() { protected void StoreFields() {
bool iniDirty = false; bool iniDirty = false;
foreach (FieldInfo field in GetCachedFields(this.GetType())) { foreach (FieldInfo field in GetCachedFields(GetType())) {
Object controlObject = field.GetValue(this); Object controlObject = field.GetValue(this);
if (controlObject == null) { if (controlObject == null) {
continue; continue;

View file

@ -26,6 +26,7 @@ using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.Plugin; using Greenshot.Plugin;
using log4net;
namespace GreenshotPlugin.Controls { namespace GreenshotPlugin.Controls {
/// <summary> /// <summary>
@ -34,7 +35,7 @@ namespace GreenshotPlugin.Controls {
/// But is modified to fit in Greenshot, and have localized support /// But is modified to fit in Greenshot, and have localized support
/// </summary> /// </summary>
public class HotkeyControl : GreenshotTextBox { public class HotkeyControl : GreenshotTextBox {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(HotkeyControl)); private static ILog LOG = LogManager.GetLogger(typeof(HotkeyControl));
// Holds the list of hotkeys // Holds the list of hotkeys
private static Dictionary<int, HotKeyHandler> keyHandlers = new Dictionary<int, HotKeyHandler>(); private static Dictionary<int, HotKeyHandler> keyHandlers = new Dictionary<int, HotKeyHandler>();
@ -120,13 +121,13 @@ namespace GreenshotPlugin.Controls {
/// Creates a new HotkeyControl /// Creates a new HotkeyControl
/// </summary> /// </summary>
public HotkeyControl() { public HotkeyControl() {
this.ContextMenu = dummy; // Disable right-clicking ContextMenu = dummy; // Disable right-clicking
this.Text = "None"; Text = "None";
// Handle events that occurs when keys are pressed // Handle events that occurs when keys are pressed
this.KeyPress += new KeyPressEventHandler(HotkeyControl_KeyPress); KeyPress += new KeyPressEventHandler(HotkeyControl_KeyPress);
this.KeyUp += new KeyEventHandler(HotkeyControl_KeyUp); KeyUp += new KeyEventHandler(HotkeyControl_KeyUp);
this.KeyDown += new KeyEventHandler(HotkeyControl_KeyDown); KeyDown += new KeyEventHandler(HotkeyControl_KeyDown);
// Fill the ArrayLists that contain all invalid hotkey combinations // Fill the ArrayLists that contain all invalid hotkey combinations
needNonShiftModifier = new ArrayList(); needNonShiftModifier = new ArrayList();
@ -183,8 +184,8 @@ namespace GreenshotPlugin.Controls {
/// Resets this hotkey control to None /// Resets this hotkey control to None
/// </summary> /// </summary>
public new void Clear() { public new void Clear() {
this.Hotkey = Keys.None; Hotkey = Keys.None;
this.HotkeyModifiers = Keys.None; HotkeyModifiers = Keys.None;
} }
/// <summary> /// <summary>
@ -197,8 +198,8 @@ namespace GreenshotPlugin.Controls {
ResetHotkey(); ResetHotkey();
return; return;
} else { } else {
this._modifiers = e.Modifiers; _modifiers = e.Modifiers;
this._hotkey = e.KeyCode; _hotkey = e.KeyCode;
Redraw(); Redraw();
} }
} }
@ -210,12 +211,12 @@ namespace GreenshotPlugin.Controls {
void HotkeyControl_KeyUp(object sender, KeyEventArgs e) { void HotkeyControl_KeyUp(object sender, KeyEventArgs e) {
// Somehow the PrintScreen only comes as a keyup, therefore we handle it here. // Somehow the PrintScreen only comes as a keyup, therefore we handle it here.
if (e.KeyCode == Keys.PrintScreen) { if (e.KeyCode == Keys.PrintScreen) {
this._modifiers = e.Modifiers; _modifiers = e.Modifiers;
this._hotkey = e.KeyCode; _hotkey = e.KeyCode;
Redraw(); Redraw();
} }
if (this._hotkey == Keys.None && Control.ModifierKeys == Keys.None) { if (_hotkey == Keys.None && ModifierKeys == Keys.None) {
ResetHotkey(); ResetHotkey();
return; return;
} }
@ -251,8 +252,8 @@ namespace GreenshotPlugin.Controls {
/// Clears the current hotkey and resets the TextBox /// Clears the current hotkey and resets the TextBox
/// </summary> /// </summary>
public void ResetHotkey() { public void ResetHotkey() {
this._hotkey = Keys.None; _hotkey = Keys.None;
this._modifiers = Keys.None; _modifiers = Keys.None;
Redraw(); Redraw();
} }
@ -261,10 +262,10 @@ namespace GreenshotPlugin.Controls {
/// </summary> /// </summary>
public Keys Hotkey { public Keys Hotkey {
get { get {
return this._hotkey; return _hotkey;
} }
set { set {
this._hotkey = value; _hotkey = value;
Redraw(true); Redraw(true);
} }
} }
@ -273,8 +274,8 @@ namespace GreenshotPlugin.Controls {
/// Used to get/set the hotkey (e.g. Keys.A) /// Used to get/set the hotkey (e.g. Keys.A)
/// </summary> /// </summary>
public void SetHotkey(string hotkey) { public void SetHotkey(string hotkey) {
this._hotkey = HotkeyFromString(hotkey); _hotkey = HotkeyFromString(hotkey);
this._modifiers = HotkeyModifiersFromString(hotkey); _modifiers = HotkeyModifiersFromString(hotkey);
Redraw(true); Redraw(true);
} }
@ -283,10 +284,10 @@ namespace GreenshotPlugin.Controls {
/// </summary> /// </summary>
public Keys HotkeyModifiers { public Keys HotkeyModifiers {
get { get {
return this._modifiers; return _modifiers;
} }
set { set {
this._modifiers = value; _modifiers = value;
Redraw(true); Redraw(true);
} }
} }
@ -304,52 +305,52 @@ namespace GreenshotPlugin.Controls {
/// <param name="bCalledProgramatically">Specifies whether this function was called by the Hotkey/HotkeyModifiers properties or by the user.</param> /// <param name="bCalledProgramatically">Specifies whether this function was called by the Hotkey/HotkeyModifiers properties or by the user.</param>
private void Redraw(bool bCalledProgramatically) { private void Redraw(bool bCalledProgramatically) {
// No hotkey set // No hotkey set
if (this._hotkey == Keys.None) { if (_hotkey == Keys.None) {
this.Text = ""; Text = "";
return; return;
} }
// LWin/RWin doesn't work as hotkeys (neither do they work as modifier keys in .NET 2.0) // LWin/RWin doesn't work as hotkeys (neither do they work as modifier keys in .NET 2.0)
if (this._hotkey == Keys.LWin || this._hotkey == Keys.RWin) { if (_hotkey == Keys.LWin || _hotkey == Keys.RWin) {
this.Text = ""; Text = "";
return; return;
} }
// Only validate input if it comes from the user // Only validate input if it comes from the user
if (bCalledProgramatically == false) { if (bCalledProgramatically == false) {
// No modifier or shift only, AND a hotkey that needs another modifier // No modifier or shift only, AND a hotkey that needs another modifier
if ((this._modifiers == Keys.Shift || this._modifiers == Keys.None) && this.needNonShiftModifier.Contains((int)this._hotkey)) { if ((_modifiers == Keys.Shift || _modifiers == Keys.None) && needNonShiftModifier.Contains((int)_hotkey)) {
if (this._modifiers == Keys.None) { if (_modifiers == Keys.None) {
// Set Ctrl+Alt as the modifier unless Ctrl+Alt+<key> won't work... // Set Ctrl+Alt as the modifier unless Ctrl+Alt+<key> won't work...
if (needNonAltGrModifier.Contains((int)this._hotkey) == false) { if (needNonAltGrModifier.Contains((int)_hotkey) == false) {
this._modifiers = Keys.Alt | Keys.Control; _modifiers = Keys.Alt | Keys.Control;
} else { } else {
// ... in that case, use Shift+Alt instead. // ... in that case, use Shift+Alt instead.
this._modifiers = Keys.Alt | Keys.Shift; _modifiers = Keys.Alt | Keys.Shift;
} }
} else { } else {
// User pressed Shift and an invalid key (e.g. a letter or a number), // User pressed Shift and an invalid key (e.g. a letter or a number),
// that needs another set of modifier keys // that needs another set of modifier keys
this._hotkey = Keys.None; _hotkey = Keys.None;
this.Text = ""; Text = "";
return; return;
} }
} }
// Check all Ctrl+Alt keys // Check all Ctrl+Alt keys
if ((this._modifiers == (Keys.Alt | Keys.Control)) && this.needNonAltGrModifier.Contains((int)this._hotkey)) { if ((_modifiers == (Keys.Alt | Keys.Control)) && needNonAltGrModifier.Contains((int)_hotkey)) {
// Ctrl+Alt+4 etc won't work; reset hotkey and tell the user // Ctrl+Alt+4 etc won't work; reset hotkey and tell the user
this._hotkey = Keys.None; _hotkey = Keys.None;
this.Text = ""; Text = "";
return; return;
} }
} }
// I have no idea why this is needed, but it is. Without this code, pressing only Ctrl // I have no idea why this is needed, but it is. Without this code, pressing only Ctrl
// will show up as "Control + ControlKey", etc. // will show up as "Control + ControlKey", etc.
if (this._hotkey == Keys.Menu /* Alt */ || this._hotkey == Keys.ShiftKey || this._hotkey == Keys.ControlKey) { if (_hotkey == Keys.Menu /* Alt */ || _hotkey == Keys.ShiftKey || _hotkey == Keys.ControlKey) {
this._hotkey = Keys.None; _hotkey = Keys.None;
} }
this.Text = HotkeyToLocalizedString(this._modifiers, this._hotkey); Text = HotkeyToLocalizedString(_modifiers, _hotkey);
} }
public override string ToString() { public override string ToString() {

View file

@ -27,13 +27,14 @@ using System.Windows.Forms;
using System.Web; using System.Web;
using System.Collections.Specialized; using System.Collections.Specialized;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using log4net;
namespace GreenshotPlugin.Controls { namespace GreenshotPlugin.Controls {
/// <summary> /// <summary>
/// The OAuthLoginForm is used to allow the user to authorize Greenshot with an "Oauth" application /// The OAuthLoginForm is used to allow the user to authorize Greenshot with an "Oauth" application
/// </summary> /// </summary>
public partial class OAuthLoginForm : Form { public partial class OAuthLoginForm : Form {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OAuthLoginForm)); private static readonly ILog LOG = LogManager.GetLogger(typeof(OAuthLoginForm));
private string callbackUrl = null; private string callbackUrl = null;
private IDictionary<string, string> callbackParameters = null; private IDictionary<string, string> callbackParameters = null;
@ -50,17 +51,17 @@ namespace GreenshotPlugin.Controls {
public OAuthLoginForm(string browserTitle, Size size, string authorizationLink, string callbackUrl) { public OAuthLoginForm(string browserTitle, Size size, string authorizationLink, string callbackUrl) {
this.callbackUrl = callbackUrl; this.callbackUrl = callbackUrl;
InitializeComponent(); InitializeComponent();
this.ClientSize = size; ClientSize = size;
this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); Icon = GreenshotResources.getGreenshotIcon();
this.Text = browserTitle; Text = browserTitle;
this.addressTextBox.Text = authorizationLink; addressTextBox.Text = authorizationLink;
// The script errors are suppressed by using the ExtendedWebBrowser // The script errors are suppressed by using the ExtendedWebBrowser
browser.ScriptErrorsSuppressed = false; browser.ScriptErrorsSuppressed = false;
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted); browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
browser.Navigate(new Uri(authorizationLink)); browser.Navigate(new Uri(authorizationLink));
WindowDetails.ToForeground(this.Handle); WindowDetails.ToForeground(Handle);
} }
private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
@ -69,7 +70,7 @@ namespace GreenshotPlugin.Controls {
} }
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
LOG.DebugFormat("Navigating to url: {0}", browser.Url); LOG.DebugFormat("Navigating to url: {0}", browser.Url);
this.addressTextBox.Text = e.Url.ToString(); addressTextBox.Text = e.Url.ToString();
} }
private void browser_Navigated(object sender, WebBrowserNavigatedEventArgs e) { private void browser_Navigated(object sender, WebBrowserNavigatedEventArgs e) {

View file

@ -23,13 +23,14 @@ using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using System.Threading; using System.Threading;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using log4net;
namespace GreenshotPlugin.Controls { namespace GreenshotPlugin.Controls {
/// <summary> /// <summary>
/// Description of PleaseWaitForm. /// Description of PleaseWaitForm.
/// </summary> /// </summary>
public partial class PleaseWaitForm : Form { public partial class PleaseWaitForm : Form {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PleaseWaitForm)); private static ILog LOG = LogManager.GetLogger(typeof(PleaseWaitForm));
private Thread waitFor = null; private Thread waitFor = null;
private string title; private string title;
public PleaseWaitForm() { public PleaseWaitForm() {
@ -37,7 +38,7 @@ namespace GreenshotPlugin.Controls {
// The InitializeComponent() call is required for Windows Forms designer support. // The InitializeComponent() call is required for Windows Forms designer support.
// //
InitializeComponent(); InitializeComponent();
this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); Icon = GreenshotResources.getGreenshotIcon();
} }
/// <summary> /// <summary>
@ -61,9 +62,9 @@ namespace GreenshotPlugin.Controls {
/// <param name="waitDelegate">delegate { with your code }</param> /// <param name="waitDelegate">delegate { with your code }</param>
public void ShowAndWait(string title, string text, ThreadStart waitDelegate) { public void ShowAndWait(string title, string text, ThreadStart waitDelegate) {
this.title = title; this.title = title;
this.Text = title; Text = title;
this.label_pleasewait.Text = text; label_pleasewait.Text = text;
this.cancelButton.Text = Language.GetString("CANCEL"); cancelButton.Text = Language.GetString("CANCEL");
// Make sure the form is shown. // Make sure the form is shown.
Show(); Show();

View file

@ -41,20 +41,20 @@ namespace GreenshotPlugin.Controls {
// The InitializeComponent() call is required for Windows Forms designer support. // The InitializeComponent() call is required for Windows Forms designer support.
// //
InitializeComponent(); InitializeComponent();
this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); Icon = GreenshotResources.getGreenshotIcon();
this.checkBox_reduceColors.Checked = Settings.ReduceColors; checkBox_reduceColors.Checked = Settings.ReduceColors;
this.trackBarJpegQuality.Enabled = OutputFormat.jpg.Equals(outputSettings.Format); trackBarJpegQuality.Enabled = OutputFormat.jpg.Equals(outputSettings.Format);
this.trackBarJpegQuality.Value = Settings.JPGQuality; trackBarJpegQuality.Value = Settings.JPGQuality;
this.textBoxJpegQuality.Enabled = OutputFormat.jpg.Equals(outputSettings.Format); textBoxJpegQuality.Enabled = OutputFormat.jpg.Equals(outputSettings.Format);
this.textBoxJpegQuality.Text = Settings.JPGQuality.ToString(); textBoxJpegQuality.Text = Settings.JPGQuality.ToString();
WindowDetails.ToForeground(Handle); WindowDetails.ToForeground(Handle);
} }
void Button_okClick(object sender, System.EventArgs e) { void Button_okClick(object sender, EventArgs e) {
Settings.JPGQuality = this.trackBarJpegQuality.Value; Settings.JPGQuality = trackBarJpegQuality.Value;
Settings.ReduceColors = checkBox_reduceColors.Checked; Settings.ReduceColors = checkBox_reduceColors.Checked;
if (this.checkbox_dontaskagain.Checked) { if (checkbox_dontaskagain.Checked) {
conf.OutputFileJpegQuality = Settings.JPGQuality; conf.OutputFileJpegQuality = Settings.JPGQuality;
conf.OutputFilePromptQuality = false; conf.OutputFilePromptQuality = false;
conf.OutputFileReduceColors = Settings.ReduceColors; conf.OutputFileReduceColors = Settings.ReduceColors;
@ -62,7 +62,7 @@ namespace GreenshotPlugin.Controls {
} }
} }
void TrackBarJpegQualityScroll(object sender, System.EventArgs e) { void TrackBarJpegQualityScroll(object sender, EventArgs e) {
textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(); textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString();
} }
} }

View file

@ -25,6 +25,7 @@ using System.Windows.Forms;
using Greenshot.Plugin; using Greenshot.Plugin;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.IniFile; using Greenshot.IniFile;
using log4net;
namespace GreenshotPlugin.Controls { namespace GreenshotPlugin.Controls {
/// <summary> /// <summary>
@ -32,7 +33,7 @@ namespace GreenshotPlugin.Controls {
/// For some reason SFD is sealed :( /// For some reason SFD is sealed :(
/// </summary> /// </summary>
public class SaveImageFileDialog : IDisposable { public class SaveImageFileDialog : IDisposable {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(SaveImageFileDialog)); private static ILog LOG = LogManager.GetLogger(typeof(SaveImageFileDialog));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
protected SaveFileDialog saveFileDialog; protected SaveFileDialog saveFileDialog;
private FilterOption[] filterOptions; private FilterOption[] filterOptions;
@ -137,7 +138,7 @@ namespace GreenshotPlugin.Controls {
get { get {
string fn = saveFileDialog.FileName; string fn = saveFileDialog.FileName;
// if the filename contains a valid extension, which is the same like the selected filter item's extension, the filename is okay // if the filename contains a valid extension, which is the same like the selected filter item's extension, the filename is okay
if(fn.EndsWith(Extension,System.StringComparison.CurrentCultureIgnoreCase)) return fn; if(fn.EndsWith(Extension,StringComparison.CurrentCultureIgnoreCase)) return fn;
// otherwise we just add the selected filter item's extension // otherwise we just add the selected filter item's extension
else return fn + "." + Extension; else return fn + "." + Extension;
} }
@ -156,7 +157,7 @@ namespace GreenshotPlugin.Controls {
} }
set { set {
for(int i=0; i<filterOptions.Length; i++) { for(int i=0; i<filterOptions.Length; i++) {
if(value.Equals(filterOptions[i].Extension, System.StringComparison.CurrentCultureIgnoreCase)) { if(value.Equals(filterOptions[i].Extension, StringComparison.CurrentCultureIgnoreCase)) {
saveFileDialog.FilterIndex = i + 1; saveFileDialog.FilterIndex = i + 1;
} }
} }

View file

@ -48,7 +48,7 @@ namespace GreenshotPlugin.Controls {
} }
// cleanup at close // cleanup at close
this.FormClosing += delegate { FormClosing += delegate {
UnregisterThumbnail(); UnregisterThumbnail();
}; };
} }

View file

@ -21,17 +21,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.IniFile; using Greenshot.IniFile;
using Greenshot.Plugin; using Greenshot.Plugin;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// Description of AbstractDestination. /// Description of AbstractDestination.
/// </summary> /// </summary>
public abstract class AbstractDestination : IDestination { public abstract class AbstractDestination : IDestination {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(AbstractDestination)); private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractDestination));
private static CoreConfiguration configuration = IniConfig.GetIniSection<CoreConfiguration>(); private static CoreConfiguration configuration = IniConfig.GetIniSection<CoreConfiguration>();
public virtual int CompareTo(object obj) { public virtual int CompareTo(object obj) {
@ -246,7 +248,7 @@ namespace GreenshotPlugin.Core {
// Close // Close
menu.Items.Add(new ToolStripSeparator()); menu.Items.Add(new ToolStripSeparator());
ToolStripMenuItem closeItem = new ToolStripMenuItem(Language.GetString("editor_close")); ToolStripMenuItem closeItem = new ToolStripMenuItem(Language.GetString("editor_close"));
closeItem.Image = GreenshotPlugin.Core.GreenshotResources.getImage("Close.Image"); closeItem.Image = GreenshotResources.getImage("Close.Image");
closeItem.Click += delegate { closeItem.Click += delegate {
// This menu entry is the close itself, we can dispose the surface // This menu entry is the close itself, we can dispose the surface
menu.Close(); menu.Close();
@ -285,7 +287,7 @@ namespace GreenshotPlugin.Core {
while (true) { while (true) {
if (menu.Visible) { if (menu.Visible) {
Application.DoEvents(); Application.DoEvents();
System.Threading.Thread.Sleep(100); Thread.Sleep(100);
} else { } else {
menu.Dispose(); menu.Dispose();
break; break;

View file

@ -23,6 +23,7 @@ using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Accessibility; using Accessibility;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
@ -32,7 +33,7 @@ namespace GreenshotPlugin.Core {
/// Maybe move the basic Accessible functions to WindowDetails!? /// Maybe move the basic Accessible functions to WindowDetails!?
/// </summary> /// </summary>
public class Accessible { public class Accessible {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(Accessible)); private static ILog LOG = LogManager.GetLogger(typeof(Accessible));
#region Interop #region Interop
private static int AccessibleObjectFromWindow(IntPtr hWnd, OBJID idObject, ref IAccessible acc) { private static int AccessibleObjectFromWindow(IntPtr hWnd, OBJID idObject, ref IAccessible acc) {

View file

@ -22,6 +22,7 @@ using System;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Collections.Generic; using System.Collections.Generic;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
@ -99,9 +100,9 @@ namespace GreenshotPlugin.Core {
this.first = first; this.first = first;
this.last = last; this.last = last;
this.frames = frames; this.frames = frames;
this.current = first; current = first;
this.EasingType = easingType; EasingType = easingType;
this.EasingMode = easingMode; EasingMode = easingMode;
} }
/// <summary> /// <summary>
@ -159,10 +160,10 @@ namespace GreenshotPlugin.Core {
/// <param name="frames"></param> /// <param name="frames"></param>
public void ChangeDestination(T newDestination, int frames) { public void ChangeDestination(T newDestination, int frames) {
queue.Clear(); queue.Clear();
this.first = current; first = current;
this.currentFrameNr = 0; currentFrameNr = 0;
this.frames = frames; this.frames = frames;
this.last = newDestination; last = newDestination;
} }
/// <summary> /// <summary>
@ -261,13 +262,13 @@ namespace GreenshotPlugin.Core {
return true; return true;
} }
if (queue.Count > 0) { if (queue.Count > 0) {
this.first = current; first = current;
this.currentFrameNr = 0; currentFrameNr = 0;
AnimationLeg<T> nextLeg = queue.Dequeue(); AnimationLeg<T> nextLeg = queue.Dequeue();
this.last = nextLeg.Destination; last = nextLeg.Destination;
this.frames = nextLeg.Frames; frames = nextLeg.Frames;
this.EasingType = nextLeg.EasingType; EasingType = nextLeg.EasingType;
this.EasingMode = nextLeg.EasingMode; EasingMode = nextLeg.EasingMode;
return true; return true;
} }
return false; return false;
@ -297,7 +298,7 @@ namespace GreenshotPlugin.Core {
/// Implementation of the RectangleAnimator /// Implementation of the RectangleAnimator
/// </summary> /// </summary>
public class RectangleAnimator : AnimatorBase<Rectangle> { public class RectangleAnimator : AnimatorBase<Rectangle> {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(RectangleAnimator)); private static readonly ILog LOG = LogManager.GetLogger(typeof(RectangleAnimator));
public RectangleAnimator(Rectangle first, Rectangle last, int frames) public RectangleAnimator(Rectangle first, Rectangle last, int frames)
: base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) {
@ -336,7 +337,7 @@ namespace GreenshotPlugin.Core {
/// Implementation of the PointAnimator /// Implementation of the PointAnimator
/// </summary> /// </summary>
public class PointAnimator : AnimatorBase<Point> { public class PointAnimator : AnimatorBase<Point> {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PointAnimator)); private static readonly ILog LOG = LogManager.GetLogger(typeof(PointAnimator));
public PointAnimator(Point first, Point last, int frames) public PointAnimator(Point first, Point last, int frames)
: base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) {
} }
@ -369,7 +370,7 @@ namespace GreenshotPlugin.Core {
/// Implementation of the SizeAnimator /// Implementation of the SizeAnimator
/// </summary> /// </summary>
public class SizeAnimator : AnimatorBase<Size> { public class SizeAnimator : AnimatorBase<Size> {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(SizeAnimator)); private static readonly ILog LOG = LogManager.GetLogger(typeof(SizeAnimator));
public SizeAnimator(Size first, Size last, int frames) public SizeAnimator(Size first, Size last, int frames)
: base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) {
} }
@ -401,7 +402,7 @@ namespace GreenshotPlugin.Core {
/// Implementation of the ColorAnimator /// Implementation of the ColorAnimator
/// </summary> /// </summary>
public class ColorAnimator : AnimatorBase<Color> { public class ColorAnimator : AnimatorBase<Color> {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ColorAnimator)); private static readonly ILog LOG = LogManager.GetLogger(typeof(ColorAnimator));
public ColorAnimator(Color first, Color last, int frames) public ColorAnimator(Color first, Color last, int frames)
: base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) {
} }
@ -437,7 +438,7 @@ namespace GreenshotPlugin.Core {
/// Implementation of the IntAnimator /// Implementation of the IntAnimator
/// </summary> /// </summary>
public class IntAnimator : AnimatorBase<int> { public class IntAnimator : AnimatorBase<int> {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IntAnimator)); private static readonly ILog LOG = LogManager.GetLogger(typeof(IntAnimator));
public IntAnimator(int first, int last, int frames) public IntAnimator(int first, int last, int frames)
: base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) {
} }

View file

@ -21,6 +21,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Timers; using System.Timers;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
@ -29,7 +30,7 @@ namespace GreenshotPlugin.Core {
/// <typeparam name="TK">Type of key</typeparam> /// <typeparam name="TK">Type of key</typeparam>
/// <typeparam name="TV">Type of value</typeparam> /// <typeparam name="TV">Type of value</typeparam>
public class Cache<TK, TV> { public class Cache<TK, TV> {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(Cache<TK, TV>)); private static readonly ILog LOG = LogManager.GetLogger(typeof(Cache<TK, TV>));
private IDictionary<TK, TV> internalCache = new Dictionary<TK, TV>(); private IDictionary<TK, TV> internalCache = new Dictionary<TK, TV>();
private object lockObject = new object(); private object lockObject = new object();
private int secondsToExpire = 10; private int secondsToExpire = 10;

View file

@ -31,13 +31,14 @@ using Greenshot.IniFile;
using Greenshot.Plugin; using Greenshot.Plugin;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// Description of ClipboardHelper. /// Description of ClipboardHelper.
/// </summary> /// </summary>
public static class ClipboardHelper { public static class ClipboardHelper {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ClipboardHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(ClipboardHelper));
private static readonly Object clipboardLockObject = new Object(); private static readonly Object clipboardLockObject = new Object();
private static readonly CoreConfiguration config = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration config = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly string FORMAT_FILECONTENTS = "FileContents"; private static readonly string FORMAT_FILECONTENTS = "FileContents";

View file

@ -113,6 +113,8 @@ namespace GreenshotPlugin.Core {
public bool OutputFileReduceColors; public bool OutputFileReduceColors;
[IniProperty("OutputFileAutoReduceColors", Description = "If set to true the amount of colors is counted and if smaller than 256 the color reduction is automatically used.", DefaultValue = "false")] [IniProperty("OutputFileAutoReduceColors", Description = "If set to true the amount of colors is counted and if smaller than 256 the color reduction is automatically used.", DefaultValue = "false")]
public bool OutputFileAutoReduceColors; public bool OutputFileAutoReduceColors;
[IniProperty("OutputFileReduceColorsTo", Description = "Amount of colors to reduce to, when reducing", DefaultValue = "256")]
public int OutputFileReduceColorsTo;
[IniProperty("OutputFileCopyPathToClipboard", Description="When saving a screenshot, copy the path to the clipboard?", DefaultValue="true")] [IniProperty("OutputFileCopyPathToClipboard", Description="When saving a screenshot, copy the path to the clipboard?", DefaultValue="true")]
public bool OutputFileCopyPathToClipboard; public bool OutputFileCopyPathToClipboard;

View file

@ -95,10 +95,10 @@ namespace GreenshotPlugin.Core {
/// <param name="message">The message of the dialog (null will cause a system default message to be used).</param> /// <param name="message">The message of the dialog (null will cause a system default message to be used).</param>
/// <param name="banner">The image to display on the dialog (null will cause a system default image to be used).</param> /// <param name="banner">The image to display on the dialog (null will cause a system default image to be used).</param>
public CredentialsDialog(string target, string caption, string message, Image banner) { public CredentialsDialog(string target, string caption, string message, Image banner) {
this.Target = target; Target = target;
this.Caption = caption; Caption = caption;
this.Message = message; Message = message;
this.Banner = banner; Banner = banner;
} }
private bool _alwaysDisplay = false; private bool _alwaysDisplay = false;
@ -307,21 +307,21 @@ namespace GreenshotPlugin.Core {
/// <summary>Shows the credentials dialog.</summary> /// <summary>Shows the credentials dialog.</summary>
/// <returns>Returns a DialogResult indicating the user action.</returns> /// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show() { public DialogResult Show() {
return Show(null, this.Name, this.Password, this.SaveChecked); return Show(null, Name, Password, SaveChecked);
} }
/// <summary>Shows the credentials dialog with the specified save checkbox status.</summary> /// <summary>Shows the credentials dialog with the specified save checkbox status.</summary>
/// <param name="saveChecked">True if the save checkbox is checked.</param> /// <param name="saveChecked">True if the save checkbox is checked.</param>
/// <returns>Returns a DialogResult indicating the user action.</returns> /// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show(bool saveChecked) { public DialogResult Show(bool saveChecked) {
return Show(null, this.Name, this.Password, saveChecked); return Show(null, Name, Password, saveChecked);
} }
/// <summary>Shows the credentials dialog with the specified name.</summary> /// <summary>Shows the credentials dialog with the specified name.</summary>
/// <param name="name">The name for the credentials.</param> /// <param name="name">The name for the credentials.</param>
/// <returns>Returns a DialogResult indicating the user action.</returns> /// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show(string name) { public DialogResult Show(string name) {
return Show(null, name, this.Password, this.SaveChecked); return Show(null, name, Password, SaveChecked);
} }
/// <summary>Shows the credentials dialog with the specified name and password.</summary> /// <summary>Shows the credentials dialog with the specified name and password.</summary>
@ -329,7 +329,7 @@ namespace GreenshotPlugin.Core {
/// <param name="password">The password for the credentials.</param> /// <param name="password">The password for the credentials.</param>
/// <returns>Returns a DialogResult indicating the user action.</returns> /// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show(string name, string password) { public DialogResult Show(string name, string password) {
return Show(null, name, password, this.SaveChecked); return Show(null, name, password, SaveChecked);
} }
/// <summary>Shows the credentials dialog with the specified name, password and save checkbox status.</summary> /// <summary>Shows the credentials dialog with the specified name, password and save checkbox status.</summary>
@ -345,7 +345,7 @@ namespace GreenshotPlugin.Core {
/// <param name="owner">The System.Windows.Forms.IWin32Window the dialog will display in front of.</param> /// <param name="owner">The System.Windows.Forms.IWin32Window the dialog will display in front of.</param>
/// <returns>Returns a DialogResult indicating the user action.</returns> /// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show(IWin32Window owner) { public DialogResult Show(IWin32Window owner) {
return Show(owner, this.Name, this.Password, this.SaveChecked); return Show(owner, Name, Password, SaveChecked);
} }
/// <summary>Shows the credentials dialog with the specified owner and save checkbox status.</summary> /// <summary>Shows the credentials dialog with the specified owner and save checkbox status.</summary>
@ -353,7 +353,7 @@ namespace GreenshotPlugin.Core {
/// <param name="saveChecked">True if the save checkbox is checked.</param> /// <param name="saveChecked">True if the save checkbox is checked.</param>
/// <returns>Returns a DialogResult indicating the user action.</returns> /// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show(IWin32Window owner, bool saveChecked) { public DialogResult Show(IWin32Window owner, bool saveChecked) {
return Show(owner, this.Name, this.Password, saveChecked); return Show(owner, Name, Password, saveChecked);
} }
/// <summary>Shows the credentials dialog with the specified owner, name and password.</summary> /// <summary>Shows the credentials dialog with the specified owner, name and password.</summary>
@ -362,7 +362,7 @@ namespace GreenshotPlugin.Core {
/// <param name="password">The password for the credentials.</param> /// <param name="password">The password for the credentials.</param>
/// <returns>Returns a DialogResult indicating the user action.</returns> /// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show(IWin32Window owner, string name, string password) { public DialogResult Show(IWin32Window owner, string name, string password) {
return Show(owner, name, password, this.SaveChecked); return Show(owner, name, password, SaveChecked);
} }
/// <summary>Shows the credentials dialog with the specified owner, name, password and save checkbox status.</summary> /// <summary>Shows the credentials dialog with the specified owner, name, password and save checkbox status.</summary>
@ -375,9 +375,9 @@ namespace GreenshotPlugin.Core {
if ((Environment.OSVersion.Version.Major < 5) || ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor < 1))) { if ((Environment.OSVersion.Version.Major < 5) || ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor < 1))) {
throw new ApplicationException("The Credential Management API requires Windows XP / Windows Server 2003 or later."); throw new ApplicationException("The Credential Management API requires Windows XP / Windows Server 2003 or later.");
} }
this.Name = name; Name = name;
this.Password = password; Password = password;
this.SaveChecked = saveChecked; SaveChecked = saveChecked;
return ShowDialog(owner); return ShowDialog(owner);
} }
@ -385,7 +385,7 @@ namespace GreenshotPlugin.Core {
/// <summary>Confirmation action to be applied.</summary> /// <summary>Confirmation action to be applied.</summary>
/// <param name="value">True if the credentials should be persisted.</param> /// <param name="value">True if the credentials should be persisted.</param>
public void Confirm(bool value) { public void Confirm(bool value) {
switch (CREDUI.ConfirmCredentials(this.Target, value)) { switch (CREDUI.ConfirmCredentials(Target, value)) {
case CREDUI.ReturnCodes.NO_ERROR: case CREDUI.ReturnCodes.NO_ERROR:
break; break;
@ -406,12 +406,12 @@ namespace GreenshotPlugin.Core {
private DialogResult ShowDialog(IWin32Window owner) { private DialogResult ShowDialog(IWin32Window owner) {
// set the api call parameters // set the api call parameters
StringBuilder name = new StringBuilder(CREDUI.MAX_USERNAME_LENGTH); StringBuilder name = new StringBuilder(CREDUI.MAX_USERNAME_LENGTH);
name.Append(this.Name); name.Append(Name);
StringBuilder password = new StringBuilder(CREDUI.MAX_PASSWORD_LENGTH); StringBuilder password = new StringBuilder(CREDUI.MAX_PASSWORD_LENGTH);
password.Append(this.Password); password.Append(Password);
int saveChecked = Convert.ToInt32(this.SaveChecked); int saveChecked = Convert.ToInt32(SaveChecked);
CREDUI.INFO info = GetInfo(owner); CREDUI.INFO info = GetInfo(owner);
CREDUI.FLAGS flags = GetFlags(); CREDUI.FLAGS flags = GetFlags();
@ -419,7 +419,7 @@ namespace GreenshotPlugin.Core {
// make the api call // make the api call
CREDUI.ReturnCodes code = CREDUI.PromptForCredentials( CREDUI.ReturnCodes code = CREDUI.PromptForCredentials(
ref info, ref info,
this.Target, Target,
IntPtr.Zero, 0, IntPtr.Zero, 0,
name, CREDUI.MAX_USERNAME_LENGTH, name, CREDUI.MAX_USERNAME_LENGTH,
password, CREDUI.MAX_PASSWORD_LENGTH, password, CREDUI.MAX_PASSWORD_LENGTH,
@ -428,14 +428,14 @@ namespace GreenshotPlugin.Core {
); );
// clean up resources // clean up resources
if (this.Banner != null) { if (Banner != null) {
DeleteObject(info.hbmBanner); DeleteObject(info.hbmBanner);
} }
// set the accessors from the api call parameters // set the accessors from the api call parameters
this.Name = name.ToString(); Name = name.ToString();
this.Password = password.ToString(); Password = password.ToString();
this.SaveChecked = Convert.ToBoolean(saveChecked); SaveChecked = Convert.ToBoolean(saveChecked);
return GetDialogResult(code); return GetDialogResult(code);
} }
@ -445,10 +445,10 @@ namespace GreenshotPlugin.Core {
private CREDUI.INFO GetInfo(IWin32Window owner) { private CREDUI.INFO GetInfo(IWin32Window owner) {
CREDUI.INFO info = new CREDUI.INFO(); CREDUI.INFO info = new CREDUI.INFO();
if (owner != null) info.hwndParent = owner.Handle; if (owner != null) info.hwndParent = owner.Handle;
info.pszCaptionText = this.Caption; info.pszCaptionText = Caption;
info.pszMessageText = this.Message; info.pszMessageText = Message;
if (this.Banner != null) { if (Banner != null) {
info.hbmBanner = new Bitmap(this.Banner, ValidBannerWidth, ValidBannerHeight).GetHbitmap(); info.hbmBanner = new Bitmap(Banner, ValidBannerWidth, ValidBannerHeight).GetHbitmap();
} }
info.cbSize = Marshal.SizeOf(info); info.cbSize = Marshal.SizeOf(info);
return info; return info;
@ -458,21 +458,21 @@ namespace GreenshotPlugin.Core {
private CREDUI.FLAGS GetFlags() { private CREDUI.FLAGS GetFlags() {
CREDUI.FLAGS flags = CREDUI.FLAGS.GENERIC_CREDENTIALS; CREDUI.FLAGS flags = CREDUI.FLAGS.GENERIC_CREDENTIALS;
if (this.IncorrectPassword) { if (IncorrectPassword) {
flags = flags | CREDUI.FLAGS.INCORRECT_PASSWORD; flags = flags | CREDUI.FLAGS.INCORRECT_PASSWORD;
} }
if (this.AlwaysDisplay) { if (AlwaysDisplay) {
flags = flags | CREDUI.FLAGS.ALWAYS_SHOW_UI; flags = flags | CREDUI.FLAGS.ALWAYS_SHOW_UI;
} }
if (this.ExcludeCertificates) { if (ExcludeCertificates) {
flags = flags | CREDUI.FLAGS.EXCLUDE_CERTIFICATES; flags = flags | CREDUI.FLAGS.EXCLUDE_CERTIFICATES;
} }
if (this.Persist) { if (Persist) {
flags = flags | CREDUI.FLAGS.EXPECT_CONFIRMATION; flags = flags | CREDUI.FLAGS.EXPECT_CONFIRMATION;
if (this.SaveDisplayed) { if (SaveDisplayed) {
flags = flags | CREDUI.FLAGS.SHOW_SAVE_CHECK_BOX; flags = flags | CREDUI.FLAGS.SHOW_SAVE_CHECK_BOX;
} else { } else {
flags = flags | CREDUI.FLAGS.PERSIST; flags = flags | CREDUI.FLAGS.PERSIST;
@ -481,7 +481,7 @@ namespace GreenshotPlugin.Core {
flags = flags | CREDUI.FLAGS.DO_NOT_PERSIST; flags = flags | CREDUI.FLAGS.DO_NOT_PERSIST;
} }
if (this.KeepName) { if (KeepName) {
flags = flags | CREDUI.FLAGS.KEEP_USERNAME; flags = flags | CREDUI.FLAGS.KEEP_USERNAME;
} }

View file

@ -29,7 +29,7 @@ namespace GreenshotPlugin.Core {
} }
public DisplayKeyAttribute(string v) { public DisplayKeyAttribute(string v) {
this.value = v; value = v;
} }
public DisplayKeyAttribute() { public DisplayKeyAttribute() {

View file

@ -27,6 +27,7 @@ using Greenshot.Plugin.Drawing;
using System.IO; using System.IO;
using System.Collections.Generic; using System.Collections.Generic;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using log4net;
namespace Greenshot.Core { namespace Greenshot.Core {
/// <summary> /// <summary>
@ -147,7 +148,7 @@ namespace Greenshot.Core {
/// ReduceColorsEffect /// ReduceColorsEffect
/// </summary> /// </summary>
public class ReduceColorsEffect : IEffect { public class ReduceColorsEffect : IEffect {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ReduceColorsEffect)); private static ILog LOG = LogManager.GetLogger(typeof(ReduceColorsEffect));
public ReduceColorsEffect() : base() { public ReduceColorsEffect() : base() {
Colors = 256; Colors = 256;
} }

View file

@ -22,10 +22,11 @@ using System;
using System.IO; using System.IO;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
public static class EncryptionHelper { public static class EncryptionHelper {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(EncryptionHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(EncryptionHelper));
private const string RGBIV = "dlgjowejgogkklwj"; private const string RGBIV = "dlgjowejgogkklwj";
private const string KEY = "lsjvkwhvwujkagfauguwcsjgu2wueuff"; private const string KEY = "lsjvkwhvwujkagfauguwcsjgu2wueuff";

View file

@ -21,7 +21,7 @@
using System; using System;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
public static class EnumerationExtensions { public static class EnumerationExtensions {
public static bool Has<T>(this System.Enum type, T value) { public static bool Has<T>(this Enum type, T value) {
Type underlyingType = Enum.GetUnderlyingType(value.GetType()); Type underlyingType = Enum.GetUnderlyingType(value.GetType());
try { try {
if (underlyingType == typeof(int)) { if (underlyingType == typeof(int)) {
@ -34,7 +34,7 @@ namespace GreenshotPlugin.Core {
return false; return false;
} }
public static bool Is<T>(this System.Enum type, T value) { public static bool Is<T>(this Enum type, T value) {
Type underlyingType = Enum.GetUnderlyingType(value.GetType()); Type underlyingType = Enum.GetUnderlyingType(value.GetType());
try { try {
if (underlyingType == typeof(int)) { if (underlyingType == typeof(int)) {
@ -53,7 +53,7 @@ namespace GreenshotPlugin.Core {
/// <param name="type"></param> /// <param name="type"></param>
/// <param name="value"></param> /// <param name="value"></param>
/// <returns></returns> /// <returns></returns>
public static T Add<T>(this System.Enum type, T value) { public static T Add<T>(this Enum type, T value) {
Type underlyingType = Enum.GetUnderlyingType(value.GetType()); Type underlyingType = Enum.GetUnderlyingType(value.GetType());
try { try {
if (underlyingType == typeof(int)) { if (underlyingType == typeof(int)) {
@ -73,7 +73,7 @@ namespace GreenshotPlugin.Core {
/// <param name="type"></param> /// <param name="type"></param>
/// <param name="value"></param> /// <param name="value"></param>
/// <returns></returns> /// <returns></returns>
public static T Remove<T>(this System.Enum type, T value) { public static T Remove<T>(this Enum type, T value) {
Type underlyingType = Enum.GetUnderlyingType(value.GetType()); Type underlyingType = Enum.GetUnderlyingType(value.GetType());
try { try {
if (underlyingType == typeof(int)) { if (underlyingType == typeof(int)) {

View file

@ -22,6 +22,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
@ -283,7 +284,7 @@ namespace GreenshotPlugin.Core {
/// The base class for the fast bitmap implementation /// The base class for the fast bitmap implementation
/// </summary> /// </summary>
public unsafe abstract class FastBitmap : IFastBitmap, IFastBitmapWithClip, IFastBitmapWithOffset { public unsafe abstract class FastBitmap : IFastBitmap, IFastBitmapWithClip, IFastBitmapWithOffset {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(FastBitmap)); private static ILog LOG = LogManager.GetLogger(typeof(FastBitmap));
protected const int PIXELFORMAT_INDEX_A = 3; protected const int PIXELFORMAT_INDEX_A = 3;
protected const int PIXELFORMAT_INDEX_R = 2; protected const int PIXELFORMAT_INDEX_R = 2;
@ -427,11 +428,11 @@ namespace GreenshotPlugin.Core {
this.area = bitmapArea; this.area = bitmapArea;
} }
// As the lock takes care that only the specified area is made available we need to calculate the offset // As the lock takes care that only the specified area is made available we need to calculate the offset
this.Left = area.Left; Left = area.Left;
this.Top = area.Top; Top = area.Top;
// Default cliping is done to the area without invert // Default cliping is done to the area without invert
this.Clip = this.area; Clip = this.area;
this.InvertClip = false; InvertClip = false;
// Always lock, so we don't need to do this ourselves // Always lock, so we don't need to do this ourselves
Lock(); Lock();
} }
@ -639,7 +640,7 @@ namespace GreenshotPlugin.Core {
Unlock(); Unlock();
} }
graphics.DrawImage(this.bitmap, destinationRect, area, GraphicsUnit.Pixel); graphics.DrawImage(bitmap, destinationRect, area, GraphicsUnit.Pixel);
} }
/// <summary> /// <summary>

View file

@ -25,10 +25,11 @@ using System.Text.RegularExpressions;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.IniFile; using Greenshot.IniFile;
using Greenshot.Plugin; using Greenshot.Plugin;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
public static class FilenameHelper { public static class FilenameHelper {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(FilenameHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(FilenameHelper));
private static readonly Regex VAR_REGEXP = new Regex(@"\${(?<variable>[^:}]+)[:]?(?<parameters>[^}]*)}", RegexOptions.Compiled); private static readonly Regex VAR_REGEXP = new Regex(@"\${(?<variable>[^:}]+)[:]?(?<parameters>[^}]*)}", RegexOptions.Compiled);
private static readonly Regex SPLIT_REGEXP = new Regex(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled); private static readonly Regex SPLIT_REGEXP = new Regex(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled);
private const int MAX_TITLE_LENGTH = 80; private const int MAX_TITLE_LENGTH = 80;
@ -104,7 +105,7 @@ namespace GreenshotPlugin.Core {
if (pattern == null || string.IsNullOrEmpty(pattern.Trim())) { if (pattern == null || string.IsNullOrEmpty(pattern.Trim())) {
pattern = "greenshot ${capturetime}"; pattern = "greenshot ${capturetime}";
} }
return FilenameHelper.GetFilenameFromPattern(pattern, format, captureDetails); return GetFilenameFromPattern(pattern, format, captureDetails);
} }

View file

@ -57,7 +57,7 @@ namespace GreenshotPlugin.Core {
} }
WindowDetails tmpWD = browserWindowDetails; WindowDetails tmpWD = browserWindowDetails;
// Since IE 9 the TabBandClass is less deep! // Since IE 9 the TabBandClass is less deep!
if (IEHelper.IEVersion() < 9) { if (IEVersion() < 9) {
tmpWD = tmpWD.GetChild("CommandBarClass"); tmpWD = tmpWD.GetChild("CommandBarClass");
if (tmpWD != null) { if (tmpWD != null) {
tmpWD = tmpWD.GetChild("ReBarWindow32"); tmpWD = tmpWD.GetChild("ReBarWindow32");

View file

@ -29,6 +29,7 @@ using Greenshot.IniFile;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.Core; using Greenshot.Core;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
internal enum ExifOrientations : byte { internal enum ExifOrientations : byte {
@ -47,7 +48,7 @@ namespace GreenshotPlugin.Core {
/// Description of ImageHelper. /// Description of ImageHelper.
/// </summary> /// </summary>
public static class ImageHelper { public static class ImageHelper {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImageHelper)); private static ILog LOG = LogManager.GetLogger(typeof(ImageHelper));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private const int EXIF_ORIENTATION_ID = 0x0112; private const int EXIF_ORIENTATION_ID = 0x0112;
@ -143,7 +144,7 @@ namespace GreenshotPlugin.Core {
} }
Bitmap bmp = new Bitmap(thumbWidth, thumbHeight); Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);
using (Graphics graphics = System.Drawing.Graphics.FromImage(bmp)) { using (Graphics graphics = Graphics.FromImage(bmp)) {
graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality;
@ -310,7 +311,7 @@ namespace GreenshotPlugin.Core {
LOG.InfoFormat("Information about file {0}: {1}x{2}-{3} Resolution {4}x{5}", filename, fileImage.Width, fileImage.Height, fileImage.PixelFormat, fileImage.HorizontalResolution, fileImage.VerticalResolution); LOG.InfoFormat("Information about file {0}: {1}x{2}-{3} Resolution {4}x{5}", filename, fileImage.Width, fileImage.Height, fileImage.PixelFormat, fileImage.HorizontalResolution, fileImage.VerticalResolution);
} }
// Make sure the orientation is set correctly so Greenshot can process the image correctly // Make sure the orientation is set correctly so Greenshot can process the image correctly
ImageHelper.Orientate(fileImage); Orientate(fileImage);
return fileImage; return fileImage;
} }
@ -338,7 +339,7 @@ namespace GreenshotPlugin.Core {
int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12); int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12);
using (MemoryStream destStream = new MemoryStream()) { using (MemoryStream destStream = new MemoryStream()) {
destStream.Write(srcBuf, iImageOffset, iImageSize); destStream.Write(srcBuf, iImageOffset, iImageSize);
destStream.Seek(0, System.IO.SeekOrigin.Begin); destStream.Seek(0, SeekOrigin.Begin);
bmpPngExtracted = new Bitmap(destStream); // This is PNG! :) bmpPngExtracted = new Bitmap(destStream); // This is PNG! :)
} }
break; break;
@ -857,7 +858,7 @@ namespace GreenshotPlugin.Core {
/// <param name="sourceImage">Bitmap to create a negative off</param> /// <param name="sourceImage">Bitmap to create a negative off</param>
/// <returns>Negative bitmap</returns> /// <returns>Negative bitmap</returns>
public static Bitmap CreateNegative(Image sourceImage) { public static Bitmap CreateNegative(Image sourceImage) {
Bitmap clone = (Bitmap)ImageHelper.Clone(sourceImage); Bitmap clone = (Bitmap)Clone(sourceImage);
ColorMatrix invertMatrix = new ColorMatrix(new float[][] { ColorMatrix invertMatrix = new ColorMatrix(new float[][] {
new float[] {-1, 0, 0, 0, 0}, new float[] {-1, 0, 0, 0, 0},
new float[] {0, -1, 0, 0, 0}, new float[] {0, -1, 0, 0, 0},
@ -1036,7 +1037,7 @@ namespace GreenshotPlugin.Core {
/// <param name="sourceImage">Original bitmap</param> /// <param name="sourceImage">Original bitmap</param>
/// <returns>Bitmap with grayscale</returns> /// <returns>Bitmap with grayscale</returns>
public static Image CreateGrayscale(Image sourceImage) { public static Image CreateGrayscale(Image sourceImage) {
Bitmap clone = (Bitmap)ImageHelper.Clone(sourceImage); Bitmap clone = (Bitmap)Clone(sourceImage);
ColorMatrix grayscaleMatrix = new ColorMatrix( new float[][] { ColorMatrix grayscaleMatrix = new ColorMatrix( new float[][] {
new float[] {.3f, .3f, .3f, 0, 0}, new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0}, new float[] {.59f, .59f, .59f, 0, 0},
@ -1334,22 +1335,22 @@ namespace GreenshotPlugin.Core {
if (nPercentW == 1) { if (nPercentW == 1) {
nPercentW = nPercentH; nPercentW = nPercentH;
if (canvasUseNewSize) { if (canvasUseNewSize) {
destX = Math.Max(0, System.Convert.ToInt32((newWidth - (sourceImage.Width * nPercentW)) / 2)); destX = Math.Max(0, Convert.ToInt32((newWidth - (sourceImage.Width * nPercentW)) / 2));
} }
} else if (nPercentH == 1) { } else if (nPercentH == 1) {
nPercentH = nPercentW; nPercentH = nPercentW;
if (canvasUseNewSize) { if (canvasUseNewSize) {
destY = Math.Max(0, System.Convert.ToInt32((newHeight - (sourceImage.Height * nPercentH)) / 2)); destY = Math.Max(0, Convert.ToInt32((newHeight - (sourceImage.Height * nPercentH)) / 2));
} }
} else if (nPercentH != 0 && nPercentH < nPercentW) { } else if (nPercentH != 0 && nPercentH < nPercentW) {
nPercentW = nPercentH; nPercentW = nPercentH;
if (canvasUseNewSize) { if (canvasUseNewSize) {
destX = Math.Max(0, System.Convert.ToInt32((newWidth - (sourceImage.Width * nPercentW)) / 2)); destX = Math.Max(0, Convert.ToInt32((newWidth - (sourceImage.Width * nPercentW)) / 2));
} }
} else { } else {
nPercentH = nPercentW; nPercentH = nPercentW;
if (canvasUseNewSize) { if (canvasUseNewSize) {
destY = Math.Max(0, System.Convert.ToInt32((newHeight - (sourceImage.Height * nPercentH)) / 2)); destY = Math.Max(0, Convert.ToInt32((newHeight - (sourceImage.Height * nPercentH)) / 2));
} }
} }
} }

View file

@ -18,29 +18,32 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using Greenshot.IniFile;
using Greenshot.Plugin;
using GreenshotPlugin.Controls;
using log4net;
using System; using System;
using System.Diagnostics;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.IniFile; using Encoder = System.Drawing.Imaging.Encoder;
using Greenshot.Plugin;
using GreenshotPlugin.Controls;
using Greenshot.Core;
using System.Diagnostics;
using System.Security.AccessControl;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// Description of ImageOutput. /// Description of ImageOutput.
/// </summary> /// </summary>
public static class ImageOutput { public static class ImageOutput {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImageOutput)); private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageOutput));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131; private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131;
private static Cache<string, string> tmpFileCache = new Cache<string, string>(10 * 60 * 60, new Cache<string, string>.CacheObjectExpired(RemoveExpiredTmpFile)); private static Cache<string, string> tmpFileCache = new Cache<string, string>(10 * 60 * 60, RemoveExpiredTmpFile);
/// <summary> /// <summary>
/// Creates a PropertyItem (Metadata) to store with the image. /// Creates a PropertyItem (Metadata) to store with the image.
@ -60,7 +63,7 @@ namespace GreenshotPlugin.Core {
// Set the ID // Set the ID
propertyItem.Id = id; propertyItem.Id = id;
// Set the text // Set the text
byte[] byteString = System.Text.ASCIIEncoding.ASCII.GetBytes(text + " "); byte[] byteString = Encoding.ASCII.GetBytes(text + " ");
// Set Zero byte for String end. // Set Zero byte for String end.
byteString[byteString.Length - 1] = 0; byteString[byteString.Length - 1] = 0;
propertyItem.Value = byteString; propertyItem.Value = byteString;
@ -78,7 +81,7 @@ namespace GreenshotPlugin.Core {
/// <param name="stream">Stream to save to</param> /// <param name="stream">Stream to save to</param>
/// <param name="outputSettings">SurfaceOutputSettings</param> /// <param name="outputSettings">SurfaceOutputSettings</param>
public static void SaveToStream(ISurface surface, Stream stream, SurfaceOutputSettings outputSettings) { public static void SaveToStream(ISurface surface, Stream stream, SurfaceOutputSettings outputSettings) {
Image imageToSave = null; Image imageToSave;
bool disposeImage = CreateImageFromSurface(surface, outputSettings, out imageToSave); bool disposeImage = CreateImageFromSurface(surface, outputSettings, out imageToSave);
SaveToStream(imageToSave, surface, stream, outputSettings); SaveToStream(imageToSave, surface, stream, outputSettings);
// cleanup if needed // cleanup if needed
@ -97,7 +100,7 @@ namespace GreenshotPlugin.Core {
/// <param name="stream">Stream to save to</param> /// <param name="stream">Stream to save to</param>
/// <param name="outputSettings">SurfaceOutputSettings</param> /// <param name="outputSettings">SurfaceOutputSettings</param>
public static void SaveToStream(Image imageToSave, ISurface surface, Stream stream, SurfaceOutputSettings outputSettings) { public static void SaveToStream(Image imageToSave, ISurface surface, Stream stream, SurfaceOutputSettings outputSettings) {
ImageFormat imageFormat = null; ImageFormat imageFormat;
bool useMemoryStream = false; bool useMemoryStream = false;
MemoryStream memoryStream = null; MemoryStream memoryStream = null;
if (outputSettings.Format == OutputFormat.greenshot && surface == null) { if (outputSettings.Format == OutputFormat.greenshot && surface == null) {
@ -118,8 +121,6 @@ namespace GreenshotPlugin.Core {
case OutputFormat.tiff: case OutputFormat.tiff:
imageFormat = ImageFormat.Tiff; imageFormat = ImageFormat.Tiff;
break; break;
case OutputFormat.greenshot:
case OutputFormat.png:
default: default:
// Problem with non-seekable streams most likely doesn't happen with Windows 7 (OS Version 6.1 and later) // Problem with non-seekable streams most likely doesn't happen with Windows 7 (OS Version 6.1 and later)
// http://stackoverflow.com/questions/8349260/generic-gdi-error-on-one-machine-but-not-the-other // http://stackoverflow.com/questions/8349260/generic-gdi-error-on-one-machine-but-not-the-other
@ -144,7 +145,7 @@ namespace GreenshotPlugin.Core {
targetStream = memoryStream; targetStream = memoryStream;
} }
if (imageFormat == ImageFormat.Jpeg) { if (Equals(imageFormat, ImageFormat.Jpeg)) {
bool foundEncoder = false; bool foundEncoder = false;
foreach (ImageCodecInfo imageCodec in ImageCodecInfo.GetImageEncoders()) { foreach (ImageCodecInfo imageCodec in ImageCodecInfo.GetImageEncoders()) {
if (imageCodec.FormatID == imageFormat.Guid) { if (imageCodec.FormatID == imageFormat.Guid) {
@ -171,14 +172,14 @@ namespace GreenshotPlugin.Core {
} else { } else {
bool needsDispose = false; bool needsDispose = false;
// Removing transparency if it's not supported in the output // Removing transparency if it's not supported in the output
if (imageFormat != ImageFormat.Png && Image.IsAlphaPixelFormat(imageToSave.PixelFormat)) { if (!Equals(imageFormat, ImageFormat.Png) && Image.IsAlphaPixelFormat(imageToSave.PixelFormat)) {
imageToSave = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb); imageToSave = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb);
needsDispose = true; needsDispose = true;
} }
AddTag(imageToSave); AddTag(imageToSave);
// Added for OptiPNG // Added for OptiPNG
bool processed = false; bool processed = false;
if (imageFormat == ImageFormat.Png && !string.IsNullOrEmpty(conf.OptimizePNGCommand)) { if (Equals(imageFormat, ImageFormat.Png) && !string.IsNullOrEmpty(conf.OptimizePNGCommand)) {
processed = ProcessPNGImageExternally(imageToSave, targetStream); processed = ProcessPNGImageExternally(imageToSave, targetStream);
} }
if (!processed) { if (!processed) {
@ -202,7 +203,7 @@ namespace GreenshotPlugin.Core {
using (BinaryWriter writer = new BinaryWriter(tmpStream)) { using (BinaryWriter writer = new BinaryWriter(tmpStream)) {
writer.Write(bytesWritten); writer.Write(bytesWritten);
Version v = Assembly.GetExecutingAssembly().GetName().Version; Version v = Assembly.GetExecutingAssembly().GetName().Version;
byte[] marker = System.Text.Encoding.ASCII.GetBytes(String.Format("Greenshot{0:00}.{1:00}", v.Major, v.Minor)); byte[] marker = Encoding.ASCII.GetBytes(String.Format("Greenshot{0:00}.{1:00}", v.Major, v.Minor));
writer.Write(marker); writer.Write(marker);
tmpStream.WriteTo(stream); tmpStream.WriteTo(stream);
} }
@ -249,19 +250,21 @@ namespace GreenshotPlugin.Core {
processStartInfo.RedirectStandardError = true; processStartInfo.RedirectStandardError = true;
processStartInfo.UseShellExecute = false; processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo); Process process = Process.Start(processStartInfo);
process.WaitForExit(); if (process != null) {
if (process.ExitCode == 0) { process.WaitForExit();
if (LOG.IsDebugEnabled) { if (process.ExitCode == 0) {
LOG.DebugFormat("File size after processing {0}", new FileInfo(tmpFileName).Length); if (LOG.IsDebugEnabled) {
LOG.DebugFormat("Reading back tmp file: {0}", tmpFileName); LOG.DebugFormat("File size after processing {0}", new FileInfo(tmpFileName).Length);
LOG.DebugFormat("Reading back tmp file: {0}", tmpFileName);
}
byte[] processedImage = File.ReadAllBytes(tmpFileName);
targetStream.Write(processedImage, 0, processedImage.Length);
return true;
} }
byte[] processedImage = File.ReadAllBytes(tmpFileName); LOG.ErrorFormat("Error while processing PNG image: {0}", process.ExitCode);
targetStream.Write(processedImage, 0, processedImage.Length); LOG.ErrorFormat("Output: {0}", process.StandardOutput.ReadToEnd());
return true; LOG.ErrorFormat("Error: {0}", process.StandardError.ReadToEnd());
} }
LOG.ErrorFormat("Error while processing PNG image: {0}", process.ExitCode);
LOG.ErrorFormat("Output: {0}", process.StandardOutput.ReadToEnd());
LOG.ErrorFormat("Error: {0}", process.StandardError.ReadToEnd());
} catch (Exception e) { } catch (Exception e) {
LOG.Error("Error while processing PNG image: ", e); LOG.Error("Error while processing PNG image: ", e);
} finally { } finally {
@ -282,26 +285,6 @@ namespace GreenshotPlugin.Core {
/// <returns>true if the image must be disposed</returns> /// <returns>true if the image must be disposed</returns>
public static bool CreateImageFromSurface(ISurface surface, SurfaceOutputSettings outputSettings, out Image imageToSave) { public static bool CreateImageFromSurface(ISurface surface, SurfaceOutputSettings outputSettings, out Image imageToSave) {
bool disposeImage = false; bool disposeImage = false;
ImageFormat imageFormat = null;
switch (outputSettings.Format) {
case OutputFormat.bmp:
imageFormat = ImageFormat.Bmp;
break;
case OutputFormat.gif:
imageFormat = ImageFormat.Gif;
break;
case OutputFormat.jpg:
imageFormat = ImageFormat.Jpeg;
break;
case OutputFormat.tiff:
imageFormat = ImageFormat.Tiff;
break;
case OutputFormat.greenshot:
case OutputFormat.png:
default:
imageFormat = ImageFormat.Png;
break;
}
if (outputSettings.Format == OutputFormat.greenshot || outputSettings.SaveBackgroundOnly) { if (outputSettings.Format == OutputFormat.greenshot || outputSettings.SaveBackgroundOnly) {
// We save the image of the surface, this should not be disposed // We save the image of the surface, this should not be disposed
@ -313,47 +296,50 @@ namespace GreenshotPlugin.Core {
} }
// The following block of modifications should be skipped when saving the greenshot format, no effects or otherwise! // The following block of modifications should be skipped when saving the greenshot format, no effects or otherwise!
if (outputSettings.Format != OutputFormat.greenshot) { if (outputSettings.Format == OutputFormat.greenshot) {
Image tmpImage; return disposeImage;
if (outputSettings.Effects != null && outputSettings.Effects.Count > 0) { }
// apply effects, if there are any Image tmpImage;
Point ignoreOffset; if (outputSettings.Effects != null && outputSettings.Effects.Count > 0) {
tmpImage = ImageHelper.ApplyEffects((Bitmap)imageToSave, outputSettings.Effects, out ignoreOffset); // apply effects, if there are any
if (tmpImage != null) { Point ignoreOffset;
tmpImage = ImageHelper.ApplyEffects(imageToSave, outputSettings.Effects, out ignoreOffset);
if (tmpImage != null) {
if (disposeImage) {
imageToSave.Dispose();
}
imageToSave = tmpImage;
disposeImage = true;
}
}
// check for color reduction, forced or automatically, only when the DisableReduceColors is false
if (outputSettings.DisableReduceColors || (!conf.OutputFileAutoReduceColors && !outputSettings.ReduceColors)) {
return disposeImage;
}
bool isAlpha = Image.IsAlphaPixelFormat(imageToSave.PixelFormat);
if (outputSettings.ReduceColors || (!isAlpha && conf.OutputFileAutoReduceColors)) {
using (var quantizer = new WuQuantizer((Bitmap)imageToSave)) {
int colorCount = quantizer.GetColorCount();
LOG.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount);
if (!outputSettings.ReduceColors && colorCount >= 256) {
return disposeImage;
}
try {
LOG.Info("Reducing colors on bitmap to 256.");
tmpImage = quantizer.GetQuantizedImage(conf.OutputFileReduceColorsTo);
if (disposeImage) { if (disposeImage) {
imageToSave.Dispose(); imageToSave.Dispose();
} }
imageToSave = tmpImage; imageToSave = tmpImage;
// Make sure the "new" image is disposed
disposeImage = true; disposeImage = true;
} catch (Exception e) {
LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e);
} }
} }
} else if (isAlpha && !outputSettings.ReduceColors) {
// check for color reduction, forced or automatically, only when the DisableReduceColors is false LOG.Info("Skipping 'optional' color reduction as the image has alpha");
if (!outputSettings.DisableReduceColors && (conf.OutputFileAutoReduceColors || outputSettings.ReduceColors)) {
bool isAlpha = Image.IsAlphaPixelFormat(imageToSave.PixelFormat);
if (outputSettings.ReduceColors || (!isAlpha && conf.OutputFileAutoReduceColors)) {
using (WuQuantizer quantizer = new WuQuantizer((Bitmap)imageToSave)) {
int colorCount = quantizer.GetColorCount();
LOG.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount);
if (outputSettings.ReduceColors || colorCount < 256) {
try {
LOG.Info("Reducing colors on bitmap to 256.");
tmpImage = quantizer.GetQuantizedImage(256);
if (disposeImage) {
imageToSave.Dispose();
}
imageToSave = tmpImage;
// Make sure the "new" image is disposed
disposeImage = true;
} catch (Exception e) {
LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e);
}
}
}
} else if (isAlpha && !outputSettings.ReduceColors) {
LOG.Info("Skipping 'optional' color reduction as the image has alpha");
}
}
} }
return disposeImage; return disposeImage;
} }
@ -378,12 +364,13 @@ namespace GreenshotPlugin.Core {
/// Load a Greenshot surface /// Load a Greenshot surface
/// </summary> /// </summary>
/// <param name="fullPath"></param> /// <param name="fullPath"></param>
/// <param name="returnSurface"></param>
/// <returns></returns> /// <returns></returns>
public static ISurface LoadGreenshotSurface(string fullPath, ISurface returnSurface) { public static ISurface LoadGreenshotSurface(string fullPath, ISurface returnSurface) {
if (string.IsNullOrEmpty(fullPath)) { if (string.IsNullOrEmpty(fullPath)) {
return null; return null;
} }
Image fileImage = null; Image fileImage;
LOG.InfoFormat("Loading image from file {0}", fullPath); LOG.InfoFormat("Loading image from file {0}", fullPath);
// Fixed lock problem Bug #3431881 // Fixed lock problem Bug #3431881
using (Stream surfaceFileStream = File.OpenRead(fullPath)) { using (Stream surfaceFileStream = File.OpenRead(fullPath)) {
@ -402,15 +389,14 @@ namespace GreenshotPlugin.Core {
string greenshotMarker; string greenshotMarker;
using (StreamReader streamReader = new StreamReader(surfaceFileStream)) { using (StreamReader streamReader = new StreamReader(surfaceFileStream)) {
greenshotMarker = streamReader.ReadToEnd(); greenshotMarker = streamReader.ReadToEnd();
if (greenshotMarker == null || !greenshotMarker.StartsWith("Greenshot")) { if (!greenshotMarker.StartsWith("Greenshot")) {
throw new ArgumentException(string.Format("{0} is not a Greenshot file!", fullPath)); throw new ArgumentException(string.Format("{0} is not a Greenshot file!", fullPath));
} }
LOG.InfoFormat("Greenshot file format: {0}", greenshotMarker); LOG.InfoFormat("Greenshot file format: {0}", greenshotMarker);
const int filesizeLocation = 8 + markerSize; const int filesizeLocation = 8 + markerSize;
surfaceFileStream.Seek(-filesizeLocation, SeekOrigin.End); surfaceFileStream.Seek(-filesizeLocation, SeekOrigin.End);
long bytesWritten = 0;
using (BinaryReader reader = new BinaryReader(surfaceFileStream)) { using (BinaryReader reader = new BinaryReader(surfaceFileStream)) {
bytesWritten = reader.ReadInt64(); long bytesWritten = reader.ReadInt64();
surfaceFileStream.Seek(-(bytesWritten + filesizeLocation), SeekOrigin.End); surfaceFileStream.Seek(-(bytesWritten + filesizeLocation), SeekOrigin.End);
returnSurface.LoadElementsFromStream(surfaceFileStream); returnSurface.LoadElementsFromStream(surfaceFileStream);
} }
@ -431,9 +417,11 @@ namespace GreenshotPlugin.Core {
string path = Path.GetDirectoryName(fullPath); string path = Path.GetDirectoryName(fullPath);
// check whether path exists - if not create it // check whether path exists - if not create it
DirectoryInfo di = new DirectoryInfo(path); if (path != null) {
if (!di.Exists) { DirectoryInfo di = new DirectoryInfo(path);
Directory.CreateDirectory(di.FullName); if (!di.Exists) {
Directory.CreateDirectory(di.FullName);
}
} }
if (!allowOverwrite && File.Exists(fullPath)) { if (!allowOverwrite && File.Exists(fullPath)) {
@ -462,9 +450,7 @@ namespace GreenshotPlugin.Core {
string extension = fullPath.Substring(fullPath.LastIndexOf(".") + 1); string extension = fullPath.Substring(fullPath.LastIndexOf(".") + 1);
OutputFormat format = OutputFormat.png; OutputFormat format = OutputFormat.png;
try { try {
if (extension != null) { format = (OutputFormat)Enum.Parse(typeof(OutputFormat), extension.ToLower());
format = (OutputFormat)Enum.Parse(typeof(OutputFormat), extension.ToLower());
}
} catch (ArgumentException ae) { } catch (ArgumentException ae) {
LOG.Warn("Couldn't parse extension: " + extension, ae); LOG.Warn("Couldn't parse extension: " + extension, ae);
} }
@ -493,10 +479,10 @@ namespace GreenshotPlugin.Core {
qualityDialog.ShowDialog(); qualityDialog.ShowDialog();
} }
// TODO: For now we always overwrite, should be changed // TODO: For now we always overwrite, should be changed
ImageOutput.Save(surface, fileNameWithExtension, true, outputSettings, conf.OutputFileCopyPathToClipboard); Save(surface, fileNameWithExtension, true, outputSettings, conf.OutputFileCopyPathToClipboard);
returnValue = fileNameWithExtension; returnValue = fileNameWithExtension;
IniConfig.Save(); IniConfig.Save();
} catch (System.Runtime.InteropServices.ExternalException) { } catch (ExternalException) {
MessageBox.Show(Language.GetFormattedString("error_nowriteaccess", saveImageFileDialog.FileName).Replace(@"\\", @"\"), Language.GetString("error")); MessageBox.Show(Language.GetFormattedString("error_nowriteaccess", saveImageFileDialog.FileName).Replace(@"\\", @"\"), Language.GetString("error"));
} }
} }
@ -530,13 +516,13 @@ namespace GreenshotPlugin.Core {
// Catching any exception to prevent that the user can't write in the directory. // Catching any exception to prevent that the user can't write in the directory.
// This is done for e.g. bugs #2974608, #2963943, #2816163, #2795317, #2789218 // This is done for e.g. bugs #2974608, #2963943, #2816163, #2795317, #2789218
try { try {
ImageOutput.Save(surface, tmpFile, true, outputSettings, false); Save(surface, tmpFile, true, outputSettings, false);
tmpFileCache.Add(tmpFile, tmpFile); tmpFileCache.Add(tmpFile, tmpFile);
} catch (Exception e) { } catch (Exception e) {
// Show the problem // Show the problem
MessageBox.Show(e.Message, "Error"); MessageBox.Show(e.Message, "Error");
// when save failed we present a SaveWithDialog // when save failed we present a SaveWithDialog
tmpFile = ImageOutput.SaveWithDialog(surface, captureDetails); tmpFile = SaveWithDialog(surface, captureDetails);
} }
return tmpFile; return tmpFile;
} }
@ -555,7 +541,8 @@ namespace GreenshotPlugin.Core {
tmpFileCache.Remove(tmpfile); tmpFileCache.Remove(tmpfile);
} }
return true; return true;
} catch (Exception) { } catch (Exception ex) {
LOG.Warn("Error deleting tmp file: ", ex);
} }
return false; return false;
} }
@ -563,7 +550,9 @@ namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// Helper method to create a temp image file /// Helper method to create a temp image file
/// </summary> /// </summary>
/// <param name="image"></param> /// <param name="surface"></param>
/// <param name="outputSettings"></param>
/// <param name="destinationPath"></param>
/// <returns></returns> /// <returns></returns>
public static string SaveToTmpFile(ISurface surface, SurfaceOutputSettings outputSettings, string destinationPath) { public static string SaveToTmpFile(ISurface surface, SurfaceOutputSettings outputSettings, string destinationPath) {
string tmpFile = Path.GetRandomFileName() + "." + outputSettings.Format.ToString(); string tmpFile = Path.GetRandomFileName() + "." + outputSettings.Format.ToString();
@ -576,7 +565,7 @@ namespace GreenshotPlugin.Core {
LOG.Debug("Creating TMP File : " + tmpPath); LOG.Debug("Creating TMP File : " + tmpPath);
try { try {
ImageOutput.Save(surface, tmpPath, true, outputSettings, false); Save(surface, tmpPath, true, outputSettings, false);
tmpFileCache.Add(tmpPath, tmpPath); tmpFileCache.Add(tmpPath, tmpPath);
} catch (Exception) { } catch (Exception) {
return null; return null;
@ -600,8 +589,8 @@ namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// Cleanup handler for expired tempfiles /// Cleanup handler for expired tempfiles
/// </summary> /// </summary>
/// <param name="filekey"></param>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <param name="alsoTheFilename"></param>
private static void RemoveExpiredTmpFile(string filekey, object filename) { private static void RemoveExpiredTmpFile(string filekey, object filename) {
string path = filename as string; string path = filename as string;
if (path != null && File.Exists(path)) { if (path != null && File.Exists(path)) {

View file

@ -23,13 +23,14 @@ using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Threading; using System.Threading;
using Greenshot.Plugin; using Greenshot.Plugin;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// Description of InterfaceUtils. /// Description of InterfaceUtils.
/// </summary> /// </summary>
public static class InterfaceUtils { public static class InterfaceUtils {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(InterfaceUtils)); private static ILog LOG = LogManager.GetLogger(typeof(InterfaceUtils));
public static List<Type> GetSubclassesOf(Type type, bool excludeSystemTypes) { public static List<Type> GetSubclassesOf(Type type, bool excludeSystemTypes) {
List<Type> list = new List<Type>(); List<Type> list = new List<Type>();

View file

@ -25,6 +25,7 @@ using System.Reflection;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Xml; using System.Xml;
using Greenshot.IniFile; using Greenshot.IniFile;
using log4net;
using Microsoft.Win32; using Microsoft.Win32;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
@ -34,7 +35,7 @@ namespace GreenshotPlugin.Core {
/// The language resources are loaded from the language files found on fixed or supplied paths /// The language resources are loaded from the language files found on fixed or supplied paths
/// </summary> /// </summary>
public class Language { public class Language {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(Language)); private static ILog LOG = LogManager.GetLogger(typeof(Language));
private static List<string> languagePaths = new List<string>(); private static List<string> languagePaths = new List<string>();
private static IDictionary<string, List<LanguageFile>> languageFiles = new Dictionary<string, List<LanguageFile>>(); private static IDictionary<string, List<LanguageFile>> languageFiles = new Dictionary<string, List<LanguageFile>>();
private static IDictionary<string, string> helpFiles = new Dictionary<string, string>(); private static IDictionary<string, string> helpFiles = new Dictionary<string, string>();
@ -534,8 +535,8 @@ namespace GreenshotPlugin.Core {
public static string Translate(object key) { public static string Translate(object key) {
string typename = key.GetType().Name; string typename = key.GetType().Name;
string enumKey = typename + "." + key.ToString(); string enumKey = typename + "." + key.ToString();
if (Language.hasKey(enumKey)) { if (hasKey(enumKey)) {
return Language.GetString(enumKey); return GetString(enumKey);
} }
return key.ToString(); return key.ToString();
} }

View file

@ -28,6 +28,7 @@ using log4net.Appender;
using log4net.Config; using log4net.Config;
using log4net.Repository.Hierarchy; using log4net.Repository.Hierarchy;
using System; using System;
using log4net.Util;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
@ -98,8 +99,8 @@ namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// A simple helper class to support the logging to the AppData location /// A simple helper class to support the logging to the AppData location
/// </summary> /// </summary>
public class SpecialFolderPatternConverter : log4net.Util.PatternConverter { public class SpecialFolderPatternConverter : PatternConverter {
override protected void Convert(System.IO.TextWriter writer, object state) { override protected void Convert(TextWriter writer, object state) {
Environment.SpecialFolder specialFolder = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), base.Option, true); Environment.SpecialFolder specialFolder = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), base.Option, true);
writer.Write(Environment.GetFolderPath(specialFolder)); writer.Write(Environment.GetFolderPath(specialFolder));
} }

View file

@ -21,6 +21,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Globalization;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Net.Security; using System.Net.Security;
@ -29,18 +30,19 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Greenshot.IniFile; using Greenshot.IniFile;
using Greenshot.Plugin; using Greenshot.Plugin;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// Description of NetworkHelper. /// Description of NetworkHelper.
/// </summary> /// </summary>
public static class NetworkHelper { public static class NetworkHelper {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(NetworkHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(NetworkHelper));
private static CoreConfiguration config = IniConfig.GetIniSection<CoreConfiguration>(); private static CoreConfiguration config = IniConfig.GetIniSection<CoreConfiguration>();
static NetworkHelper() { static NetworkHelper() {
// Disable certificate checking // Disable certificate checking
System.Net.ServicePointManager.ServerCertificateValidationCallback += ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslError) { delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslError) {
bool validationResult = true; bool validationResult = true;
return validationResult; return validationResult;
@ -52,10 +54,10 @@ namespace GreenshotPlugin.Core {
/// <param name=url">An Uri to specify the download location</param> /// <param name=url">An Uri to specify the download location</param>
/// <returns>string with the file content</returns> /// <returns>string with the file content</returns>
public static string GetAsString(Uri url) { public static string GetAsString(Uri url) {
HttpWebRequest webRequest = (HttpWebRequest)NetworkHelper.CreateWebRequest(url); HttpWebRequest webRequest = (HttpWebRequest)CreateWebRequest(url);
webRequest.Method = "GET"; webRequest.Method = "GET";
webRequest.KeepAlive = true; webRequest.KeepAlive = true;
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; webRequest.Credentials = CredentialCache.DefaultCredentials;
return GetResponse(webRequest); return GetResponse(webRequest);
} }
@ -67,7 +69,7 @@ namespace GreenshotPlugin.Core {
public static Bitmap DownloadFavIcon(Uri baseUri) { public static Bitmap DownloadFavIcon(Uri baseUri) {
Uri url = new Uri(baseUri, new Uri("favicon.ico")); Uri url = new Uri(baseUri, new Uri("favicon.ico"));
try { try {
HttpWebRequest request = (HttpWebRequest)NetworkHelper.CreateWebRequest(url); HttpWebRequest request = (HttpWebRequest)CreateWebRequest(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (request.HaveResponse) { if (request.HaveResponse) {
using (Image image = Image.FromStream(response.GetResponseStream())) { using (Image image = Image.FromStream(response.GetResponseStream())) {
@ -88,7 +90,7 @@ namespace GreenshotPlugin.Core {
/// <returns>Bitmap</returns> /// <returns>Bitmap</returns>
public static Image DownloadImage(string url) { public static Image DownloadImage(string url) {
try { try {
HttpWebRequest request = (HttpWebRequest)NetworkHelper.CreateWebRequest(url); HttpWebRequest request = (HttpWebRequest)CreateWebRequest(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (request.HaveResponse) { if (request.HaveResponse) {
using (Image image = Image.FromStream(response.GetResponseStream())) { using (Image image = Image.FromStream(response.GetResponseStream())) {
@ -118,7 +120,7 @@ namespace GreenshotPlugin.Core {
public static WebRequest CreateWebRequest(Uri uri) { public static WebRequest CreateWebRequest(Uri uri) {
WebRequest webRequest = WebRequest.Create(uri); WebRequest webRequest = WebRequest.Create(uri);
if (config.UseProxy) { if (config.UseProxy) {
webRequest.Proxy = GreenshotPlugin.Core.NetworkHelper.CreateProxy(uri); webRequest.Proxy = CreateProxy(uri);
//webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials; //webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
} }
return webRequest; return webRequest;
@ -166,7 +168,7 @@ namespace GreenshotPlugin.Core {
public static string UrlEncode(string text) { public static string UrlEncode(string text) {
if (!string.IsNullOrEmpty(text)) { if (!string.IsNullOrEmpty(text)) {
// Sytem.Uri provides reliable parsing, but doesn't encode spaces. // Sytem.Uri provides reliable parsing, but doesn't encode spaces.
return System.Uri.EscapeDataString(text).Replace("%20", "+"); return Uri.EscapeDataString(text).Replace("%20", "+");
} }
return null; return null;
} }
@ -200,7 +202,7 @@ namespace GreenshotPlugin.Core {
// pre-process for + sign space formatting since System.Uri doesn't handle it // pre-process for + sign space formatting since System.Uri doesn't handle it
// plus literals are encoded as %2b normally so this should be safe // plus literals are encoded as %2b normally so this should be safe
text = text.Replace("+", " "); text = text.Replace("+", " ");
return System.Uri.UnescapeDataString(text); return Uri.UnescapeDataString(text);
} }
/// <summary> /// <summary>
@ -246,7 +248,7 @@ namespace GreenshotPlugin.Core {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
foreach(string key in queryParameters.Keys) { foreach(string key in queryParameters.Keys) {
sb.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "{0}={1}&", key, UrlEncode(string.Format("{0}",queryParameters[key]))); sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", key, UrlEncode(string.Format("{0}",queryParameters[key])));
} }
sb.Remove(sb.Length-1,1); sb.Remove(sb.Length-1,1);
@ -363,12 +365,12 @@ namespace GreenshotPlugin.Core {
} }
public ByteContainer(byte[] file, string filename, string contenttype, int filesize) { public ByteContainer(byte[] file, string filename, string contenttype, int filesize) {
this.file = file; this.file = file;
this.fileName = filename; fileName = filename;
this.contentType = contenttype; contentType = contenttype;
if (filesize == 0) { if (filesize == 0) {
this.fileSize = file.Length; fileSize = file.Length;
} else { } else {
this.fileSize = filesize; fileSize = filesize;
} }
} }
@ -377,7 +379,7 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
/// <returns>string</returns> /// <returns>string</returns>
public string ToBase64String(Base64FormattingOptions formattingOptions) { public string ToBase64String(Base64FormattingOptions formattingOptions) {
return System.Convert.ToBase64String(file, 0, fileSize, formattingOptions); return Convert.ToBase64String(file, 0, fileSize, formattingOptions);
} }
/// <summary> /// <summary>
@ -440,7 +442,7 @@ namespace GreenshotPlugin.Core {
public BitmapContainer(Bitmap bitmap, SurfaceOutputSettings outputSettings, string filename) { public BitmapContainer(Bitmap bitmap, SurfaceOutputSettings outputSettings, string filename) {
this.bitmap = bitmap; this.bitmap = bitmap;
this.outputSettings = outputSettings; this.outputSettings = outputSettings;
this.fileName = filename; fileName = filename;
} }
/// <summary> /// <summary>
@ -451,7 +453,7 @@ namespace GreenshotPlugin.Core {
public string ToBase64String(Base64FormattingOptions formattingOptions) { public string ToBase64String(Base64FormattingOptions formattingOptions) {
using (MemoryStream stream = new MemoryStream()) { using (MemoryStream stream = new MemoryStream()) {
ImageOutput.SaveToStream(bitmap, null, stream, outputSettings); ImageOutput.SaveToStream(bitmap, null, stream, outputSettings);
return System.Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions); return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions);
} }
} }
@ -516,7 +518,7 @@ namespace GreenshotPlugin.Core {
public SurfaceContainer(ISurface surface, SurfaceOutputSettings outputSettings, string filename) { public SurfaceContainer(ISurface surface, SurfaceOutputSettings outputSettings, string filename) {
this.surface = surface; this.surface = surface;
this.outputSettings = outputSettings; this.outputSettings = outputSettings;
this.fileName = filename; fileName = filename;
} }
/// <summary> /// <summary>
@ -527,7 +529,7 @@ namespace GreenshotPlugin.Core {
public string ToBase64String(Base64FormattingOptions formattingOptions) { public string ToBase64String(Base64FormattingOptions formattingOptions) {
using (MemoryStream stream = new MemoryStream()) { using (MemoryStream stream = new MemoryStream()) {
ImageOutput.SaveToStream(surface, stream, outputSettings); ImageOutput.SaveToStream(surface, stream, outputSettings);
return System.Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions); return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions);
} }
} }

View file

@ -21,11 +21,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Globalization;
using System.Net; using System.Net;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Threading;
using GreenshotPlugin.Controls; using GreenshotPlugin.Controls;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
@ -40,7 +43,7 @@ namespace GreenshotPlugin.Core {
public enum HTTPMethod { GET, POST, PUT, DELETE }; public enum HTTPMethod { GET, POST, PUT, DELETE };
public class OAuthSession { public class OAuthSession {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OAuthSession)); private static readonly ILog LOG = LogManager.GetLogger(typeof(OAuthSession));
protected const string OAUTH_VERSION = "1.0"; protected const string OAUTH_VERSION = "1.0";
protected const string OAUTH_PARAMETER_PREFIX = "oauth_"; protected const string OAUTH_PARAMETER_PREFIX = "oauth_";
@ -207,11 +210,11 @@ namespace GreenshotPlugin.Core {
public OAuthSession(string consumerKey, string consumerSecret) { public OAuthSession(string consumerKey, string consumerSecret) {
this.consumerKey = consumerKey; this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret; this.consumerSecret = consumerSecret;
this.UseMultipartFormData = true; UseMultipartFormData = true;
this.RequestTokenMethod = HTTPMethod.GET; RequestTokenMethod = HTTPMethod.GET;
this.AccessTokenMethod = HTTPMethod.GET; AccessTokenMethod = HTTPMethod.GET;
this.SignatureType = OAuthSignatureTypes.HMACSHA1; SignatureType = OAuthSignatureTypes.HMACSHA1;
this.AutoLogin = true; AutoLogin = true;
} }
/// <summary> /// <summary>
@ -250,7 +253,7 @@ namespace GreenshotPlugin.Core {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
foreach (string key in queryParameters.Keys) { foreach (string key in queryParameters.Keys) {
if (queryParameters[key] is string) { if (queryParameters[key] is string) {
sb.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "{0}={1}&", key, UrlEncode3986(string.Format("{0}",queryParameters[key]))); sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", key, UrlEncode3986(string.Format("{0}",queryParameters[key])));
} }
} }
sb.Remove(sb.Length - 1, 1); sb.Remove(sb.Length - 1, 1);
@ -318,9 +321,9 @@ namespace GreenshotPlugin.Core {
LOG.DebugFormat("Request token response: {0}", response); LOG.DebugFormat("Request token response: {0}", response);
requestTokenResponseParameters = NetworkHelper.ParseQueryString(response); requestTokenResponseParameters = NetworkHelper.ParseQueryString(response);
if (requestTokenResponseParameters.ContainsKey(OAUTH_TOKEN_KEY)) { if (requestTokenResponseParameters.ContainsKey(OAUTH_TOKEN_KEY)) {
this.Token = requestTokenResponseParameters[OAUTH_TOKEN_KEY]; Token = requestTokenResponseParameters[OAUTH_TOKEN_KEY];
this.TokenSecret = requestTokenResponseParameters[OAUTH_TOKEN_SECRET_KEY]; TokenSecret = requestTokenResponseParameters[OAUTH_TOKEN_SECRET_KEY];
ret = this.Token; ret = Token;
} }
} }
return ret; return ret;
@ -377,10 +380,10 @@ namespace GreenshotPlugin.Core {
LOG.DebugFormat("Access token response: {0}", response); LOG.DebugFormat("Access token response: {0}", response);
accessTokenResponseParameters = NetworkHelper.ParseQueryString(response); accessTokenResponseParameters = NetworkHelper.ParseQueryString(response);
if (accessTokenResponseParameters.ContainsKey(OAUTH_TOKEN_KEY) && accessTokenResponseParameters[OAUTH_TOKEN_KEY] != null) { if (accessTokenResponseParameters.ContainsKey(OAUTH_TOKEN_KEY) && accessTokenResponseParameters[OAUTH_TOKEN_KEY] != null) {
this.Token = accessTokenResponseParameters[OAUTH_TOKEN_KEY]; Token = accessTokenResponseParameters[OAUTH_TOKEN_KEY];
} }
if (accessTokenResponseParameters.ContainsKey(OAUTH_TOKEN_SECRET_KEY) && accessTokenResponseParameters[OAUTH_TOKEN_SECRET_KEY] != null) { if (accessTokenResponseParameters.ContainsKey(OAUTH_TOKEN_SECRET_KEY) && accessTokenResponseParameters[OAUTH_TOKEN_SECRET_KEY] != null) {
this.TokenSecret = accessTokenResponseParameters[OAUTH_TOKEN_SECRET_KEY]; TokenSecret = accessTokenResponseParameters[OAUTH_TOKEN_SECRET_KEY];
} }
} }
@ -392,9 +395,9 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
/// <returns>true if the process is completed</returns> /// <returns>true if the process is completed</returns>
public bool Authorize() { public bool Authorize() {
this.Token = null; Token = null;
this.TokenSecret = null; TokenSecret = null;
this.Verifier = null; Verifier = null;
LOG.Debug("Creating Token"); LOG.Debug("Creating Token");
try { try {
getRequestToken(); getRequestToken();
@ -407,7 +410,7 @@ namespace GreenshotPlugin.Core {
return false; return false;
} }
try { try {
System.Threading.Thread.Sleep(1000); Thread.Sleep(1000);
return getAccessToken() != null; return getAccessToken() != null;
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error(ex); LOG.Error(ex);
@ -421,7 +424,7 @@ namespace GreenshotPlugin.Core {
/// <returns>The url with a valid request token, or a null string.</returns> /// <returns>The url with a valid request token, or a null string.</returns>
private string authorizationLink { private string authorizationLink {
get { get {
return AuthorizeUrl + "?" + OAUTH_TOKEN_KEY + "=" + this.Token + "&" + OAUTH_CALLBACK_KEY + "=" + UrlEncode3986(CallbackUrl); return AuthorizeUrl + "?" + OAUTH_TOKEN_KEY + "=" + Token + "&" + OAUTH_CALLBACK_KEY + "=" + UrlEncode3986(CallbackUrl);
} }
} }
@ -552,7 +555,7 @@ namespace GreenshotPlugin.Core {
// Add normalized URL // Add normalized URL
Uri url = new Uri(requestURL); Uri url = new Uri(requestURL);
string normalizedUrl = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host); string normalizedUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443))) { if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443))) {
normalizedUrl += ":" + url.Port; normalizedUrl += ":" + url.Port;
} }
@ -587,7 +590,7 @@ namespace GreenshotPlugin.Core {
} }
signatureBase.Append(UrlEncode3986(GenerateNormalizedParametersString(parameters))); signatureBase.Append(UrlEncode3986(GenerateNormalizedParametersString(parameters)));
LOG.DebugFormat("Signature base: {0}", signatureBase); LOG.DebugFormat("Signature base: {0}", signatureBase);
string key = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}&{1}", UrlEncode3986(consumerSecret), string.IsNullOrEmpty(TokenSecret) ? string.Empty : UrlEncode3986(TokenSecret)); string key = string.Format(CultureInfo.InvariantCulture, "{0}&{1}", UrlEncode3986(consumerSecret), string.IsNullOrEmpty(TokenSecret) ? string.Empty : UrlEncode3986(TokenSecret));
switch (SignatureType) { switch (SignatureType) {
case OAuthSignatureTypes.RSASHA1: case OAuthSignatureTypes.RSASHA1:
// Code comes from here: http://www.dotnetfunda.com/articles/article1932-rest-service-call-using-oauth-10-authorization-with-rsa-sha1.aspx // Code comes from here: http://www.dotnetfunda.com/articles/article1932-rest-service-call-using-oauth-10-authorization-with-rsa-sha1.aspx
@ -601,7 +604,7 @@ namespace GreenshotPlugin.Core {
// Create a RSA-SHA1 Hash object // Create a RSA-SHA1 Hash object
using (SHA1Managed shaHASHObject = new SHA1Managed()) { using (SHA1Managed shaHASHObject = new SHA1Managed()) {
// Create Byte Array of Signature base string // Create Byte Array of Signature base string
byte[] data = System.Text.Encoding.ASCII.GetBytes(signatureBase.ToString()); byte[] data = Encoding.ASCII.GetBytes(signatureBase.ToString());
// Create Hashmap of Signature base string // Create Hashmap of Signature base string
byte[] hash = shaHASHObject.ComputeHash(data); byte[] hash = shaHASHObject.ComputeHash(data);
// Create Sign Hash of base string // Create Sign Hash of base string
@ -649,7 +652,7 @@ namespace GreenshotPlugin.Core {
requestParameters = new Dictionary<string, object>(); requestParameters = new Dictionary<string, object>();
foreach (string parameterKey in parameters.Keys) { foreach (string parameterKey in parameters.Keys) {
if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) { if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) {
authHeader.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "{0}=\"{1}\", ", parameterKey, UrlEncode3986(string.Format("{0}",parameters[parameterKey]))); authHeader.AppendFormat(CultureInfo.InvariantCulture, "{0}=\"{1}\", ", parameterKey, UrlEncode3986(string.Format("{0}",parameters[parameterKey])));
} else if (!requestParameters.ContainsKey(parameterKey)) { } else if (!requestParameters.ContainsKey(parameterKey)) {
requestParameters.Add(parameterKey, parameters[parameterKey]); requestParameters.Add(parameterKey, parameters[parameterKey]);
} }
@ -694,9 +697,9 @@ namespace GreenshotPlugin.Core {
foreach (string parameterKey in requestParameters.Keys) { foreach (string parameterKey in requestParameters.Keys) {
if (parameters[parameterKey] is IBinaryContainer) { if (parameters[parameterKey] is IBinaryContainer) {
IBinaryContainer binaryParameter = parameters[parameterKey] as IBinaryContainer; IBinaryContainer binaryParameter = parameters[parameterKey] as IBinaryContainer;
form.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None))); form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)));
} else { } else {
form.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(string.Format("{0}",parameters[parameterKey]))); form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(string.Format("{0}",parameters[parameterKey])));
} }
} }
// Remove trailing & // Remove trailing &

View file

@ -23,6 +23,7 @@ using System.Drawing;
using System.IO; using System.IO;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.Plugin; using Greenshot.Plugin;
using log4net;
using Microsoft.Win32; using Microsoft.Win32;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
@ -30,7 +31,7 @@ namespace GreenshotPlugin.Core {
/// Description of PluginUtils. /// Description of PluginUtils.
/// </summary> /// </summary>
public static class PluginUtils { public static class PluginUtils {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PluginUtils)); private static readonly ILog LOG = LogManager.GetLogger(typeof(PluginUtils));
private const string PATH_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"; private const string PATH_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\";
/// <summary> /// <summary>
@ -96,8 +97,8 @@ namespace GreenshotPlugin.Core {
/// <param name="tag">The TAG value</param> /// <param name="tag">The TAG value</param>
/// <param name="shortcutKeys">Keys which can be used as shortcut</param> /// <param name="shortcutKeys">Keys which can be used as shortcut</param>
/// <param name="handler">The onclick handler</param> /// <param name="handler">The onclick handler</param>
public static void AddToFileMenu(IImageEditor imageEditor, Image image, string text, object tag, Keys? shortcutKeys, System.EventHandler handler) { public static void AddToFileMenu(IImageEditor imageEditor, Image image, string text, object tag, Keys? shortcutKeys, EventHandler handler) {
System.Windows.Forms.ToolStripMenuItem item = new System.Windows.Forms.ToolStripMenuItem(); ToolStripMenuItem item = new ToolStripMenuItem();
item.Image = image; item.Image = image;
item.Text = text; item.Text = text;
item.Tag = tag; item.Tag = tag;

View file

@ -23,6 +23,7 @@ using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
internal class WuColorCube { internal class WuColorCube {
@ -70,7 +71,7 @@ namespace GreenshotPlugin.Core {
} }
public class WuQuantizer : IDisposable { public class WuQuantizer : IDisposable {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WuQuantizer)); private static ILog LOG = LogManager.GetLogger(typeof(WuQuantizer));
private const Int32 MAXCOLOR = 512; private const Int32 MAXCOLOR = 512;
private const Int32 RED = 2; private const Int32 RED = 2;

View file

@ -24,6 +24,7 @@ using System.Globalization;
using System.Net; using System.Net;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Xml; using System.Xml;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
public class SourceforgeFile { public class SourceforgeFile {
@ -94,7 +95,7 @@ namespace GreenshotPlugin.Core {
/// Description of SourceForgeHelper. /// Description of SourceForgeHelper.
/// </summary> /// </summary>
public class SourceForgeHelper { public class SourceForgeHelper {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(SourceForgeHelper)); private static ILog LOG = LogManager.GetLogger(typeof(SourceForgeHelper));
private const String RSSFEED = "http://getgreenshot.org/project-feed/"; private const String RSSFEED = "http://getgreenshot.org/project-feed/";
/// <summary> /// <summary>

View file

@ -28,6 +28,7 @@ using System.Windows.Forms;
using Greenshot.IniFile; using Greenshot.IniFile;
using Greenshot.Plugin; using Greenshot.Plugin;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
@ -132,7 +133,7 @@ namespace GreenshotPlugin.Core {
/// Having the Bitmap, eventually the Windows Title and cursor all together. /// Having the Bitmap, eventually the Windows Title and cursor all together.
/// </summary> /// </summary>
public class Capture : IDisposable, ICapture { public class Capture : IDisposable, ICapture {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(Capture)); private static ILog LOG = LogManager.GetLogger(typeof(Capture));
private List<ICaptureElement> elements = new List<ICaptureElement>(); private List<ICaptureElement> elements = new List<ICaptureElement>();
private Rectangle screenBounds; private Rectangle screenBounds;
@ -165,7 +166,7 @@ namespace GreenshotPlugin.Core {
LOG.Debug("Converting Bitmap to PixelFormat.Format32bppArgb as we don't support: " + value.PixelFormat); LOG.Debug("Converting Bitmap to PixelFormat.Format32bppArgb as we don't support: " + value.PixelFormat);
try { try {
// Default Bitmap PixelFormat is Format32bppArgb // Default Bitmap PixelFormat is Format32bppArgb
this.image = new Bitmap(value); image = new Bitmap(value);
} finally { } finally {
// Always dispose, even when a exception occured // Always dispose, even when a exception occured
value.Dispose(); value.Dispose();
@ -246,7 +247,7 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
/// <param name="newImage">Image</param> /// <param name="newImage">Image</param>
public Capture(Image newImage) : this() { public Capture(Image newImage) : this() {
this.Image = newImage; Image = newImage;
} }
/// <summary> /// <summary>
@ -425,7 +426,7 @@ namespace GreenshotPlugin.Core {
/// The Window Capture code /// The Window Capture code
/// </summary> /// </summary>
public class WindowCapture { public class WindowCapture {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WindowCapture)); private static readonly ILog LOG = LogManager.GetLogger(typeof(WindowCapture));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
/// <summary> /// <summary>

View file

@ -21,6 +21,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO; using System.IO;
@ -33,13 +34,14 @@ using Greenshot.IniFile;
using Greenshot.Interop; using Greenshot.Interop;
using Greenshot.Plugin; using Greenshot.Plugin;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
/// <summary> /// <summary>
/// Code for handling with "windows" /// Code for handling with "windows"
/// Main code is taken from vbAccelerator, location: /// Main code is taken from vbAccelerator, location:
/// http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows/Enumerating_Windows/article.asp /// http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows/Enumerating_Windows/article.asp
/// but a LOT of changes/enhancements were made to adapt it for Greenshot. /// but a LOT of changes/enhancements were made to adapt it for Greenshot.
/// </summary> /// </summary>
using log4net;
namespace GreenshotPlugin.Core { namespace GreenshotPlugin.Core {
#region EnumWindows #region EnumWindows
/// <summary> /// <summary>
@ -56,7 +58,7 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
public List<WindowDetails> Items { public List<WindowDetails> Items {
get { get {
return this.items; return items;
} }
} }
@ -87,9 +89,9 @@ namespace GreenshotPlugin.Core {
/// <param name="hWndParent">Window Handle to get children for</param> /// <param name="hWndParent">Window Handle to get children for</param>
/// <param name="classname">Window Classname to copy, use null to copy all</param> /// <param name="classname">Window Classname to copy, use null to copy all</param>
public WindowsEnumerator GetWindows(IntPtr hWndParent, string classname) { public WindowsEnumerator GetWindows(IntPtr hWndParent, string classname) {
this.items = new List<WindowDetails>(); items = new List<WindowDetails>();
List<WindowDetails> windows = new List<WindowDetails>(); List<WindowDetails> windows = new List<WindowDetails>();
User32.EnumChildWindows(hWndParent, new EnumWindowsProc(this.WindowEnum), 0); User32.EnumChildWindows(hWndParent, new EnumWindowsProc(WindowEnum), 0);
bool hasParent = !IntPtr.Zero.Equals(hWndParent); bool hasParent = !IntPtr.Zero.Equals(hWndParent);
string parentText = null; string parentText = null;
@ -120,7 +122,7 @@ namespace GreenshotPlugin.Core {
/// <param name="lParam">Application defined value</param> /// <param name="lParam">Application defined value</param>
/// <returns>1 to continue enumeration, 0 to stop</returns> /// <returns>1 to continue enumeration, 0 to stop</returns>
private int WindowEnum(IntPtr hWnd, int lParam) { private int WindowEnum(IntPtr hWnd, int lParam) {
if (this.OnWindowEnum(hWnd)) { if (OnWindowEnum(hWnd)) {
return 1; return 1;
} else { } else {
return 0; return 0;
@ -159,13 +161,13 @@ namespace GreenshotPlugin.Core {
/// Provides details about a Window returned by the /// Provides details about a Window returned by the
/// enumeration /// enumeration
/// </summary> /// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")] [SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")]
public class WindowDetails : IEquatable<WindowDetails>{ public class WindowDetails : IEquatable<WindowDetails>{
private const string METRO_WINDOWS_CLASS = "Windows.UI.Core.CoreWindow"; private const string METRO_WINDOWS_CLASS = "Windows.UI.Core.CoreWindow";
private const string METRO_APPLAUNCHER_CLASS = "ImmersiveLauncher"; private const string METRO_APPLAUNCHER_CLASS = "ImmersiveLauncher";
private const string METRO_GUTTER_CLASS = "ImmersiveGutter"; private const string METRO_GUTTER_CLASS = "ImmersiveGutter";
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WindowDetails)); private static ILog LOG = LogManager.GetLogger(typeof(WindowDetails));
private static Dictionary<string, List<string>> classnameTree = new Dictionary<string, List<string>>(); private static Dictionary<string, List<string>> classnameTree = new Dictionary<string, List<string>>();
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private static List<IntPtr> ignoreHandles = new List<IntPtr>(); private static List<IntPtr> ignoreHandles = new List<IntPtr>();
@ -241,19 +243,19 @@ namespace GreenshotPlugin.Core {
} }
public override bool Equals(object right) { public override bool Equals(object right) {
return this.Equals(right as WindowDetails); return Equals(right as WindowDetails);
} }
public bool Equals(WindowDetails other) { public bool Equals(WindowDetails other) {
if (Object.ReferenceEquals(other, null)) { if (ReferenceEquals(other, null)) {
return false; return false;
} }
if (Object.ReferenceEquals(this, other)) { if (ReferenceEquals(this, other)) {
return true; return true;
} }
if (this.GetType() != other.GetType()){ if (GetType() != other.GetType()){
return false; return false;
} }
return other.Handle == Handle; return other.Handle == Handle;
@ -292,7 +294,7 @@ namespace GreenshotPlugin.Core {
public Image DisplayIcon { public Image DisplayIcon {
get { get {
try { try {
using (Icon appIcon = GetAppIcon(this.Handle)) { using (Icon appIcon = GetAppIcon(Handle)) {
if (appIcon != null) { if (appIcon != null) {
return appIcon.ToBitmap(); return appIcon.ToBitmap();
} }
@ -590,7 +592,7 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
public IntPtr Handle { public IntPtr Handle {
get { get {
return this.hWnd; return hWnd;
} }
} }
@ -605,7 +607,7 @@ namespace GreenshotPlugin.Core {
get { get {
if (text == null) { if (text == null) {
StringBuilder title = new StringBuilder(260, 260); StringBuilder title = new StringBuilder(260, 260);
User32.GetWindowText(this.hWnd, title, title.Capacity); User32.GetWindowText(hWnd, title, title.Capacity);
text = title.ToString(); text = title.ToString();
} }
return text; return text;
@ -619,7 +621,7 @@ namespace GreenshotPlugin.Core {
public string ClassName { public string ClassName {
get { get {
if (className == null) { if (className == null) {
className = GetClassName(this.hWnd); className = GetClassName(hWnd);
} }
return className; return className;
} }
@ -633,13 +635,13 @@ namespace GreenshotPlugin.Core {
if (isMetroApp) { if (isMetroApp) {
return !Visible; return !Visible;
} }
return User32.IsIconic(this.hWnd) || Location.X <= -32000; return User32.IsIconic(hWnd) || Location.X <= -32000;
} }
set { set {
if (value) { if (value) {
User32.SendMessage(this.hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MINIMIZE, IntPtr.Zero); User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MINIMIZE, IntPtr.Zero);
} else { } else {
User32.SendMessage(this.hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_RESTORE, IntPtr.Zero); User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_RESTORE, IntPtr.Zero);
} }
} }
} }
@ -662,13 +664,13 @@ namespace GreenshotPlugin.Core {
} }
return false; return false;
} }
return User32.IsZoomed(this.hWnd); return User32.IsZoomed(hWnd);
} }
set { set {
if (value) { if (value) {
User32.SendMessage(this.hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MAXIMIZE, IntPtr.Zero); User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MAXIMIZE, IntPtr.Zero);
} else { } else {
User32.SendMessage(this.hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MINIMIZE, IntPtr.Zero); User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MINIMIZE, IntPtr.Zero);
} }
} }
} }
@ -718,7 +720,7 @@ namespace GreenshotPlugin.Core {
if (isAppLauncher) { if (isAppLauncher) {
return IsAppLauncherVisible; return IsAppLauncherVisible;
} }
return User32.IsWindowVisible(this.hWnd); return User32.IsWindowVisible(hWnd);
} }
} }
@ -846,10 +848,10 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
public void Restore() { public void Restore() {
if (Iconic) { if (Iconic) {
User32.SendMessage(this.hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_RESTORE, IntPtr.Zero); User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_RESTORE, IntPtr.Zero);
} }
User32.BringWindowToTop(this.hWnd); User32.BringWindowToTop(hWnd);
User32.SetForegroundWindow(this.hWnd); User32.SetForegroundWindow(hWnd);
// Make sure windows has time to perform the action // Make sure windows has time to perform the action
while(Iconic) { while(Iconic) {
Application.DoEvents(); Application.DoEvents();
@ -861,10 +863,10 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
public WindowStyleFlags WindowStyle { public WindowStyleFlags WindowStyle {
get { get {
return (WindowStyleFlags)User32.GetWindowLongWrapper(this.hWnd, (int)WindowLongIndex.GWL_STYLE); return (WindowStyleFlags)User32.GetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_STYLE);
} }
set { set {
User32.SetWindowLongWrapper(this.hWnd, (int)WindowLongIndex.GWL_STYLE, (uint)value); User32.SetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_STYLE, (uint)value);
} }
} }
@ -874,11 +876,11 @@ namespace GreenshotPlugin.Core {
public WindowPlacement WindowPlacement { public WindowPlacement WindowPlacement {
get { get {
WindowPlacement placement = WindowPlacement.Default; WindowPlacement placement = WindowPlacement.Default;
User32.GetWindowPlacement(this.Handle, ref placement); User32.GetWindowPlacement(Handle, ref placement);
return placement; return placement;
} }
set { set {
User32.SetWindowPlacement(this.Handle, ref value); User32.SetWindowPlacement(Handle, ref value);
} }
} }
@ -887,10 +889,10 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
public ExtendedWindowStyleFlags ExtendedWindowStyle { public ExtendedWindowStyleFlags ExtendedWindowStyle {
get { get {
return (ExtendedWindowStyleFlags)User32.GetWindowLongWrapper(this.hWnd, (int)WindowLongIndex.GWL_EXSTYLE); return (ExtendedWindowStyleFlags)User32.GetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_EXSTYLE);
} }
set { set {
User32.SetWindowLongWrapper(this.hWnd, (int)WindowLongIndex.GWL_EXSTYLE, (uint)value); User32.SetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_EXSTYLE, (uint)value);
} }
} }
@ -1015,7 +1017,7 @@ namespace GreenshotPlugin.Core {
try { try {
// Check if we make a transparent capture // Check if we make a transparent capture
if (windowCaptureMode == WindowCaptureMode.AeroTransparent) { if (windowCaptureMode == WindowCaptureMode.AeroTransparent) {
frozen = this.FreezeWindow(); frozen = FreezeWindow();
// Use white, later black to capture transparent // Use white, later black to capture transparent
tempForm.BackColor = Color.White; tempForm.BackColor = Color.White;
// Make sure everything is visible // Make sure everything is visible
@ -1073,7 +1075,7 @@ namespace GreenshotPlugin.Core {
// Not needed for Windows 8 // Not needed for Windows 8
if (!(Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2)) { if (!(Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2)) {
// Only if the Inivalue is set, not maximized and it's not a tool window. // Only if the Inivalue is set, not maximized and it's not a tool window.
if (conf.WindowCaptureRemoveCorners && !Maximised && (this.ExtendedWindowStyle & ExtendedWindowStyleFlags.WS_EX_TOOLWINDOW) == 0) { if (conf.WindowCaptureRemoveCorners && !Maximised && (ExtendedWindowStyle & ExtendedWindowStyleFlags.WS_EX_TOOLWINDOW) == 0) {
// Remove corners // Remove corners
if (!Image.IsAlphaPixelFormat(capturedBitmap.PixelFormat)) { if (!Image.IsAlphaPixelFormat(capturedBitmap.PixelFormat)) {
LOG.Debug("Changing pixelformat to Alpha for the RemoveCorners"); LOG.Debug("Changing pixelformat to Alpha for the RemoveCorners");
@ -1088,7 +1090,7 @@ namespace GreenshotPlugin.Core {
} finally { } finally {
// Make sure to ALWAYS unfreeze!! // Make sure to ALWAYS unfreeze!!
if (frozen) { if (frozen) {
this.UnfreezeWindow(); UnfreezeWindow();
} }
} }
@ -1251,7 +1253,7 @@ namespace GreenshotPlugin.Core {
/// Set the window as foreground window /// Set the window as foreground window
/// </summary> /// </summary>
public void ToForeground() { public void ToForeground() {
ToForeground(this.Handle); ToForeground(Handle);
} }
/// <summary> /// <summary>
@ -1290,7 +1292,7 @@ namespace GreenshotPlugin.Core {
/// Warning: Use only if no other way!! /// Warning: Use only if no other way!!
/// </summary> /// </summary>
private bool FreezeWindow() { private bool FreezeWindow() {
Process proc = Process.GetProcessById(this.ProcessId.ToInt32()); Process proc = Process.GetProcessById(ProcessId.ToInt32());
string processName = proc.ProcessName; string processName = proc.ProcessName;
if (!CanFreezeOrUnfreeze(processName)) { if (!CanFreezeOrUnfreeze(processName)) {
LOG.DebugFormat("Not freezing {0}", processName); LOG.DebugFormat("Not freezing {0}", processName);
@ -1320,7 +1322,7 @@ namespace GreenshotPlugin.Core {
/// Unfreeze the process belonging to the window /// Unfreeze the process belonging to the window
/// </summary> /// </summary>
public void UnfreezeWindow() { public void UnfreezeWindow() {
Process proc = Process.GetProcessById(this.ProcessId.ToInt32()); Process proc = Process.GetProcessById(ProcessId.ToInt32());
string processName = proc.ProcessName; string processName = proc.ProcessName;
if (!CanFreezeOrUnfreeze(processName)) { if (!CanFreezeOrUnfreeze(processName)) {
@ -1390,7 +1392,7 @@ namespace GreenshotPlugin.Core {
} }
return null; return null;
} }
if (!HasParent && this.Maximised) { if (!HasParent && Maximised) {
LOG.Debug("Correcting for maximalization"); LOG.Debug("Correcting for maximalization");
Size borderSize = Size.Empty; Size borderSize = Size.Empty;
GetBorderSize(out borderSize); GetBorderSize(out borderSize);
@ -1417,13 +1419,13 @@ namespace GreenshotPlugin.Core {
IntPtr hWnd = User32.GetForegroundWindow(); IntPtr hWnd = User32.GetForegroundWindow();
if (hWnd != null && hWnd != IntPtr.Zero) { if (hWnd != null && hWnd != IntPtr.Zero) {
if (ignoreHandles.Contains(hWnd)) { if (ignoreHandles.Contains(hWnd)) {
return WindowDetails.GetDesktopWindow(); return GetDesktopWindow();
} }
WindowDetails activeWindow = new WindowDetails(hWnd); WindowDetails activeWindow = new WindowDetails(hWnd);
// Invisible Windows should not be active // Invisible Windows should not be active
if (!activeWindow.Visible) { if (!activeWindow.Visible) {
return WindowDetails.GetDesktopWindow(); return GetDesktopWindow();
} }
return activeWindow; return activeWindow;
} }
@ -1507,7 +1509,7 @@ namespace GreenshotPlugin.Core {
List<WindowDetails> windows = new List<WindowDetails>(); List<WindowDetails> windows = new List<WindowDetails>();
Rectangle screenBounds = WindowCapture.GetScreenBounds(); Rectangle screenBounds = WindowCapture.GetScreenBounds();
List<WindowDetails> allWindows = GetMetroApps(); List<WindowDetails> allWindows = GetMetroApps();
allWindows.AddRange(WindowDetails.GetAllWindows()); allWindows.AddRange(GetAllWindows());
foreach(WindowDetails window in allWindows) { foreach(WindowDetails window in allWindows) {
// Ignore windows without title // Ignore windows without title
if (window.Text.Length == 0) { if (window.Text.Length == 0) {
@ -1581,7 +1583,7 @@ namespace GreenshotPlugin.Core {
public static List<WindowDetails> GetTopLevelWindows() { public static List<WindowDetails> GetTopLevelWindows() {
List<WindowDetails> windows = new List<WindowDetails>(); List<WindowDetails> windows = new List<WindowDetails>();
var possibleTopLevelWindows = GetMetroApps(); var possibleTopLevelWindows = GetMetroApps();
possibleTopLevelWindows.AddRange(WindowDetails.GetAllWindows()); possibleTopLevelWindows.AddRange(GetAllWindows());
foreach (WindowDetails window in possibleTopLevelWindows) { foreach (WindowDetails window in possibleTopLevelWindows) {
// Ignore windows without title // Ignore windows without title
if (window.Text.Length == 0) { if (window.Text.Length == 0) {
@ -1621,7 +1623,7 @@ namespace GreenshotPlugin.Core {
/// <returns></returns> /// <returns></returns>
public static WindowDetails GetLinkedWindow(WindowDetails windowToLinkTo) { public static WindowDetails GetLinkedWindow(WindowDetails windowToLinkTo) {
IntPtr processIdSelectedWindow = windowToLinkTo.ProcessId; IntPtr processIdSelectedWindow = windowToLinkTo.ProcessId;
foreach(WindowDetails window in WindowDetails.GetAllWindows()) { foreach(WindowDetails window in GetAllWindows()) {
// Ignore windows without title // Ignore windows without title
if (window.Text.Length == 0) { if (window.Text.Length == 0) {
continue; continue;
@ -1657,7 +1659,7 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
/// <param name="oldWindows">List<WindowDetails> with old windows</param> /// <param name="oldWindows">List<WindowDetails> with old windows</param>
public static void ActiveNewerWindows(List<WindowDetails> oldWindows) { public static void ActiveNewerWindows(List<WindowDetails> oldWindows) {
List<WindowDetails> windowsAfter = WindowDetails.GetVisibleWindows(); List<WindowDetails> windowsAfter = GetVisibleWindows();
foreach(WindowDetails window in windowsAfter) { foreach(WindowDetails window in windowsAfter) {
if (!oldWindows.Contains(window)) { if (!oldWindows.Contains(window)) {
window.ToForeground(); window.ToForeground();

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport, Guid("3050F1D8-98B5-11CF-BB82-00AA00BDCE0B"), [ComImport, Guid("3050F1D8-98B5-11CF-BB82-00AA00BDCE0B"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLBodyElement { public interface IHTMLBodyElement {
string scroll { string scroll {
set; set;

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport, Guid("3050f3db-98b5-11cf-bb82-00aa00bdce0b"), [ComImport, Guid("3050f3db-98b5-11cf-bb82-00aa00bdce0b"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLCurrentStyle { public interface IHTMLCurrentStyle {
/// <summary><para><c>styleFloat</c> property of <c>IHTMLStyle</c> interface.</para></summary> /// <summary><para><c>styleFloat</c> property of <c>IHTMLStyle</c> interface.</para></summary>
string styleFloat { string styleFloat {

View file

@ -26,7 +26,7 @@ namespace Greenshot.Interop.IE {
[Guid("626FC520-A41E-11CF-A731-00A0C9082637")] [Guid("626FC520-A41E-11CF-A731-00A0C9082637")]
[ComImport] [ComImport]
[TypeLibType(TypeLibTypeFlags.FDual)] [TypeLibType(TypeLibTypeFlags.FDual)]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLDocument { public interface IHTMLDocument {
object Script { object Script {
[return: MarshalAs(UnmanagedType.IDispatch)] [return: MarshalAs(UnmanagedType.IDispatch)]

View file

@ -26,7 +26,7 @@ namespace Greenshot.Interop.IE {
[Guid("332C4425-26CB-11D0-B483-00C04FD90119")] [Guid("332C4425-26CB-11D0-B483-00C04FD90119")]
[ComImport] [ComImport]
[TypeLibType(TypeLibTypeFlags.FDual)] [TypeLibType(TypeLibTypeFlags.FDual)]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLDocument2 { public interface IHTMLDocument2 {
IHTMLElement body { IHTMLElement body {
[DispId(1004)] [DispId(1004)]

View file

@ -26,7 +26,7 @@ namespace Greenshot.Interop.IE {
[Guid("3050F485-98B5-11CF-BB82-00AA00BDCE0B")] [Guid("3050F485-98B5-11CF-BB82-00AA00BDCE0B")]
[ComImport] [ComImport]
[TypeLibType(TypeLibTypeFlags.FDual)] [TypeLibType(TypeLibTypeFlags.FDual)]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLDocument3 { public interface IHTMLDocument3 {
IHTMLElement documentElement { IHTMLElement documentElement {
[DispId(1075)] [DispId(1075)]

View file

@ -23,7 +23,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComVisible(true), Guid("3050f69a-98b5-11cf-bb82-00aa00bdce0b"), [ComVisible(true), Guid("3050f69a-98b5-11cf-bb82-00aa00bdce0b"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
TypeLibType(TypeLibTypeFlags.FDual)] TypeLibType(TypeLibTypeFlags.FDual)]
public interface IHTMLDocument4 { public interface IHTMLDocument4 {
[DispId(1090)] [DispId(1090)]

View file

@ -23,7 +23,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport, ComVisible(true), Guid("3050f80c-98b5-11cf-bb82-00aa00bdce0b"), [ComImport, ComVisible(true), Guid("3050f80c-98b5-11cf-bb82-00aa00bdce0b"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
TypeLibType(TypeLibTypeFlags.FDual)] TypeLibType(TypeLibTypeFlags.FDual)]
public interface IHTMLDocument5 { public interface IHTMLDocument5 {
[DispId(1102)] [DispId(1102)]

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport, Guid("3050F1FF-98B5-11CF-BB82-00AA00BDCE0B"), [ComImport, Guid("3050F1FF-98B5-11CF-BB82-00AA00BDCE0B"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLElement { public interface IHTMLElement {
[DispId(-2147417611)] [DispId(-2147417611)]
void setAttribute([MarshalAs(UnmanagedType.BStr)] string strAttributeName, object AttributeValue, int lFlags); void setAttribute([MarshalAs(UnmanagedType.BStr)] string strAttributeName, object AttributeValue, int lFlags);

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport, Guid("3050F434-98B5-11CF-BB82-00AA00BDCE0B"), [ComImport, Guid("3050F434-98B5-11CF-BB82-00AA00BDCE0B"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLElement2 { public interface IHTMLElement2 {
[DispId(-2147417067)] [DispId(-2147417067)]
[return: MarshalAs(UnmanagedType.IDispatch)] [return: MarshalAs(UnmanagedType.IDispatch)]

View file

@ -25,7 +25,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport(), ComVisible(true), [ComImport(), ComVisible(true),
Guid("3050F21F-98B5-11CF-BB82-00AA00BDCE0B"), Guid("3050F21F-98B5-11CF-BB82-00AA00BDCE0B"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
TypeLibType(TypeLibTypeFlags.FDispatchable)] TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLElementCollection : IEnumerable { public interface IHTMLElementCollection : IEnumerable {
new IEnumerator GetEnumerator(); new IEnumerator GetEnumerator();

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComVisible(true), ComImport(), Guid("3050f311-98b5-11cf-bb82-00aa00bdce0b"), [ComVisible(true), ComImport(), Guid("3050f311-98b5-11cf-bb82-00aa00bdce0b"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLFrameBase { public interface IHTMLFrameBase {
//dispinterface IHTMLFrameBase { //dispinterface IHTMLFrameBase {
// properties: // properties:

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport(), ComVisible(true), [ComImport(), ComVisible(true),
Guid("332C4426-26CB-11D0-B483-00C04FD90119"), Guid("332C4426-26CB-11D0-B483-00C04FD90119"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
TypeLibType(TypeLibTypeFlags.FDispatchable)] TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLFramesCollection2 { public interface IHTMLFramesCollection2 {
[DispId(0)] [DispId(0)]

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport, Guid("3050F4A3-98B5-11CF-BB82-00AA00BDCE0B"), [ComImport, Guid("3050F4A3-98B5-11CF-BB82-00AA00BDCE0B"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLRect { public interface IHTMLRect {
int bottom { int bottom {
[DispId(1004)] [DispId(1004)]

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport, Guid("3050F35C-98B5-11CF-BB82-00AA00BDCE0B"), [ComImport, Guid("3050F35C-98B5-11CF-BB82-00AA00BDCE0B"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLScreen { public interface IHTMLScreen {
[DispId(1003)] [DispId(1003)]
int width { int width {

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport, Guid("3050F84A-98B5-11CF-BB82-00AA00BDCE0B"), [ComImport, Guid("3050F84A-98B5-11CF-BB82-00AA00BDCE0B"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLScreen2 { public interface IHTMLScreen2 {
int logicalXDPI { int logicalXDPI {
[DispId(1009)] [DispId(1009)]

View file

@ -25,7 +25,7 @@ namespace Greenshot.Interop.IE {
// See: http://msdn.microsoft.com/en-us/library/aa768849%28v=vs.85%29.aspx // See: http://msdn.microsoft.com/en-us/library/aa768849%28v=vs.85%29.aspx
[ComImport, Guid("3050f25A-98b5-11cf-bb82-00aa00bdce0b"), [ComImport, Guid("3050f25A-98b5-11cf-bb82-00aa00bdce0b"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLSelectionObject { public interface IHTMLSelectionObject {
[return: MarshalAs(UnmanagedType.IDispatch)] [return: MarshalAs(UnmanagedType.IDispatch)]
[DispId(1001)] [DispId(1001)]

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComImport, Guid("3050F25E-98B5-11CF-BB82-00AA00BDCE0B"), [ComImport, Guid("3050F25E-98B5-11CF-BB82-00AA00BDCE0B"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLStyle { public interface IHTMLStyle {
/// <summary><para><c>setAttribute</c> method of <c>IHTMLStyle</c> interface.</para></summary> /// <summary><para><c>setAttribute</c> method of <c>IHTMLStyle</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>setAttribute</c> method was the following: <c>HRESULT setAttribute (BSTR strAttributeName, VARIANT AttributeValue, [optional, defaultvalue(1)] long lFlags)</c>;</para></remarks> /// <remarks><para>An original IDL definition of <c>setAttribute</c> method was the following: <c>HRESULT setAttribute (BSTR strAttributeName, VARIANT AttributeValue, [optional, defaultvalue(1)] long lFlags)</c>;</para></remarks>

View file

@ -25,7 +25,7 @@ namespace Greenshot.Interop.IE {
// See: http://msdn.microsoft.com/en-us/library/aa741548%28v=vs.85%29.aspx // See: http://msdn.microsoft.com/en-us/library/aa741548%28v=vs.85%29.aspx
[ComImport, Guid("3050F220-98B5-11CF-BB82-00AA00BDCE0B"), [ComImport, Guid("3050F220-98B5-11CF-BB82-00AA00BDCE0B"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLTxtRange { public interface IHTMLTxtRange {
[DispId(1006)] [DispId(1006)]
IHTMLElement parentElement(); IHTMLElement parentElement();

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComVisible(true), ComImport(), Guid("332c4427-26cb-11d0-b483-00c04fd90119"), [ComVisible(true), ComImport(), Guid("332c4427-26cb-11d0-b483-00c04fd90119"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLWindow2 { public interface IHTMLWindow2 {
[DispId(1156)] [DispId(1156)]
IHTMLScreen screen { IHTMLScreen screen {

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComVisible(true), ComImport(), Guid("3050f4ae-98b5-11cf-bb82-00aa00bdce0b"), [ComVisible(true), ComImport(), Guid("3050f4ae-98b5-11cf-bb82-00aa00bdce0b"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLWindow3 { public interface IHTMLWindow3 {
[DispId(1170)] [DispId(1170)]
int screenLeft { get;} int screenLeft { get;}

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop.IE { namespace Greenshot.Interop.IE {
[ComVisible(true), ComImport(), Guid("3050f6cf-98b5-11cf-bb82-00aa00bdce0b"), [ComVisible(true), ComImport(), Guid("3050f6cf-98b5-11cf-bb82-00aa00bdce0b"),
TypeLibType(TypeLibTypeFlags.FDual), TypeLibType(TypeLibTypeFlags.FDual),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLWindow4 { public interface IHTMLWindow4 {
[DispId(1181)] [DispId(1181)]
IHTMLFrameBase frameElement { IHTMLFrameBase frameElement {

View file

@ -46,7 +46,7 @@ namespace Greenshot.IniFile {
Separator = ","; Separator = ",";
} }
public IniPropertyAttribute(string name) : this() { public IniPropertyAttribute(string name) : this() {
this.Name = name; Name = name;
} }
public string Description { public string Description {
get; get;

View file

@ -24,10 +24,11 @@ using System.IO;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using log4net;
namespace Greenshot.IniFile { namespace Greenshot.IniFile {
public class IniConfig { public class IniConfig {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IniConfig)); private static ILog LOG = LogManager.GetLogger(typeof(IniConfig));
private const string INI_EXTENSION = ".ini"; private const string INI_EXTENSION = ".ini";
private const string DEFAULTS_POSTFIX = "-defaults"; private const string DEFAULTS_POSTFIX = "-defaults";
private const string FIXED_POSTFIX = "-fixed"; private const string FIXED_POSTFIX = "-fixed";
@ -358,7 +359,7 @@ namespace Greenshot.IniFile {
} }
if (allowSave && section.IsDirty) { if (allowSave && section.IsDirty) {
LOG.DebugFormat("Section {0} is marked dirty, saving!", sectionName); LOG.DebugFormat("Section {0} is marked dirty, saving!", sectionName);
IniConfig.Save(); Save();
} }
return section; return section;
} }

View file

@ -23,6 +23,7 @@ using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.IO; using System.IO;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using log4net;
namespace Greenshot.IniFile { namespace Greenshot.IniFile {
/// <summary> /// <summary>
@ -30,7 +31,7 @@ namespace Greenshot.IniFile {
/// </summary> /// </summary>
[Serializable] [Serializable]
public abstract class IniSection { public abstract class IniSection {
protected static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IniSection)); protected static ILog LOG = LogManager.GetLogger(typeof(IniSection));
[NonSerialized] [NonSerialized]
private IDictionary<string, IniValue> values = new Dictionary<string, IniValue>(); private IDictionary<string, IniValue> values = new Dictionary<string, IniValue>();
@ -39,7 +40,7 @@ namespace Greenshot.IniFile {
public IniSectionAttribute IniSectionAttribute { public IniSectionAttribute IniSectionAttribute {
get { get {
if (iniSectionAttribute == null) { if (iniSectionAttribute == null) {
iniSectionAttribute = GetIniSectionAttribute(this.GetType()); iniSectionAttribute = GetIniSectionAttribute(GetType());
} }
return iniSectionAttribute; return iniSectionAttribute;
} }
@ -117,7 +118,7 @@ namespace Greenshot.IniFile {
/// </summary> /// </summary>
/// <param name="properties"></param> /// <param name="properties"></param>
public void Fill(Dictionary<string, string> properties) { public void Fill(Dictionary<string, string> properties) {
Type iniSectionType = this.GetType(); Type iniSectionType = GetType();
// Iterate over the members and create IniValueContainers // Iterate over the members and create IniValueContainers
foreach (FieldInfo fieldInfo in iniSectionType.GetFields()) { foreach (FieldInfo fieldInfo in iniSectionType.GetFields()) {

View file

@ -24,13 +24,14 @@ using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.IO; using System.IO;
using System.Text; using System.Text;
using log4net;
namespace Greenshot.IniFile { namespace Greenshot.IniFile {
/// <summary> /// <summary>
/// A container to be able to pass the value from a IniSection around. /// A container to be able to pass the value from a IniSection around.
/// </summary> /// </summary>
public class IniValue { public class IniValue {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IniValue)); private static ILog LOG = LogManager.GetLogger(typeof(IniValue));
private PropertyInfo propertyInfo; private PropertyInfo propertyInfo;
private FieldInfo fieldInfo; private FieldInfo fieldInfo;
private IniSection containingIniSection; private IniSection containingIniSection;
@ -39,13 +40,13 @@ namespace Greenshot.IniFile {
public IniValue(IniSection containingIniSection, PropertyInfo propertyInfo, IniPropertyAttribute iniPropertyAttribute) { public IniValue(IniSection containingIniSection, PropertyInfo propertyInfo, IniPropertyAttribute iniPropertyAttribute) {
this.containingIniSection = containingIniSection; this.containingIniSection = containingIniSection;
this.propertyInfo = propertyInfo; this.propertyInfo = propertyInfo;
this.attributes = iniPropertyAttribute; attributes = iniPropertyAttribute;
} }
public IniValue(IniSection containingIniSection, FieldInfo fieldInfo, IniPropertyAttribute iniPropertyAttribute) { public IniValue(IniSection containingIniSection, FieldInfo fieldInfo, IniPropertyAttribute iniPropertyAttribute) {
this.containingIniSection = containingIniSection; this.containingIniSection = containingIniSection;
this.fieldInfo = fieldInfo; this.fieldInfo = fieldInfo;
this.attributes = iniPropertyAttribute; attributes = iniPropertyAttribute;
} }
/// <summary> /// <summary>
@ -318,7 +319,7 @@ namespace Greenshot.IniFile {
try { try {
LOG.WarnFormat("Problem '{0}' while converting {1} to type {2} trying fallback...", ex1.Message, propertyValue, valueType.FullName); LOG.WarnFormat("Problem '{0}' while converting {1} to type {2} trying fallback...", ex1.Message, propertyValue, valueType.FullName);
newValue = ConvertStringToValueType(valueType, defaultValue, attributes.Separator); newValue = ConvertStringToValueType(valueType, defaultValue, attributes.Separator);
this.ContainingIniSection.IsDirty = true; ContainingIniSection.IsDirty = true;
LOG.InfoFormat("Used default value {0} for property {1}", defaultValue, propertyName); LOG.InfoFormat("Used default value {0} for property {1}", defaultValue, propertyName);
} catch (Exception ex2) { } catch (Exception ex2) {
LOG.Warn("Problem converting fallback value " + defaultValue + " to type " + valueType.FullName, ex2); LOG.Warn("Problem converting fallback value " + defaultValue + " to type " + valueType.FullName, ex2);

View file

@ -30,7 +30,7 @@ using Greenshot.Core;
namespace Greenshot.Plugin { namespace Greenshot.Plugin {
[Serializable] [Serializable]
[AttributeUsageAttribute(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
sealed public class PluginAttribute : Attribute, IComparable { sealed public class PluginAttribute : Attribute, IComparable {
public string Name { public string Name {
get; get;
@ -59,8 +59,8 @@ namespace Greenshot.Plugin {
} }
public PluginAttribute(string entryType, bool configurable) { public PluginAttribute(string entryType, bool configurable) {
this.EntryType = entryType; EntryType = entryType;
this.Configurable = configurable; Configurable = configurable;
} }
public int CompareTo(object obj) { public int CompareTo(object obj) {

View file

@ -26,13 +26,14 @@ using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies; using System.Runtime.Remoting.Proxies;
using System.Windows.Forms; using System.Windows.Forms;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using log4net;
namespace Greenshot.Interop { namespace Greenshot.Interop {
/// <summary> /// <summary>
/// Wraps a late-bound COM server. /// Wraps a late-bound COM server.
/// </summary> /// </summary>
public sealed class COMWrapper : RealProxy, IDisposable, IRemotingTypeInfo { public sealed class COMWrapper : RealProxy, IDisposable, IRemotingTypeInfo {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(COMWrapper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(COMWrapper));
private const int MK_E_UNAVAILABLE = -2147221021; private const int MK_E_UNAVAILABLE = -2147221021;
private const int CO_E_CLASSSTRING = -2147221005; private const int CO_E_CLASSSTRING = -2147221005;
public const int RPC_E_CALL_REJECTED = unchecked((int)0x80010001); public const int RPC_E_CALL_REJECTED = unchecked((int)0x80010001);
@ -317,10 +318,10 @@ namespace Greenshot.Interop {
/// The interface type to impersonate. /// The interface type to impersonate.
/// </param> /// </param>
private COMWrapper(object comObject, Type type, string targetName) : base(type) { private COMWrapper(object comObject, Type type, string targetName) : base(type) {
this._COMObject = comObject; _COMObject = comObject;
this._COMType = comObject.GetType(); _COMType = comObject.GetType();
this._InterceptType = type; _InterceptType = type;
this._TargetName = targetName; _TargetName = targetName;
} }
#endregion #endregion
@ -332,15 +333,15 @@ namespace Greenshot.Interop {
/// sure that the COM object is still cleaned up. /// sure that the COM object is still cleaned up.
/// </summary> /// </summary>
~COMWrapper() { ~COMWrapper() {
LOG.DebugFormat("Finalize {0}", this._InterceptType.ToString()); LOG.DebugFormat("Finalize {0}", _InterceptType.ToString());
this.Dispose(false); Dispose(false);
} }
/// <summary> /// <summary>
/// Cleans up the COM object. /// Cleans up the COM object.
/// </summary> /// </summary>
public void Dispose() { public void Dispose() {
this.Dispose(true); Dispose(true);
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
@ -352,18 +353,18 @@ namespace Greenshot.Interop {
/// <see cref="IDisposable"/> interface. /// <see cref="IDisposable"/> interface.
/// </param> /// </param>
private void Dispose(bool disposing) { private void Dispose(bool disposing) {
if (null != this._COMObject) { if (null != _COMObject) {
LOG.DebugFormat("Disposing {0}", this._InterceptType.ToString()); LOG.DebugFormat("Disposing {0}", _InterceptType.ToString());
if (Marshal.IsComObject(this._COMObject)) { if (Marshal.IsComObject(_COMObject)) {
try { try {
while (Marshal.ReleaseComObject(this._COMObject) > 0) ; while (Marshal.ReleaseComObject(_COMObject) > 0) ;
} catch (Exception ex) { } catch (Exception ex) {
LOG.WarnFormat("Problem releasing {0}", _COMType); LOG.WarnFormat("Problem releasing {0}", _COMType);
LOG.Warn("Error: ", ex); LOG.Warn("Error: ", ex);
} }
} }
this._COMObject = null; _COMObject = null;
} }
} }
@ -378,7 +379,7 @@ namespace Greenshot.Interop {
/// The full name of the intercepted type. /// The full name of the intercepted type.
/// </returns> /// </returns>
public override string ToString() { public override string ToString() {
return this._InterceptType.FullName; return _InterceptType.FullName;
} }
/// <summary> /// <summary>
@ -388,7 +389,7 @@ namespace Greenshot.Interop {
/// The hash code of the wrapped object. /// The hash code of the wrapped object.
/// </returns> /// </returns>
public override int GetHashCode() { public override int GetHashCode() {
return this._COMObject.GetHashCode(); return _COMObject.GetHashCode();
} }
/// <summary> /// <summary>
@ -404,7 +405,7 @@ namespace Greenshot.Interop {
if (null != value && RemotingServices.IsTransparentProxy(value)) { if (null != value && RemotingServices.IsTransparentProxy(value)) {
COMWrapper wrapper = RemotingServices.GetRealProxy(value) as COMWrapper; COMWrapper wrapper = RemotingServices.GetRealProxy(value) as COMWrapper;
if (null != wrapper) { if (null != wrapper) {
return this._COMObject == wrapper._COMObject; return _COMObject == wrapper._COMObject;
} }
} }
@ -575,15 +576,15 @@ namespace Greenshot.Interop {
ParameterInfo parameter; ParameterInfo parameter;
if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType) { if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType) {
this.Dispose(); Dispose();
} else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType) { } else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType) {
returnValue = this.ToString(); returnValue = ToString();
} else if ("GetType" == methodName && 0 == argCount && typeof(System.Type) == returnType) { } else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType) {
returnValue = this._InterceptType; returnValue = _InterceptType;
} else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType) { } else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType) {
returnValue = this.GetHashCode(); returnValue = GetHashCode();
} else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType) { } else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType) {
returnValue = this.Equals(callMessage.Args[0]); returnValue = Equals(callMessage.Args[0]);
} else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_"))) { } else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_"))) {
bool removeHandler = methodName.StartsWith("remove_"); bool removeHandler = methodName.StartsWith("remove_");
methodName = methodName.Substring(removeHandler ? 7 : 4); methodName = methodName.Substring(removeHandler ? 7 : 4);
@ -593,8 +594,8 @@ namespace Greenshot.Interop {
return new ReturnMessage(new ArgumentNullException("handler"), callMessage); return new ReturnMessage(new ArgumentNullException("handler"), callMessage);
} }
} else { } else {
invokeObject = this._COMObject; invokeObject = _COMObject;
invokeType = this._COMType; invokeType = _COMType;
if (methodName.StartsWith("get_")) { if (methodName.StartsWith("get_")) {
// Property Get // Property Get
@ -670,7 +671,7 @@ namespace Greenshot.Interop {
if (comEx == null) { if (comEx == null) {
comEx = ex.InnerException as COMException; comEx = ex.InnerException as COMException;
} }
if (comEx != null && (comEx.ErrorCode == RPC_E_CALL_REJECTED || comEx.ErrorCode == COMWrapper.RPC_E_FAIL)) { if (comEx != null && (comEx.ErrorCode == RPC_E_CALL_REJECTED || comEx.ErrorCode == RPC_E_FAIL)) {
string destinationName = _TargetName; string destinationName = _TargetName;
// Try to find a "catchy" name for the rejecting application // Try to find a "catchy" name for the rejecting application
if (destinationName != null && destinationName.Contains(".")) { if (destinationName != null && destinationName.Contains(".")) {
@ -694,7 +695,7 @@ namespace Greenshot.Interop {
if (returnType.IsInterface) { if (returnType.IsInterface) {
// Wrap the returned value in an intercepting COM wrapper // Wrap the returned value in an intercepting COM wrapper
if (Marshal.IsComObject(returnValue)) { if (Marshal.IsComObject(returnValue)) {
returnValue = COMWrapper.Wrap(returnValue, returnType, _TargetName); returnValue = Wrap(returnValue, returnType, _TargetName);
} }
} else if (returnType.IsEnum) { } else if (returnType.IsEnum) {
// Convert to proper Enum type // Convert to proper Enum type

View file

@ -24,7 +24,7 @@ using System.Runtime.InteropServices;
namespace Greenshot.Interop { namespace Greenshot.Interop {
// This is the COM IServiceProvider interface, not System.IServiceProvider .Net interface! // This is the COM IServiceProvider interface, not System.IServiceProvider .Net interface!
[ComImport(), ComVisible(true), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), [ComImport(), ComVisible(true), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IServiceProvider { public interface IServiceProvider {
[return: MarshalAs(UnmanagedType.I4)][PreserveSig] [return: MarshalAs(UnmanagedType.I4)][PreserveSig]
int QueryService(ref Guid guidService, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject); int QueryService(ref Guid guidService, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject);

View file

@ -117,10 +117,10 @@ namespace GreenshotPlugin.UnmanagedHelpers {
public static extern uint DwmEnableComposition(uint uCompositionAction); public static extern uint DwmEnableComposition(uint uCompositionAction);
public static void EnableComposition() { public static void EnableComposition() {
DWM.DwmEnableComposition(DWM.DWM_EC_ENABLECOMPOSITION); DwmEnableComposition(DWM_EC_ENABLECOMPOSITION);
} }
public static void DisableComposition() { public static void DisableComposition() {
DWM.DwmEnableComposition(DWM.DWM_EC_DISABLECOMPOSITION); DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);
} }
// Key to ColorizationColor for DWM // Key to ColorizationColor for DWM
@ -139,7 +139,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
} }
if (Environment.OSVersion.Version.Major >= 6) { if (Environment.OSVersion.Version.Major >= 6) {
bool dwmEnabled; bool dwmEnabled;
DWM.DwmIsCompositionEnabled(out dwmEnabled); DwmIsCompositionEnabled(out dwmEnabled);
return dwmEnabled; return dwmEnabled;
} }
return false; return false;

View file

@ -22,6 +22,7 @@ using System;
using System.Drawing; using System.Drawing;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security; using System.Security;
using log4net;
using Microsoft.Win32.SafeHandles; using Microsoft.Win32.SafeHandles;
using System.Reflection; using System.Reflection;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
@ -93,7 +94,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// GDIplus Helpers /// GDIplus Helpers
/// </summary> /// </summary>
public static class GDIplus { public static class GDIplus {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(GDIplus)); private static ILog LOG = LogManager.GetLogger(typeof(GDIplus));
[DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)] [DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
private static extern int GdipBitmapApplyEffect(IntPtr bitmap, IntPtr effect, ref RECT rectOfInterest, bool useAuxData, IntPtr auxData, int auxDataSize); private static extern int GdipBitmapApplyEffect(IntPtr bitmap, IntPtr effect, ref RECT rectOfInterest, bool useAuxData, IntPtr auxData, int auxDataSize);

View file

@ -76,23 +76,23 @@ namespace GreenshotPlugin.UnmanagedHelpers {
// Try the GetModuleFileName method first since it's the fastest. // Try the GetModuleFileName method first since it's the fastest.
// May return ACCESS_DENIED (due to VM_READ flag) if the process is not owned by the current user. // May return ACCESS_DENIED (due to VM_READ flag) if the process is not owned by the current user.
// Will fail if we are compiled as x86 and we're trying to open a 64 bit process...not allowed. // Will fail if we are compiled as x86 and we're trying to open a 64 bit process...not allowed.
IntPtr hprocess = Kernel32.OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VMRead, false, processid); IntPtr hprocess = OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VMRead, false, processid);
if (hprocess != IntPtr.Zero) { if (hprocess != IntPtr.Zero) {
try { try {
if (PsAPI.GetModuleFileNameEx(hprocess, IntPtr.Zero, _PathBuffer, (uint)_PathBuffer.Capacity) > 0) { if (PsAPI.GetModuleFileNameEx(hprocess, IntPtr.Zero, _PathBuffer, (uint)_PathBuffer.Capacity) > 0) {
return _PathBuffer.ToString(); return _PathBuffer.ToString();
} }
} finally { } finally {
Kernel32.CloseHandle(hprocess); CloseHandle(hprocess);
} }
} }
hprocess = Kernel32.OpenProcess(ProcessAccessFlags.QueryInformation, false, processid); hprocess = OpenProcess(ProcessAccessFlags.QueryInformation, false, processid);
if (hprocess != IntPtr.Zero) { if (hprocess != IntPtr.Zero) {
try { try {
// Try this method for Vista or higher operating systems // Try this method for Vista or higher operating systems
uint size = (uint)_PathBuffer.Capacity; uint size = (uint)_PathBuffer.Capacity;
if ((Environment.OSVersion.Version.Major >= 6) && (Kernel32.QueryFullProcessImageName(hprocess, 0, _PathBuffer, ref size) && (size > 0))) { if ((Environment.OSVersion.Version.Major >= 6) && (QueryFullProcessImageName(hprocess, 0, _PathBuffer, ref size) && (size > 0))) {
return _PathBuffer.ToString(); return _PathBuffer.ToString();
} }
@ -100,7 +100,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
if (PsAPI.GetProcessImageFileName(hprocess, _PathBuffer, (uint)_PathBuffer.Capacity) > 0) { if (PsAPI.GetProcessImageFileName(hprocess, _PathBuffer, (uint)_PathBuffer.Capacity) > 0) {
string dospath = _PathBuffer.ToString(); string dospath = _PathBuffer.ToString();
foreach (string drive in Environment.GetLogicalDrives()) { foreach (string drive in Environment.GetLogicalDrives()) {
if (Kernel32.QueryDosDevice(drive.TrimEnd('\\'), _PathBuffer, (uint)_PathBuffer.Capacity) > 0) { if (QueryDosDevice(drive.TrimEnd('\\'), _PathBuffer, (uint)_PathBuffer.Capacity) > 0) {
if (dospath.StartsWith(_PathBuffer.ToString())) { if (dospath.StartsWith(_PathBuffer.ToString())) {
return drive + dospath.Remove(0, _PathBuffer.Length); return drive + dospath.Remove(0, _PathBuffer.Length);
} }
@ -108,7 +108,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
} }
} }
} finally { } finally {
Kernel32.CloseHandle(hprocess); CloseHandle(hprocess);
} }
} }

View file

@ -44,19 +44,19 @@ namespace GreenshotPlugin.UnmanagedHelpers {
public int Y; public int Y;
public POINT(int x, int y) { public POINT(int x, int y) {
this.X = x; X = x;
this.Y = y; Y = y;
} }
public POINT(Point point) { public POINT(Point point) {
this.X = point.X; X = point.X;
this.Y = point.Y; Y = point.Y;
} }
public static implicit operator System.Drawing.Point(POINT p) { public static implicit operator Point(POINT p) {
return new System.Drawing.Point(p.X, p.Y); return new Point(p.X, p.Y);
} }
public static implicit operator POINT(System.Drawing.Point p) { public static implicit operator POINT(Point p) {
return new POINT(p.X, p.Y); return new POINT(p.X, p.Y);
} }

View file

@ -24,7 +24,7 @@ using System.Diagnostics;
using System.Drawing; using System.Drawing;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Windows.Forms;
using Microsoft.Win32.SafeHandles; using Microsoft.Win32.SafeHandles;
using System.Security; using System.Security;
using System.Security.Permissions; using System.Security.Permissions;
@ -136,7 +136,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
[return: MarshalAs(UnmanagedType.Bool)] [return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowScrollBar(IntPtr hwnd, ScrollBarDirection scrollBar, bool show); public static extern bool ShowScrollBar(IntPtr hwnd, ScrollBarDirection scrollBar, bool show);
[DllImport("user32", SetLastError = true)] [DllImport("user32", SetLastError = true)]
public static extern int SetScrollPos(IntPtr hWnd, System.Windows.Forms.Orientation nBar, int nPos, bool bRedraw); public static extern int SetScrollPos(IntPtr hWnd, Orientation nBar, int nPos, bool bRedraw);
[DllImport("user32", SetLastError=true, EntryPoint = "PostMessageA")] [DllImport("user32", SetLastError=true, EntryPoint = "PostMessageA")]
public static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam); public static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
[DllImport("user32", SetLastError = true)] [DllImport("user32", SetLastError = true)]
@ -295,12 +295,12 @@ namespace GreenshotPlugin.UnmanagedHelpers {
} }
public SafeIconHandle(IntPtr hIcon) : base(true) { public SafeIconHandle(IntPtr hIcon) : base(true) {
this.SetHandle(hIcon); SetHandle(hIcon);
} }
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
protected override bool ReleaseHandle() { protected override bool ReleaseHandle() {
return User32.DestroyIcon(this.handle); return User32.DestroyIcon(handle);
} }
} }

View file

@ -27,9 +27,9 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// </summary> /// </summary>
public class WinMM { public class WinMM {
[DllImport("winmm.dll", SetLastError = true)] [DllImport("winmm.dll", SetLastError = true)]
public static extern bool PlaySound(byte[] ptrToSound, System.UIntPtr hmod, uint fdwSound); public static extern bool PlaySound(byte[] ptrToSound, UIntPtr hmod, uint fdwSound);
[DllImport("winmm.dll", SetLastError = true)] [DllImport("winmm.dll", SetLastError = true)]
public static extern bool PlaySound(IntPtr ptrToSound, System.UIntPtr hmod, uint fdwSound); public static extern bool PlaySound(IntPtr ptrToSound, UIntPtr hmod, uint fdwSound);
} }
} }