-
Notifications
You must be signed in to change notification settings - Fork 73
/
CDEvents.m
389 lines (321 loc) · 10.8 KB
/
CDEvents.m
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/**
* CDEvents
*
* Copyright (c) 2010-2013 Aron Cedercrantz
* http://github.com/rastersize/CDEvents/
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#import "CDEvents.h"
#import "CDEventsDelegate.h"
#ifndef __has_feature
#define __has_feature(x) 0
#endif
#if !__has_feature(objc_arc)
#error CDEvents must be built with ARC.
#endif
#if !__has_feature(blocks)
#error CDEvents must be built with support for blocks.
#endif
#pragma mark CDEvents custom exceptions
NSString *const CDEventsEventStreamCreationFailureException = @"CDEventsEventStreamCreationFailureException";
#pragma -
#pragma mark Default values
const CDEventsEventStreamCreationFlags kCDEventsDefaultEventStreamFlags =
(kFSEventStreamCreateFlagUseCFTypes |
kFSEventStreamCreateFlagWatchRoot);
const CDEventIdentifier kCDEventsSinceEventNow = kFSEventStreamEventIdSinceNow;
#pragma mark -
#pragma mark Private API
// Private API
@interface CDEvents () {
@private
CDEventsEventBlock _eventBlock;
FSEventStreamRef _eventStream;
CDEventsEventStreamCreationFlags _eventStreamCreationFlags;
}
// Redefine the properties that should be writeable.
@property (strong, readwrite) CDEvent *lastEvent;
@property (copy, readwrite) NSArray *watchedURLs;
// The FSEvents callback function
static void CDEventsCallback(
ConstFSEventStreamRef streamRef,
void *callbackCtxInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[]);
// Creates and initiates the event stream.
- (void)createEventStream;
// Disposes of the event stream.
- (void)disposeEventStream;
@end
#pragma mark -
#pragma mark Implementation
@implementation CDEvents
#pragma mark Properties
@synthesize delegate = _delegate;
@synthesize notificationLatency = _notificationLatency;
@synthesize sinceEventIdentifier = _sinceEventIdentifier;
@synthesize ignoreEventsFromSubDirectories = _ignoreEventsFromSubDirectories;
@synthesize lastEvent = _lastEvent;
@synthesize watchedURLs = _watchedURLs;
@synthesize excludedURLs = _excludedURLs;
#pragma mark Event identifier class methods
+ (CDEventIdentifier)currentEventIdentifier
{
return (NSUInteger)FSEventsGetCurrentEventId();
}
#pragma mark Init/dealloc/finalize methods
- (void)dealloc
{
[self disposeEventStream];
_delegate = nil;
}
- (void)finalize
{
[self disposeEventStream];
_delegate = nil;
[super finalize];
}
- (id)initWithURLs:(NSArray *)URLs delegate:(id<CDEventsDelegate>)delegate
{
return [self initWithURLs:URLs
delegate:delegate
onRunLoop:[NSRunLoop currentRunLoop]];
}
- (id)initWithURLs:(NSArray *)URLs
delegate:(id<CDEventsDelegate>)delegate
onRunLoop:(NSRunLoop *)runLoop
{
return [self initWithURLs:URLs
delegate:delegate
onRunLoop:runLoop
sinceEventIdentifier:kCDEventsSinceEventNow
notificationLantency:CD_EVENTS_DEFAULT_NOTIFICATION_LATENCY
ignoreEventsFromSubDirs:CD_EVENTS_DEFAULT_IGNORE_EVENT_FROM_SUB_DIRS
excludeURLs:nil
streamCreationFlags:kCDEventsDefaultEventStreamFlags];
}
- (id)initWithURLs:(NSArray *)URLs
delegate:(id<CDEventsDelegate>)delegate
onRunLoop:(NSRunLoop *)runLoop
sinceEventIdentifier:(CDEventIdentifier)sinceEventIdentifier
notificationLantency:(CFTimeInterval)notificationLatency
ignoreEventsFromSubDirs:(BOOL)ignoreEventsFromSubDirs
excludeURLs:(NSArray *)exludeURLs
streamCreationFlags:(CDEventsEventStreamCreationFlags)streamCreationFlags
{
if (delegate == nil) {
[NSException raise:NSInvalidArgumentException
format:@"Invalid arguments passed to CDEvents init-method."];
}
_delegate = delegate;
return [self initWithURLs:URLs
block:^(CDEvents *watcher, CDEvent *event){
if ([(id)[watcher delegate] conformsToProtocol:@protocol(CDEventsDelegate)]) {
[[watcher delegate] URLWatcher:watcher eventOccurred:event];
}
}
onRunLoop:runLoop
sinceEventIdentifier:sinceEventIdentifier
notificationLantency:notificationLatency
ignoreEventsFromSubDirs:ignoreEventsFromSubDirs
excludeURLs:exludeURLs
streamCreationFlags:streamCreationFlags];
}
#pragma mark Creating CDEvents Objects With a Block
- (id)initWithURLs:(NSArray *)URLs block:(CDEventsEventBlock)block
{
return [self initWithURLs:URLs block:block onRunLoop:[NSRunLoop currentRunLoop]];
}
- (id)initWithURLs:(NSArray *)URLs
block:(CDEventsEventBlock)block
onRunLoop:(NSRunLoop *)runLoop
{
return [self initWithURLs:URLs
block:block
onRunLoop:runLoop
sinceEventIdentifier:kCDEventsSinceEventNow
notificationLantency:CD_EVENTS_DEFAULT_NOTIFICATION_LATENCY
ignoreEventsFromSubDirs:CD_EVENTS_DEFAULT_IGNORE_EVENT_FROM_SUB_DIRS
excludeURLs:nil
streamCreationFlags:kCDEventsDefaultEventStreamFlags];
}
- (id)initWithURLs:(NSArray *)URLs
block:(CDEventsEventBlock)block
onRunLoop:(NSRunLoop *)runLoop
sinceEventIdentifier:(CDEventIdentifier)sinceEventIdentifier
notificationLantency:(CFTimeInterval)notificationLatency
ignoreEventsFromSubDirs:(BOOL)ignoreEventsFromSubDirs
excludeURLs:(NSArray *)exludeURLs
streamCreationFlags:(CDEventsEventStreamCreationFlags)streamCreationFlags
{
if (block == NULL || URLs == nil || [URLs count] == 0) {
[NSException raise:NSInvalidArgumentException
format:@"Invalid arguments passed to CDEvents init-method."];
}
if ((self = [super init])) {
_watchedURLs = [URLs copy];
_excludedURLs = [exludeURLs copy];
_eventBlock = block;
_sinceEventIdentifier = sinceEventIdentifier;
_eventStreamCreationFlags = streamCreationFlags;
_notificationLatency = notificationLatency;
_ignoreEventsFromSubDirectories = ignoreEventsFromSubDirs;
_lastEvent = nil;
[self createEventStream];
FSEventStreamScheduleWithRunLoop(_eventStream,
[runLoop getCFRunLoop],
kCFRunLoopDefaultMode);
if (!FSEventStreamStart(_eventStream)) {
[NSException raise:CDEventsEventStreamCreationFailureException
format:@"Failed to create event stream."];
}
}
return self;
}
#pragma mark NSCopying method
- (id)copyWithZone:(NSZone *)zone
{
CDEvents *copy = [[CDEvents alloc] initWithURLs:[self watchedURLs]
block:[self eventBlock]
onRunLoop:[NSRunLoop currentRunLoop]
sinceEventIdentifier:[self sinceEventIdentifier]
notificationLantency:[self notificationLatency]
ignoreEventsFromSubDirs:[self ignoreEventsFromSubDirectories]
excludeURLs:[self excludedURLs]
streamCreationFlags:_eventStreamCreationFlags];
return copy;
}
#pragma mark Block
- (CDEventsEventBlock)eventBlock
{
return _eventBlock;
}
#pragma mark Flush methods
- (void)flushSynchronously
{
FSEventStreamFlushSync(_eventStream);
}
- (void)flushAsynchronously
{
FSEventStreamFlushAsync(_eventStream);
}
#pragma mark Misc methods
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: %p { watchedURLs = %@ }>",
[self className],
self,
[self watchedURLs]];
}
- (NSString *)streamDescription
{
CFStringRef streamDescriptionCF = FSEventStreamCopyDescription(_eventStream);
NSString *returnString = [[NSString alloc] initWithString:(__bridge NSString *)streamDescriptionCF];
CFRelease(streamDescriptionCF);
return returnString;
}
#pragma mark Private API:
- (void)createEventStream
{
FSEventStreamContext callbackCtx;
callbackCtx.version = 0;
callbackCtx.info = (__bridge void *)self;
callbackCtx.retain = NULL;
callbackCtx.release = NULL;
callbackCtx.copyDescription = NULL;
NSMutableArray *watchedPaths = [NSMutableArray arrayWithCapacity:[[self watchedURLs] count]];
for (NSURL *URL in [self watchedURLs]) {
[watchedPaths addObject:[URL path]];
}
_eventStream = FSEventStreamCreate(kCFAllocatorDefault,
&CDEventsCallback,
&callbackCtx,
(__bridge CFArrayRef)watchedPaths,
(FSEventStreamEventId)[self sinceEventIdentifier],
[self notificationLatency],
(uint) _eventStreamCreationFlags);
}
- (void)disposeEventStream
{
if (!(_eventStream)) {
return;
}
FSEventStreamStop(_eventStream);
FSEventStreamInvalidate(_eventStream);
FSEventStreamRelease(_eventStream);
_eventStream = NULL;
}
static void CDEventsCallback(
ConstFSEventStreamRef streamRef,
void *callbackCtxInfo,
size_t numEvents,
void *eventPaths, // CFArrayRef
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
CDEvents *watcher = (__bridge CDEvents *)callbackCtxInfo;
NSArray *eventPathsArray = (__bridge NSArray *)eventPaths;
NSArray *watchedURLs = [watcher watchedURLs];
NSArray *excludedURLs = [watcher excludedURLs];
CDEvent *lastEvent = nil;
for (NSUInteger i = 0; i < numEvents; ++i) {
BOOL shouldIgnore = NO;
FSEventStreamEventFlags flags = eventFlags[i];
FSEventStreamEventId identifier = eventIds[i];
// We do this hackery to ensure that the eventPath string doesn't
// contain any trailing slash.
NSURL *eventURL = [NSURL fileURLWithPath:[[eventPathsArray objectAtIndex:i] stringByStandardizingPath]];
NSString *eventPath = [eventURL path];
// Ignore all events except for the URLs we are explicitly watching.
if ([watcher ignoreEventsFromSubDirectories]) {
shouldIgnore = YES;
for (NSURL *url in watchedURLs) {
if ([[url path] isEqualToString:eventPath]) {
shouldIgnore = NO;
break;
}
}
// Ignore all explicitly excludeded URLs (not required to check if we
// ignore all events from sub-directories).
} else if (excludedURLs != nil) {
for (NSURL *url in excludedURLs) {
if ([eventPath hasPrefix:[url path]]) {
shouldIgnore = YES;
break;
}
}
}
if (!shouldIgnore) {
CDEvent *event = [[CDEvent alloc] initWithIdentifier:identifier date:[NSDate date] URL:eventURL flags:flags];
lastEvent = event;
CDEventsEventBlock eventBlock = [watcher eventBlock];
eventBlock(watcher, event);
}
}
if (lastEvent) {
[watcher setLastEvent:lastEvent];
}
}
@end