-
Notifications
You must be signed in to change notification settings - Fork 0
/
DirectoryWatcher.cs
366 lines (309 loc) · 12.7 KB
/
DirectoryWatcher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using MonoMac;
using MonoMac.Foundation;
using OSXUtils;
namespace VimFastFind {
// uses VolumeWatcher so on mac your application's main thread must be in a
// CoreFoundation run loop.
//
public class DirectoryWatcher : IDisposable
{
public delegate void AvailabilityChangedDelegate(DirectoryWatcher sender, string path, bool exists);
public delegate void ContentsChangedDelegate(DirectoryWatcher sender, string fullpath);
string _path;
string _fullpath;
bool _watchcontents;
// NOTE: we use FileSystemWatcher and VolumeWatcher on mac and windows. on windows and linux
// we periodically poll to ensure the directory still exists. we don't need to poll on mac
// because FsEventsWatcher notifies of root changes.
FsEventsWatcher _fswatcher;
VolumeWatcher _volwatcher;
// fires when directory disappears (volume unmounted, dir renamed, dir
// deleted) and when directory reappears (volume mounted, dir
// created/restored).
public event AvailabilityChangedDelegate AvailabilityChanged;
// on mac we don't have information about specific file changes.
// instead of firing added/removed we fire this event indicating that
// something happened inside the subdirectory provided.
public event ContentsChangedDelegate SubdirectoryChanged;
public DirectoryWatcher(string path)
{
Path = path;
}
public void Initialize()
{
_volwatcher = new VolumeWatcher();
_volwatcher.VolumeChanged += ev_VolumeChanged;
ThreadPool.QueueUserWorkItem(delegate { _CheckAvailable(false); });
}
public string Path
{
get
{
return _path;
}
private set
{
_path = value;
_fullpath = System.IO.Path.GetFullPath(_path);
}
}
public bool Exists
{
get; private set;
}
public bool EnableWatchingContents
{
get { return _watchcontents; }
set { _watchcontents = value; }
}
public void Dispose()
{
if (_fswatcher != null)
_fswatcher.Dispose();
#if SYSTEM_WINDOWS || SYSTEM_LINUX
if (_availabletimer != null)
_availabletimer.Dispose();
#endif
#if SYSTEM_WINDOWS || SYSTEM_MACOSX
if (_volwatcher != null)
_volwatcher.Dispose();
#endif
}
void StartWatcher()
{
Trace("Starting FileSystemWatcher");
if (_fswatcher != null) _fswatcher.Dispose();
#if SYSTEM_MACOSX
_fswatcher = new FsEventsWatcher(_fullpath);
_fswatcher.RootChanged += ev_RootChanged;
_fswatcher.SubdirectoryChanged += ev_SubdirectoryChanged;
#else
_fswatcher = new FileSystemWatcher();
_fswatcher.Path = _fullpath;
_fswatcher.IncludeSubdirectories = true;
_fswatcher.NotifyFilter = NotifyFilters.FileName
| NotifyFilters.DirectoryName
| NotifyFilters.Attributes
| NotifyFilters.Size
| NotifyFilters.LastWrite
| NotifyFilters.CreationTime
| NotifyFilters.Security;
_fswatcher.Changed += new FileSystemEventHandler(ev_FileChanged);
_fswatcher.Created += new FileSystemEventHandler(ev_FileChanged);
_fswatcher.Deleted += new FileSystemEventHandler(ev_FileChanged);
_fswatcher.Renamed += new RenamedEventHandler(ev_FileRenamed);
try {
// this can throw if, e.g. dir went away between when we
// checked for existence and now. don't bring down process.
_fswatcher.EnableRaisingEvents = true;
} catch {
Trace("Failed to start FileSystemWatcher: directory is inaccessible");
Exists = false;
}
#endif
}
void StopWatcher()
{
Trace("Stopping FileSystemWatcher");
if (_fswatcher != null) _fswatcher.Dispose();
_fswatcher = null;
}
#if SYSTEM_MACOSX || SYSTEM_WINDOWS
void ev_VolumeChanged(VolumeWatcher sender, VolumeWatcherEvent evt, string volume)
{
if (!_fullpath.StartsWith(volume)) return;
Trace("ev_VolumeChanged " + evt + ": " + volume);
if (evt == VolumeWatcherEvent.DidMount)
{
_CheckAvailable(false);
}
else if (evt == VolumeWatcherEvent.WillUnmount || evt == VolumeWatcherEvent.DidUnmount)
{
_CheckAvailable(true); // must stop watcher on WillUnmount so we don't block unmount
}
}
#endif
void FireAvailabilityChanged()
{
if (AvailabilityChanged != null)
AvailabilityChanged(this, Path, Exists);
}
void _CheckAvailable(bool forceunavailable)
{
bool oldvalue = Exists;
Exists = false;
if (!forceunavailable)
{
try {
var di = new DirectoryInfo(_fullpath);
if (di.Exists) {
#if SYSTEM_WINDOWS
di.GetAccessControl(); // on windows, may throw if we have no access.
// always seems to throw on mac...
#endif
Exists = true;
}
} catch { }
}
if (oldvalue != Exists)
{
// do this before firing availability changed because if
// starting watcher fails, it will mark dir as inaccessible.
if (Exists) StartWatcher();
else StopWatcher();
FireAvailabilityChanged();
}
}
static void Trace(string s) {
// Console.WriteLine("[watcher] " + s);
}
#if SYSTEM_MACOSX
// FsEventsWatcher uses the CoreServices FSEvents API: your application's
// main thread must be in a CoreFoundation run loop so the event stream
// listener can be scheduled.
public class FsEventsWatcher : IDisposable
{
public delegate void RootChangedDelegate(FsEventsWatcher sender, string rootpath, bool exists);
public delegate void SubdirectoryChangedDelegate(FsEventsWatcher sender, string dirpath);
List<string> _paths;
IntPtr _stream;
CoreServices.FSEventStreamCallback _callback;
// watched path or one of its parents was created or deleted
public event RootChangedDelegate RootChanged;
// contained subdirectory changed
public event SubdirectoryChangedDelegate SubdirectoryChanged;
public FsEventsWatcher(string path) : this(new List<string>(){ path })
{
}
public FsEventsWatcher(IEnumerable<string> paths)
{
_paths = new List<string>();
foreach (string path in paths)
_paths.Add(System.IO.Path.GetFullPath(path));
Init();
}
public void Dispose()
{
Trace(DateTime.Now + " FsEventsWatcher: stop stream");
CoreServices.FSEventStreamStop(_stream);
Trace(DateTime.Now + " FsEventsWatcher: invalidate stream");
CoreServices.FSEventStreamInvalidate(_stream);
Trace(DateTime.Now + " FsEventsWatcher: release stream");
CoreServices.FSEventStreamRelease(_stream);
_callback = null;
Trace(DateTime.Now + " FsEventsWatcher: disposed");
}
void Init()
{
NSAutoreleasePool pool = new NSAutoreleasePool();
_callback = new CoreServices.FSEventStreamCallback(OnFsEvent);
var pathptrs = new List<IntPtr>();
foreach (string path in _paths)
pathptrs.Add(CoreFoundation.CFSTR(new StringBuilder(path)));
_stream = CoreServices.FSEventStreamCreate(IntPtr.Zero,
_callback,
IntPtr.Zero,
CoreFoundation.CFArrayCreate(pathptrs.ToArray()),
CoreServices.kFSEventStreamEventIdSinceNow,
1.0,
CoreServices.kFSEventStreamCreateFlagWatchRoot);
CoreServices.FSEventStreamScheduleWithRunLoop(_stream,
RunLoopHelper.GetRunLoop(),
CoreFoundation.kCFRunLoopDefaultMode);
CoreServices.FSEventStreamStart(_stream);
//CoreServices.FSEventStreamShow(_stream);
pool.Dispose();
}
void OnFsEvent(IntPtr stream, IntPtr userData,
UIntPtr numEvents,
string[] paths,
uint[] eventFlags,
ulong[] eventIds)
{
string rootchanged = null;
for (int i = 0; i < (uint)numEvents; i++)
{
Trace(String.Format("FsEventsWatcher: Changed {0} in {1}, flags {2}", eventIds[i], paths[i], eventFlags[i]));
string path = paths[i].TrimEnd(new char[]{ '/' });
if (eventFlags[i] == CoreServices.kFSEventStreamEventFlagRootChanged)
{
rootchanged = path;
}
else
{
if (SubdirectoryChanged != null)
SubdirectoryChanged(this, path);
}
}
if (rootchanged != null && RootChanged != null)
RootChanged(this, rootchanged, Directory.Exists(rootchanged) || File.Exists(rootchanged));
}
}
void ev_RootChanged(FsEventsWatcher sender, string rootpath, bool exists)
{
if (!Exists && Directory.Exists(_fullpath))
{
Exists = true;
FireAvailabilityChanged();
}
else if (Exists && !Directory.Exists(_fullpath))
{
Exists = false;
FireAvailabilityChanged();
}
}
void ev_SubdirectoryChanged(FsEventsWatcher sender, string dirpath)
{
if (_watchcontents)
FireSubdirectoryChanged(dirpath);
}
void FireSubdirectoryChanged(string dirpath)
{
if (SubdirectoryChanged != null)
SubdirectoryChanged(this, dirpath);
}
#else
void ev_FileChanged(object sender, FileSystemEventArgs e)
{
if (_watchcontents)
{
Trace(e.ChangeType + ": " + e.FullPath);
FireWatcherEvent(e.ChangeType, e.FullPath);
}
}
void ev_FileRenamed(object sender, RenamedEventArgs e)
{
if (_watchcontents)
{
if (e.FullPath.StartsWith(_fullpath) || e.OldFullPath.StartsWith(_fullpath))
Trace("Renamed: " + e.OldFullPath + " to " + e.FullPath);
if (e.FullPath.StartsWith(_fullpath))
FireWatcherEvent(WatcherChangeTypes.Created, e.FullPath);
if (e.OldFullPath.StartsWith(_fullpath))
FireWatcherEvent(WatcherChangeTypes.Deleted, e.OldFullPath);
}
}
void FireWatcherEvent(WatcherChangeTypes type, string path)
{
switch (type)
{
case WatcherChangeTypes.Created:
if (FileAdded != null) FileAdded(this, path);
break;
case WatcherChangeTypes.Deleted:
if (FileRemoved != null) FileRemoved(this, path);
break;
case WatcherChangeTypes.Changed:
if (FileModified != null) FileModified(this, path);
break;
default: throw new ArgumentException("watcher change type");
}
}
#endif
}
}