forked from kasper/phoenix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPHPathWatcher.m
89 lines (66 loc) · 2.49 KB
/
PHPathWatcher.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
/*
* Phoenix is released under the MIT License. Refer to https://github.com/kasper/phoenix/blob/master/LICENSE.md
*/
#import "PHPathWatcher.h"
@interface PHPathWatcher ()
@property FSEventStreamRef stream;
@property(copy) NSArray<NSString *> *paths;
@property(copy) void (^handler)(void);
@end
@implementation PHPathWatcher
#pragma mark - FSEventStreamCallback
static void PHFSEventStreamCallback(__unused ConstFSEventStreamRef stream,
void *callback,
__unused size_t count,
__unused void *paths,
__unused FSEventStreamEventFlags const flags[],
__unused FSEventStreamEventId const ids[]) {
@autoreleasepool {
PHPathWatcher *watcher = (__bridge PHPathWatcher *)callback;
[watcher fileDidChange];
}
}
#pragma mark - Initialising
- (instancetype)initWithPaths:(NSArray<NSString *> *)paths handler:(void (^)(void))handler {
if (self = [super init]) {
self.paths = paths;
self.handler = handler;
[self setup];
}
return self;
}
+ (instancetype)watcherFor:(NSArray<NSString *> *)paths handler:(void (^)(void))handler {
return [[self alloc] initWithPaths:paths handler:handler];
}
#pragma mark - Deallocing
- (void)dealloc {
FSEventStreamStop(self.stream);
FSEventStreamInvalidate(self.stream);
FSEventStreamRelease(self.stream);
}
#pragma mark - Setting up
- (void)setup {
FSEventStreamContext context;
context.version = 0;
context.info = (__bridge void *)self;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
self.stream = FSEventStreamCreate(NULL,
PHFSEventStreamCallback,
&context,
(__bridge CFArrayRef)self.paths,
kFSEventStreamEventIdSinceNow,
1.0,
kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagFileEvents);
FSEventStreamScheduleWithRunLoop(self.stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
BOOL started = FSEventStreamStart(self.stream);
if (!started) {
NSLog(@"Error: Could not start event stream %@ for observing file changes.", self.stream);
}
}
#pragma mark - Event Handling
- (void)fileDidChange {
self.handler();
}
@end