Merge pull request #901 from Blewzman/FixAggregateExceptionGetBaseException
[mono.git] / mcs / class / System / System.IO / FileSystemWatcher.cs
1 // 
2 // System.IO.FileSystemWatcher.cs
3 //
4 // Authors:
5 //      Tim Coleman (tim@timcoleman.com)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // Copyright (C) Tim Coleman, 2002 
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 // Copyright (C) 2004, 2006 Novell, Inc (http://www.novell.com)
11 //
12
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System.ComponentModel;
35 using System.Diagnostics;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
38 using System.Security.Permissions;
39 using System.Threading;
40
41 namespace System.IO {
42         [DefaultEvent("Changed")]
43         [IODescription ("")]
44         public class FileSystemWatcher : Component, ISupportInitialize {
45
46                 #region Fields
47
48                 bool enableRaisingEvents;
49                 string filter;
50                 bool includeSubdirectories;
51                 int internalBufferSize;
52                 NotifyFilters notifyFilter;
53                 string path;
54                 string fullpath;
55                 ISynchronizeInvoke synchronizingObject;
56                 WaitForChangedResult lastData;
57                 bool waiting;
58                 SearchPattern2 pattern;
59                 bool disposed;
60                 string mangledFilter;
61                 static IFileWatcher watcher;
62                 static object lockobj = new object ();
63
64                 #endregion // Fields
65
66                 #region Constructors
67
68                 public FileSystemWatcher ()
69                 {
70                         this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
71                         this.enableRaisingEvents = false;
72                         this.filter = "*.*";
73                         this.includeSubdirectories = false;
74                         this.internalBufferSize = 8192;
75                         this.path = "";
76                         InitWatcher ();
77                 }
78
79                 public FileSystemWatcher (string path)
80                         : this (path, "*.*")
81                 {
82                 }
83
84                 public FileSystemWatcher (string path, string filter)
85                 {
86                         if (path == null)
87                                 throw new ArgumentNullException ("path");
88
89                         if (filter == null)
90                                 throw new ArgumentNullException ("filter");
91
92                         if (path == String.Empty)
93                                 throw new ArgumentException ("Empty path", "path");
94
95                         if (!Directory.Exists (path))
96                                 throw new ArgumentException ("Directory does not exist", "path");
97
98                         this.enableRaisingEvents = false;
99                         this.filter = filter;
100                         this.includeSubdirectories = false;
101                         this.internalBufferSize = 8192;
102                         this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
103                         this.path = path;
104                         this.synchronizingObject = null;
105                         InitWatcher ();
106                 }
107
108                 [EnvironmentPermission (SecurityAction.Assert, Read="MONO_MANAGED_WATCHER")]
109                 void InitWatcher ()
110                 {
111                         lock (lockobj) {
112                                 if (watcher != null)
113                                         return;
114
115                                 string managed = Environment.GetEnvironmentVariable ("MONO_MANAGED_WATCHER");
116                                 int mode = 0;
117                                 if (managed == null)
118                                         mode = InternalSupportsFSW ();
119                                 
120                                 bool ok = false;
121                                 switch (mode) {
122                                 case 1: // windows
123                                         ok = DefaultWatcher.GetInstance (out watcher);
124                                         //ok = WindowsWatcher.GetInstance (out watcher);
125                                         break;
126                                 case 2: // libfam
127                                         ok = FAMWatcher.GetInstance (out watcher, false);
128                                         break;
129                                 case 3: // kevent
130                                         ok = KeventWatcher.GetInstance (out watcher);
131                                         break;
132                                 case 4: // libgamin
133                                         ok = FAMWatcher.GetInstance (out watcher, true);
134                                         break;
135                                 case 5: // inotify
136                                         ok = InotifyWatcher.GetInstance (out watcher, true);
137                                         break;
138                                 }
139
140                                 if (mode == 0 || !ok) {
141                                         if (String.Compare (managed, "disabled", true) == 0)
142                                                 NullFileWatcher.GetInstance (out watcher);
143                                         else
144                                                 DefaultWatcher.GetInstance (out watcher);
145                                 }
146
147                                 ShowWatcherInfo ();
148                         }
149                 }
150
151                 [Conditional ("DEBUG"), Conditional ("TRACE")]
152                 void ShowWatcherInfo ()
153                 {
154                         Console.WriteLine ("Watcher implementation: {0}", watcher != null ? watcher.GetType ().ToString () : "<none>");
155                 }
156                 
157                 #endregion // Constructors
158
159                 #region Properties
160
161                 /* If this is enabled, we Pulse this instance */
162                 internal bool Waiting {
163                         get { return waiting; }
164                         set { waiting = value; }
165                 }
166
167                 internal string MangledFilter {
168                         get {
169                                 if (filter != "*.*")
170                                         return filter;
171
172                                 if (mangledFilter != null)
173                                         return mangledFilter;
174
175                                 string filterLocal = "*.*";
176                                 if (!(watcher.GetType () == typeof (WindowsWatcher)))
177                                         filterLocal = "*";
178
179                                 return filterLocal;
180                         }
181                 }
182
183                 internal SearchPattern2 Pattern {
184                         get {
185                                 if (pattern == null) {
186                                         pattern = new SearchPattern2 (MangledFilter);
187                                 }
188                                 return pattern;
189                         }
190                 }
191
192                 internal string FullPath {
193                         get {
194                                 if (fullpath == null) {
195                                         if (path == null || path == "")
196                                                 fullpath = Environment.CurrentDirectory;
197                                         else
198                                                 fullpath = System.IO.Path.GetFullPath (path);
199                                 }
200
201                                 return fullpath;
202                         }
203                 }
204
205                 [DefaultValue(false)]
206                 [IODescription("Flag to indicate if this instance is active")]
207                 public bool EnableRaisingEvents {
208                         get { return enableRaisingEvents; }
209                         set {
210                                 if (value == enableRaisingEvents)
211                                         return; // Do nothing
212
213                                 enableRaisingEvents = value;
214                                 if (value) {
215                                         Start ();
216                                 } else {
217                                         Stop ();
218                                 }
219                         }
220                 }
221
222                 [DefaultValue("*.*")]
223                 [IODescription("File name filter pattern")]
224                 [RecommendedAsConfigurable(true)]
225                 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
226                 public string Filter {
227                         get { return filter; }
228                         set {
229                                 if (value == null || value == "")
230                                         value = "*.*";
231
232                                 if (filter != value) {
233                                         filter = value;
234                                         pattern = null;
235                                         mangledFilter = null;
236                                 }
237                         }
238                 }
239
240                 [DefaultValue(false)]
241                 [IODescription("Flag to indicate we want to watch subdirectories")]
242                 public bool IncludeSubdirectories {
243                         get { return includeSubdirectories; }
244                         set {
245                                 if (includeSubdirectories == value)
246                                         return;
247
248                                 includeSubdirectories = value;
249                                 if (value && enableRaisingEvents) {
250                                         Stop ();
251                                         Start ();
252                                 }
253                         }
254                 }
255
256                 [Browsable(false)]
257                 [DefaultValue(8192)]
258                 public int InternalBufferSize {
259                         get { return internalBufferSize; }
260                         set {
261                                 if (internalBufferSize == value)
262                                         return;
263
264                                 if (value < 4196)
265                                         value = 4196;
266
267                                 internalBufferSize = value;
268                                 if (enableRaisingEvents) {
269                                         Stop ();
270                                         Start ();
271                                 }
272                         }
273                 }
274
275                 [DefaultValue(NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite)]
276                 [IODescription("Flag to indicate which change event we want to monitor")]
277                 public NotifyFilters NotifyFilter {
278                         get { return notifyFilter; }
279                         set {
280                                 if (notifyFilter == value)
281                                         return;
282                                         
283                                 notifyFilter = value;
284                                 if (enableRaisingEvents) {
285                                         Stop ();
286                                         Start ();
287                                 }
288                         }
289                 }
290
291                 [DefaultValue("")]
292                 [IODescription("The directory to monitor")]
293                 [RecommendedAsConfigurable(true)]
294                 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
295                 [Editor ("System.Diagnostics.Design.FSWPathEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
296                 public string Path {
297                         get { return path; }
298                         set {
299                                 if (path == value)
300                                         return;
301
302                                 bool exists = false;
303                                 Exception exc = null;
304
305                                 try {
306                                         exists = Directory.Exists (value);
307                                 } catch (Exception e) {
308                                         exc = e;
309                                 }
310
311                                 if (exc != null)
312                                         throw new ArgumentException ("Invalid directory name", "value", exc);
313
314                                 if (!exists)
315                                         throw new ArgumentException ("Directory does not exist", "value");
316
317                                 path = value;
318                                 fullpath = null;
319                                 if (enableRaisingEvents) {
320                                         Stop ();
321                                         Start ();
322                                 }
323                         }
324                 }
325
326                 [Browsable(false)]
327                 public override ISite Site {
328                         get { return base.Site; }
329                         set { base.Site = value; }
330                 }
331
332                 [DefaultValue(null)]
333                 [IODescription("The object used to marshal the event handler calls resulting from a directory change")]
334                 [Browsable (false)]
335                 public ISynchronizeInvoke SynchronizingObject {
336                         get { return synchronizingObject; }
337                         set { synchronizingObject = value; }
338                 }
339
340                 #endregion // Properties
341
342                 #region Methods
343         
344                 public void BeginInit ()
345                 {
346                         // Not necessary in Mono
347                 }
348
349                 protected override void Dispose (bool disposing)
350                 {
351                         if (!disposed) {
352                                 disposed = true;
353                                 Stop ();
354                         }
355
356                         base.Dispose (disposing);
357                 }
358
359                 ~FileSystemWatcher ()
360                 {
361                         disposed = true;
362                         Stop ();
363                 }
364                 
365                 public void EndInit ()
366                 {
367                         // Not necessary in Mono
368                 }
369
370                 enum EventType {
371                         FileSystemEvent,
372                         ErrorEvent,
373                         RenameEvent
374                 }
375                 private void RaiseEvent (Delegate ev, EventArgs arg, EventType evtype)
376                 {
377                         if (ev == null)
378                                 return;
379
380                         if (synchronizingObject == null) {
381                                 switch (evtype) {
382                                 case EventType.RenameEvent:
383                                         ((RenamedEventHandler)ev).BeginInvoke (this, (RenamedEventArgs) arg, null, null);
384                                         break;
385                                 case EventType.ErrorEvent:
386                                         ((ErrorEventHandler)ev).BeginInvoke (this, (ErrorEventArgs) arg, null, null);
387                                         break;
388                                 case EventType.FileSystemEvent:
389                                         ((FileSystemEventHandler)ev).BeginInvoke (this, (FileSystemEventArgs) arg, null, null);
390                                         break;
391                                 }
392                                 return;
393                         }
394                         
395                         synchronizingObject.BeginInvoke (ev, new object [] {this, arg});
396                 }
397
398                 protected void OnChanged (FileSystemEventArgs e)
399                 {
400                         RaiseEvent (Changed, e, EventType.FileSystemEvent);
401                 }
402
403                 protected void OnCreated (FileSystemEventArgs e)
404                 {
405                         RaiseEvent (Created, e, EventType.FileSystemEvent);
406                 }
407
408                 protected void OnDeleted (FileSystemEventArgs e)
409                 {
410                         RaiseEvent (Deleted, e, EventType.FileSystemEvent);
411                 }
412
413                 protected void OnError (ErrorEventArgs e)
414                 {
415                         RaiseEvent (Error, e, EventType.ErrorEvent);
416                 }
417
418                 protected void OnRenamed (RenamedEventArgs e)
419                 {
420                         RaiseEvent (Renamed, e, EventType.RenameEvent);
421                 }
422
423                 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType)
424                 {
425                         return WaitForChanged (changeType, Timeout.Infinite);
426                 }
427
428                 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType, int timeout)
429                 {
430                         WaitForChangedResult result = new WaitForChangedResult ();
431                         bool prevEnabled = EnableRaisingEvents;
432                         if (!prevEnabled)
433                                 EnableRaisingEvents = true;
434
435                         bool gotData;
436                         lock (this) {
437                                 waiting = true;
438                                 gotData = Monitor.Wait (this, timeout);
439                                 if (gotData)
440                                         result = this.lastData;
441                         }
442
443                         EnableRaisingEvents = prevEnabled;
444                         if (!gotData)
445                                 result.TimedOut = true;
446
447                         return result;
448                 }
449
450                 internal void DispatchEvents (FileAction act, string filename, ref RenamedEventArgs renamed)
451                 {
452                         if (waiting) {
453                                 lastData = new WaitForChangedResult ();
454                         }
455
456                         switch (act) {
457                         case FileAction.Added:
458                                 lastData.Name = filename;
459                                 lastData.ChangeType = WatcherChangeTypes.Created;
460                                 OnCreated (new FileSystemEventArgs (WatcherChangeTypes.Created, path, filename));
461                                 break;
462                         case FileAction.Removed:
463                                 lastData.Name = filename;
464                                 lastData.ChangeType = WatcherChangeTypes.Deleted;
465                                 OnDeleted (new FileSystemEventArgs (WatcherChangeTypes.Deleted, path, filename));
466                                 break;
467                         case FileAction.Modified:
468                                 lastData.Name = filename;
469                                 lastData.ChangeType = WatcherChangeTypes.Changed;
470                                 OnChanged (new FileSystemEventArgs (WatcherChangeTypes.Changed, path, filename));
471                                 break;
472                         case FileAction.RenamedOldName:
473                                 if (renamed != null) {
474                                         OnRenamed (renamed);
475                                 }
476                                 lastData.OldName = filename;
477                                 lastData.ChangeType = WatcherChangeTypes.Renamed;
478                                 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, filename, "");
479                                 break;
480                         case FileAction.RenamedNewName:
481                                 lastData.Name = filename;
482                                 lastData.ChangeType = WatcherChangeTypes.Renamed;
483                                 if (renamed == null) {
484                                         renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, "", filename);
485                                 }
486                                 OnRenamed (renamed);
487                                 renamed = null;
488                                 break;
489                         default:
490                                 break;
491                         }
492                 }
493
494                 void Start ()
495                 {
496                         watcher.StartDispatching (this);
497                 }
498
499                 void Stop ()
500                 {
501                         watcher.StopDispatching (this);
502                 }
503                 #endregion // Methods
504
505                 #region Events and Delegates
506
507                 [IODescription("Occurs when a file/directory change matches the filter")]
508                 public event FileSystemEventHandler Changed;
509
510                 [IODescription("Occurs when a file/directory creation matches the filter")]
511                 public event FileSystemEventHandler Created;
512
513                 [IODescription("Occurs when a file/directory deletion matches the filter")]
514                 public event FileSystemEventHandler Deleted;
515
516                 [Browsable(false)]
517                 public event ErrorEventHandler Error;
518
519                 [IODescription("Occurs when a file/directory rename matches the filter")]
520                 public event RenamedEventHandler Renamed;
521
522                 #endregion // Events and Delegates
523
524                 /* 0 -> not supported   */
525                 /* 1 -> windows         */
526                 /* 2 -> FAM             */
527                 /* 3 -> Kevent          */
528                 /* 4 -> gamin           */
529                 /* 5 -> inotify         */
530                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
531                 static extern int InternalSupportsFSW ();
532         }
533 }
534