Merge pull request #375 from atomia/master
[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                 // Locked by caller
97                 public static bool GetInstance (out IFileWatcher watcher)
98                 {
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                 public void StartDispatching (FileSystemWatcher fsw)
124                 {
125                         KeventData data;
126                         lock (this) {
127                                 if (thread == null) {
128                                         thread = new Thread (new ThreadStart (Monitor));
129                                         thread.IsBackground = true;
130                                         thread.Start ();
131                                 }
132
133                                 data = (KeventData) watches [fsw];
134                         }
135
136                         if (data == null) {
137                                 data = new KeventData ();
138                                 data.FSW = fsw;
139                                 data.Directory = fsw.FullPath;
140                                 data.FileMask = fsw.MangledFilter;
141                                 data.IncludeSubdirs = fsw.IncludeSubdirectories;
142
143                                 data.Enabled = true;
144                                 lock (this) {
145                                         StartMonitoringDirectory (data);
146                                         watches [fsw] = data;
147                                         stop = false;
148                                 }
149                         }
150                 }
151
152                 static void StartMonitoringDirectory (KeventData data)
153                 {
154                         DirectoryInfo dir = new DirectoryInfo (data.Directory);
155                         if(data.DirEntries == null) {
156                                 data.DirEntries = new Hashtable();
157                                 foreach (FileSystemInfo fsi in dir.GetFileSystemInfos() ) 
158                                         data.DirEntries.Add(fsi.FullName, new KeventFileData(fsi, fsi.LastAccessTime, fsi.LastWriteTime));
159                         }
160
161                         int fd = open(data.Directory, 0, 0);
162                         kevent ev = new kevent();
163                         ev.udata = IntPtr.Zero;
164                         timespec nullts = new timespec();
165                         nullts.tv_sec = 0;
166                         nullts.tv_usec = 0;
167                         if (fd > 0) {
168                                 ev.ident = fd;
169                                 ev.filter = -4;
170                                 ev.flags = 1 | 4 | 20;
171                                 ev.fflags = 20 | 2 | 1 | 8;
172                                 ev.data = 0;
173                                 ev.udata = Marshal.StringToHGlobalAuto (data.Directory);
174                                 kevent outev = new kevent();
175                                 outev.udata = IntPtr.Zero;
176                                 kevent (conn, ref ev, 1, ref outev, 0, ref nullts);
177                                 data.ev = ev;
178                                 requests [fd] = data;
179                         }
180                         
181                         if (!data.IncludeSubdirs)
182                                 return;
183
184                 }
185
186                 public void StopDispatching (FileSystemWatcher fsw)
187                 {
188                         KeventData data;
189                         lock (this) {
190                                 data = (KeventData) watches [fsw];
191                                 if (data == null)
192                                         return;
193
194                                 StopMonitoringDirectory (data);
195                                 watches.Remove (fsw);
196                                 if (watches.Count == 0)
197                                         stop = true;
198
199                                 if (!data.IncludeSubdirs)
200                                         return;
201
202                         }
203                 }
204
205                 static void StopMonitoringDirectory (KeventData data)
206                 {
207                         close(data.ev.ident);
208                 }
209
210                 void Monitor ()
211                 {
212                 
213                         while (!stop) {
214                                 kevent ev = new kevent();
215                                 ev.udata = IntPtr.Zero;
216                                 kevent nullev = new kevent();
217                                 nullev.udata = IntPtr.Zero;
218                                 timespec ts = new timespec();
219                                 ts.tv_sec = 0;
220                                 ts.tv_usec = 0;
221                                 int haveEvents;
222                                 lock (this) {
223                                         haveEvents = kevent (conn, ref nullev, 0, ref ev, 1, ref ts);
224                                 }
225
226                                 if (haveEvents > 0) {
227                                         // Restart monitoring
228                                         KeventData data = (KeventData) requests [ev.ident];
229                                         StopMonitoringDirectory (data);
230                                         StartMonitoringDirectory (data);
231                                         ProcessEvent (ev);
232                                 } else {
233                                         System.Threading.Thread.Sleep (500);
234                                 }
235                         }
236
237                         lock (this) {
238                                 thread = null;
239                                 stop = false;
240                         }
241                 }
242
243                 void ProcessEvent (kevent ev)
244                 {
245                         lock (this) {
246                                 KeventData data = (KeventData) requests [ev.ident];
247                                 if (!data.Enabled)
248                                         return;
249
250                                 FileSystemWatcher fsw;
251                                 string filename = "";
252
253                                 fsw = data.FSW;
254                                 FileAction fa = 0;
255                                 DirectoryInfo dir = new DirectoryInfo (data.Directory);
256                                 FileSystemInfo changedFsi = null;
257
258                                 try {
259                                         foreach (FileSystemInfo fsi in dir.GetFileSystemInfos() )
260                                                 if (data.DirEntries.ContainsKey (fsi.FullName) && (fsi is FileInfo)) {
261                                                         KeventFileData entry = (KeventFileData) data.DirEntries [fsi.FullName];
262                                                         if (entry.LastWriteTime != fsi.LastWriteTime) {
263                                                                 filename = fsi.Name;
264                                                                 fa = FileAction.Modified;
265                                                                 data.DirEntries [fsi.FullName] = new KeventFileData(fsi, fsi.LastAccessTime, fsi.LastWriteTime);
266                                                                 if (fsw.IncludeSubdirectories && fsi is DirectoryInfo) {
267                                                                         data.Directory = filename;
268                                                                         requests [ev.ident] = data;
269                                                                         ProcessEvent(ev);
270                                                                 }
271                                                                 PostEvent(filename, fsw, fa, changedFsi);
272                                                         }
273                                                 }
274                                 } catch (Exception) {
275                                         // The file system infos were changed while we processed them
276                                 }
277                                 // Deleted
278                                 try {
279                                         bool deleteMatched = true;
280                                         while(deleteMatched) {
281                                                 foreach (KeventFileData entry in data.DirEntries.Values) { 
282                                                         if (!File.Exists (entry.fsi.FullName) && !Directory.Exists (entry.fsi.FullName)) {
283                                                                 filename = entry.fsi.Name;
284                                                                 fa = FileAction.Removed;
285                                                                 data.DirEntries.Remove (entry.fsi.FullName);
286                                                                 PostEvent(filename, fsw, fa, changedFsi);
287                                                                 break;
288                                                         }
289                                                 }
290                                                 deleteMatched = false;
291                                         }
292                                 } catch (Exception) {
293                                         // The file system infos were changed while we processed them
294                                 }
295                                 // Added
296                                 try {
297                                         foreach (FileSystemInfo fsi in dir.GetFileSystemInfos()) 
298                                                 if (!data.DirEntries.ContainsKey (fsi.FullName)) {
299                                                         changedFsi = fsi;
300                                                         filename = fsi.Name;
301                                                         fa = FileAction.Added;
302                                                         data.DirEntries [fsi.FullName] = new KeventFileData(fsi, fsi.LastAccessTime, fsi.LastWriteTime);
303                                                         PostEvent(filename, fsw, fa, changedFsi);
304                                                 }
305                                 } catch (Exception) {
306                                         // The file system infos were changed while we processed them
307                                 }
308                                 
309
310                         }
311                 }
312
313                 private void PostEvent (string filename, FileSystemWatcher fsw, FileAction fa, FileSystemInfo changedFsi) {
314                         RenamedEventArgs renamed = null;
315                         if (fa == 0)
316                                 return;
317                         
318                         if (fsw.IncludeSubdirectories && fa == FileAction.Added) {
319                                 if (changedFsi is DirectoryInfo) {
320                                         KeventData newdirdata = new KeventData ();
321                                         newdirdata.FSW = fsw;
322                                         newdirdata.Directory = changedFsi.FullName;
323                                         newdirdata.FileMask = fsw.MangledFilter;
324                                         newdirdata.IncludeSubdirs = fsw.IncludeSubdirectories;
325         
326                                         newdirdata.Enabled = true;
327                                         lock (this) {
328                                                 StartMonitoringDirectory (newdirdata);
329                                         }
330                                 }
331                         }
332                 
333                         if (!fsw.Pattern.IsMatch(filename, true))
334                                 return;
335
336                         lock (fsw) {
337                                 fsw.DispatchEvents (fa, filename, ref renamed);
338                                 if (fsw.Waiting) {
339                                         fsw.Waiting = false;
340                                         System.Threading.Monitor.PulseAll (fsw);
341                                 }
342                         }
343                 }
344
345                 [DllImport ("libc")]
346                 extern static int open(string path, int flags, int mode_t);
347                 
348                 [DllImport ("libc")]
349                 extern static int close(int fd);
350
351                 [DllImport ("libc")]
352                 extern static int kqueue();
353
354                 [DllImport ("libc")]
355                 extern static int kevent(int kqueue, ref kevent ev, int nchanges, ref kevent evtlist,  int nevents, ref timespec ts);
356         }
357 }
358