Modified loggers to use their enclosing class
[pithos-ms-client] / trunk / Pithos.ShellExtensions / Overlays / IconOverlayBase.cs
1 #region
2 /* -----------------------------------------------------------------------
3  * <copyright file="IconOverlayBase.cs" company="GRNet">
4  * 
5  * Copyright 2011-2012 GRNET S.A. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or
8  * without modification, are permitted provided that the following
9  * conditions are met:
10  *
11  *   1. Redistributions of source code must retain the above
12  *      copyright notice, this list of conditions and the following
13  *      disclaimer.
14  *
15  *   2. Redistributions in binary form must reproduce the above
16  *      copyright notice, this list of conditions and the following
17  *      disclaimer in the documentation and/or other materials
18  *      provided with the distribution.
19  *
20  *
21  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  * The views and conclusions contained in the software and
35  * documentation are those of the authors and should not be
36  * interpreted as representing official policies, either expressed
37  * or implied, of GRNET S.A.
38  * </copyright>
39  * -----------------------------------------------------------------------
40  */
41 #endregion
42 using System;
43 using System.Diagnostics;
44 using System.Diagnostics.Contracts;
45 using System.IO;
46
47 using System.ComponentModel.Composition;
48 using System.Linq;
49 using System.Reflection;
50 using Microsoft.Win32;
51 using Pithos.Interfaces;
52
53 namespace Pithos.ShellExtensions.Overlays
54 {
55
56     public class IconOverlayBase : IShellIconOverlayIdentifier
57     {
58         private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
59
60         protected static string PithosPrefix = "0Pithos";
61
62         public string OverlayName { get; private set; }
63         public string IconPath { get; private set; }
64
65         [Import(typeof (IStatusChecker))] 
66         public IStatusChecker StatusChecker;
67         [Import(typeof (IPithosSettings))] 
68         public IPithosSettings Settings;
69
70
71
72         public IconOverlayBase(string iconName)
73         {
74             if (String.IsNullOrWhiteSpace(iconName))
75                 throw new ArgumentNullException("iconName","Empty iconName");
76
77             Debug.WriteLine("Icon Overlay Instance created", LogCategories.ShellOverlays);
78             IoC.Current.Compose(this);
79             
80
81             string overlayName=PithosPrefix + iconName;
82             string iconFile = iconName + "Icon.ico";
83
84
85             var iconsFolder = Settings.IconsPath;
86             var fullPath = Path.Combine(iconsFolder, iconFile);
87
88             OverlayName = overlayName;
89             IconPath = fullPath;
90
91             
92         }
93
94
95         private static bool? _isExplorer = false;
96
97
98         private bool IsExplorer
99         {
100             get
101             {
102                 if (!_isExplorer.HasValue)
103                 {
104                     var moduleName = Process.GetCurrentProcess().MainModule.ModuleName;
105                     _isExplorer = (moduleName == "explorer.exe");
106                 }
107                 return _isExplorer.Value;
108             }
109         }
110
111         public int IsMemberOf(string path, uint attributes)
112         {
113             var showOnlyInExplorer=(int)Registry.LocalMachine.GetValue(@"SOFTWARE\GRNet\Pithos\ShowOnlyInExplorer", 0);
114             if (showOnlyInExplorer!=0 && !IsExplorer)
115                 return WinError.S_FALSE;
116
117
118             if (String.IsNullOrWhiteSpace(path))
119                 throw new ArgumentNullException("path","Empty path");
120
121             Debug.WriteLine(String.Format("ICON Status check for {0} - {1}", path, GetType().Name), LogCategories.ShellOverlays);
122             
123             if (!Settings.Accounts.Any(account=>account.RootPath!=null && path.StartsWith(account.RootPath,StringComparison.InvariantCultureIgnoreCase)))
124                 return WinError.S_FALSE;
125
126             var status=StatusChecker.GetFileOverlayStatus(path);
127             var isMember = (PithosPrefix + status == OverlayName);
128             Debug.WriteLine(String.Format("[STATUS] Was {0}, expected {1} for {2}", status, OverlayName,path ), LogCategories.ShellOverlays);
129             return isMember ? WinError.S_OK : WinError.S_FALSE;
130         }
131
132         public int GetOverlayInfo(
133             IntPtr iconFileBuffer,
134             int iconFileBufferSize,
135             out int iconIndex,
136             out uint flags)
137         {
138             Contract.Requires(iconFileBuffer!=IntPtr.Zero);
139             Contract.Requires(iconFileBufferSize>0);
140
141             if (iconFileBuffer == IntPtr.Zero)
142                 throw new ArgumentNullException("iconFileBuffer","iconFileBuffer not initialized");
143             if (iconFileBufferSize<=0)
144                 throw new ArgumentException("iconFileBufferSize", "iconFileBufferSize must be greatere than 0");
145             Debug.WriteLine("Looking for icons", LogCategories.ShellOverlays);
146             Debug.WriteLine(string.Format("ICON file {0}", IconPath), LogCategories.ShellOverlays);
147             
148             int bytesCount = System.Text.Encoding.Unicode.GetByteCount(IconPath);
149             Debug.WriteLine(string.Format(" GetOverlayInfo::{0}", bytesCount), LogCategories.ShellOverlays);
150
151             MarshalHelpers.CopyToBuffer(IconPath, iconFileBuffer, iconFileBufferSize);
152
153             flags = (uint)(ISIOI.ISIOI_ICONFILE);// | ISIOI.ISIOI_ICONINDEX);
154             iconIndex = 0;
155             return WinError.S_OK;
156         }
157
158         public int  GetPriority(out int priority)
159         {
160             Debug.WriteLine("Checking for priority");
161             priority = 0;
162             return WinError.S_OK;
163         }
164
165         
166         public static void RegisterOverlay(Type type,string iconName)
167         {
168             Contract.Requires(type != null);
169             Contract.Requires(!String.IsNullOrWhiteSpace(iconName));
170
171             if (type == null)
172                 throw new ArgumentNullException("type", "type can't be null");
173             if (String.IsNullOrWhiteSpace(iconName))
174                 throw new ArgumentNullException("iconName", "iconName can't be null");
175
176             try
177             {
178                 
179                 ShellExtReg.RegisterIconOverlayIdentifier(type.GUID, iconName);
180
181                 NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST,
182                                              IntPtr.Zero, IntPtr.Zero);
183                 Debug.WriteLine("Registered icon handler");
184             }
185             catch (Exception ex)
186             {
187                 Debug.WriteLine(ex.Message); // Log the error
188                 throw;  // Re-throw the exception
189             }
190         }
191
192         
193         public static void UnregisterOverlay(Type type,string iconName)
194         {
195             Contract.Requires(type!=null);
196             Contract.Requires(!String.IsNullOrWhiteSpace(iconName));
197
198             if (type==null)
199                 throw new ArgumentNullException("type","type can't be null");
200             if (String.IsNullOrWhiteSpace(iconName))
201                 throw new ArgumentNullException("iconName","iconName can't be null");
202             try
203             {                
204                 ShellExtReg.UnregisterIconOverlayIdentifier(type.GUID, iconName);
205                 Debug.WriteLine(String.Format("UnRegistered icon handler {0}:{1}",iconName,type.GUID), LogCategories.ShellOverlays);
206             }
207             catch (Exception ex)
208             {
209                 //Log and rethrow
210                 Log.ErrorFormat("Failed to unregister overlay {0}:{1} with error {2}",iconName,type.GUID,ex.Message); 
211                 throw;  
212             }
213         }
214     }
215
216 }