803629effcdc3f7e2f31c405466e92e896687d7c
[mono.git] / mcs / class / System / System.IO / KeventWatcher.cs
1 // 
2 // System.IO.KeventWatcher.cs: interface with osx kevent
3 //
4 // Authors:
5 //      Geoff Norton (gnorton@customerdna.com)
6 //
7 // (c) 2004 Geoff Norton
8
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.Collections;
32 using System.ComponentModel;
33 using System.Runtime.CompilerServices;
34 using System.Runtime.InteropServices;
35 using System.Text;
36 using System.Threading;
37
38 namespace System.IO {
39
40         struct kevent : IDisposable {
41                 public int ident;
42                 public short filter;
43                 public ushort flags;
44                 public uint fflags;
45                 public int data;
46                 public IntPtr udata;
47
48                 public void Dispose ()
49                 {
50                         if (udata != IntPtr.Zero)
51                                 Marshal.FreeHGlobal (udata);
52                 }
53         }
54
55         struct timespec {
56                 public int tv_sec;
57                 public int tv_usec;
58         }
59
60         class KeventFileData {
61                 public FileSystemInfo fsi;
62                 public DateTime LastAccessTime;
63                 public DateTime LastWriteTime;
64
65                 public KeventFileData(FileSystemInfo fsi, DateTime LastAccessTime, DateTime LastWriteTime) {
66                         this.fsi = fsi;
67                         this.LastAccessTime = LastAccessTime;
68                         this.LastWriteTime = LastWriteTime;
69                 }
70         }
71
72         class KeventData {
73                 public FileSystemWatcher FSW;
74                 public string Directory;
75                 public string FileMask;
76                 public bool IncludeSubdirs;
77                 public bool Enabled;
78                 public Hashtable DirEntries;
79                 public kevent ev;
80         }
81
82         class KeventWatcher : IFileWatcher
83         {
84                 static bool failed;
85                 static KeventWatcher instance;
86                 static Hashtable watches;
87                 static Hashtable requests;
88                 static Thread thread;
89                 static int conn;
90                 static bool stop;
91                 
92                 private KeventWatcher ()
93                 {
94                 }
95                 
96                 public static bool GetInstance (out IFileWatcher watcher)
97                 {
98                         lock (typeof (KeventWatcher)) {
99                                 if (failed == true) {
100                                         watcher = null;
101                                         return false;
102                                 }
103
104                                 if (instance != null) {
105                                         watcher = instance;
106                                         return true;
107                                 }
108
109                                 watches = Hashtable.Synchronized (new Hashtable ());
110                                 requests = Hashtable.Synchronized (new Hashtable ());
111                                 conn = kqueue();
112                                 if (conn == -1) {
113                                         failed = true;
114                                         watcher = null;
115                                         return false;
116                                 }
117
118                                 instance = new KeventWatcher ();
119                                 watcher = instance;
120                                 return true;
121                         }
122                 }
123                 
124                 public void StartDispatching (FileSystemWatcher fsw)
125                 {
126                         KeventData data;
127                         lock (this) {
128                                 if (thread == null) {
129                                         thread = new Thread (new ThreadStart (Monitor));
130                                         thread.IsBackground = true;
131                                         thread.Start ();
132                                 }
133
134                                 data = (KeventData) watches [fsw];
135                         }
136
137                         if (data == null) {
138                                 data = new KeventData ();
139                                 data.FSW = fsw;
140                                 data.Directory = fsw.FullPath;
141                                 data.FileMask = fsw.MangledFilter;
142                                 data.IncludeSubdirs = fsw.IncludeSubdirectories;
143
144                                 data.Enabled = true;
145                                 lock (this) {
146                                         StartMonitoringDirectory (data);
147                                         watches [fsw] = data;
148                                         stop = false;
149                                 }
150                         }
151                 }
152
153                 static void StartMonitoringDirectory (KeventData data)
154                 {
155                         DirectoryInfo dir = new DirectoryInfo (data.Directory);
156                         if(data.DirEntries == null) {
157                                 data.DirEntries = new Hashtable();
158                                 foreach (FileSystemInfo fsi in dir.GetFileSystemInfos() ) 
159                                         data.DirEntries.Add(fsi.FullName, new KeventFileData(fsi, fsi.LastAccessTime, fsi.LastWriteTime));
160                         }
161
162                         int fd = open(data.Directory, 0, 0);
163                         kevent ev = new kevent();
164                         ev.udata = IntPtr.Zero;
165                         timespec nullts = new timespec();
166                         nullts.tv_sec = 0;
167                         nullts.tv_usec = 0;
168                         if (fd > 0) {
169                                 ev.ident = fd;
170                                 ev.filter = -4;
171                                 ev.flags = 1 | 4 | 20;
172                                 ev.fflags = 20 | 2 | 1 | 8;
173                                 ev.data = 0;
174                                 ev.udata = Marshal.StringToHGlobalAuto (data.Directory);
175                                 kevent outev = new kevent();
176                                 outev.udata = IntPtr.Zero;
177                                 kevent (conn, ref ev, 1, ref outev, 0, ref nullts);
178                                 data.ev = ev;
179                                 requests [fd] = data;
180                         }
181                         
182                         if (!data.IncludeSubdirs)
183                                 return;
184
185                 }
186
187                 public void StopDispatching (FileSystemWatcher fsw)
188                 {
189                         KeventData data;
190                         lock (this) {
191                                 data = (KeventData) watches [fsw];
192                                 if (data == null)
193                                         return;
194
195                                 StopMonitoringDirectory (data);
196                                 watches.Remove (fsw);
197                                 if (watches.Count == 0)
198                                         stop = true;
199
200                                 if (!data.IncludeSubdirs)
201                                         return;
202
203                         }
204                 }
205
206                 static void StopMonitoringDirectory (KeventData data)
207                 {
208                         close(data.ev.ident);
209                 }
210
211                 void Monitor ()
212                 {
213                 
214                         while (!stop) {
215                                 kevent ev = new kevent();
216                                 ev.udata = IntPtr.Zero;
217                                 kevent nullev = new kevent();
218                                 nullev.udata = IntPtr.Zero;
219                                 timespec ts = new timespec();
220                                 ts.tv_sec = 0;
221                                 ts.tv_usec = 0;
222                                 int haveEvents;
223                                 lock (this) {
224                                         haveEvents = kevent (conn, ref nullev, 0, ref ev, 1, ref ts);
225                                 }
226
227                                 if (haveEvents > 0) {
228                                         // Restart monitoring
229                                         KeventData data = (KeventData) requests [ev.ident];
230                                         StopMonitoringDirectory (data);
231                                         StartMonitoringDirectory (data);
232                                         ProcessEvent (ev);
233                                 } else {
234                                         System.Threading.Thread.Sleep (500);
235                                 }
236                         }
237
238                         lock (this) {
239                                 thread = null;
240                                 stop = false;
241                         }
242                 }
243
244                 void ProcessEvent (kevent ev)
245                 {
246                         lock (this) {
247                                 KeventData data = (KeventData) requests [ev.ident];
248                                 if (!data.Enabled)
249                                         return;
250
251                                 FileSystemWatcher fsw;
252                                 string filename = "";
253
254                                 fsw = data.FSW;
255                                 FileAction fa = 0;
256                                 DirectoryInfo dir = new DirectoryInfo (data.Directory);
257                                 FileSystemInfo changedFsi = null;
258
259                                 try {
260                                         foreach (FileSystemInfo fsi in dir.GetFileSystemInfos() )
261                                                 if (data.DirEntries.ContainsKey (fsi.FullName) && (fsi is FileInfo)) {
262                                                         KeventFileData entry = (KeventFileData) data.DirEntries [fsi.FullName];
263                                                         if (entry.LastWriteTime != fsi.LastWriteTime) {
264                                                                 filename = fsi.Name;
265                                                                 fa = FileAction.Modified;
266                                                                 data.DirEntries [fsi.FullName] = new KeventFileData(fsi, fsi.LastAccessTime, fsi.LastWriteTime);
267                                                                 if (fsw.IncludeSubdirectories && fsi is DirectoryInfo) {
268                                                                         data.Directory = filename;
269                                                                         requests [ev.ident] = data;
270                                                                         ProcessEvent(ev);
271                                                                 }
272                                                                 PostEvent(filename, fsw, fa, changedFsi);
273                                                         }
274                                                 }
275                                 } catch (Exception) {
276                                         // The file system infos were changed while we processed them
277                                 }
278                                 // Deleted
279                                 try {
280                                         bool deleteMatched = true;
281                                         while(deleteMatched) {
282                                                 foreach (KeventFileData entry in data.DirEntries.Values) { 
283                                                         if (!File.Exists (entry.fsi.FullName) && !Directory.Exists (entry.fsi.FullName)) {
284                                                                 filename = entry.fsi.Name;
285                                                                 fa = FileAction.Removed;
286                                                                 data.DirEntries.Remove (entry.fsi.FullName);
287                                                                 PostEvent(filename, fsw, fa, changedFsi);
288                                                                 break;
289                                                         }
290                                                 }
291                                                 deleteMatched = false;
292                                         }
293                                 } catch (Exception) {
294                                         // The file system infos were changed while we processed them
295                                 }
296                                 // Added
297                                 try {
298                                         foreach (FileSystemInfo fsi in dir.GetFileSystemInfos()) 
299                                                 if (!data.DirEntries.ContainsKey (fsi.FullName)) {
300                                                         changedFsi = fsi;
301                                                         filename = fsi.Name;
302                                                         fa = FileAction.Added;
303                                                         data.DirEntries [fsi.FullName] = new KeventFileData(fsi, fsi.LastAccessTime, fsi.LastWriteTime);
304                                                         PostEvent(filename, fsw, fa, changedFsi);
305                                                 }
306                                 } catch (Exception) {
307                                         // The file system infos were changed while we processed them
308                                 }
309                                 
310
311                         }
312                 }
313
314                 private void PostEvent (string filename, FileSystemWatcher fsw, FileAction fa, FileSystemInfo changedFsi) {
315                         RenamedEventArgs renamed = null;
316                         if (fa == 0)
317                                 return;
318                         
319                         if (fsw.IncludeSubdirectories && fa == FileAction.Added) {
320                                 if (changedFsi is DirectoryInfo) {
321                                         KeventData newdirdata = new KeventData ();
322                                         newdirdata.FSW = fsw;
323                                         newdirdata.Directory = changedFsi.FullName;
324                                         newdirdata.FileMask = fsw.MangledFilter;
325                                         newdirdata.IncludeSubdirs = fsw.IncludeSubdirectories;
326         
327                                         newdirdata.Enabled = true;
328                                         lock (this) {
329                                                 StartMonitoringDirectory (newdirdata);
330                                         }
331                                 }
332                         }
333                 
334                         if (!fsw.Pattern.IsMatch(filename, true))
335                                 return;
336
337                         lock (fsw) {
338                                 fsw.DispatchEvents (fa, filename, ref renamed);
339                                 if (fsw.Waiting) {
340                                         fsw.Waiting = false;
341                                         System.Threading.Monitor.PulseAll (fsw);
342                                 }
343                         }
344                 }
345
346                 [DllImport ("libc")]
347                 extern static int open(string path, int flags, int mode_t);
348                 
349                 [DllImport ("libc")]
350                 extern static int close(int fd);
351
352                 [DllImport ("libc")]
353                 extern static int kqueue();
354
355                 [DllImport ("libc")]
356                 extern static int kevent(int kqueue, ref kevent ev, int nchanges, ref kevent evtlist,  int nevents, ref timespec ts);
357         }
358 }
359