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
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/file_path_watcher/file_path_watcher.h"
#include <CoreServices/CoreServices.h>
#include <set>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/message_loop.h"
#include "base/singleton.h"
#include "base/time.h"
// Note to future well meaning engineers. Unless kqueue semantics have changed
// considerably, do NOT try to reimplement this class using kqueue. The main
// problem is that this class requires the ability to watch a directory
// and notice changes to any files within it. A kqueue on a directory can watch
// for creation and deletion of files, but not for modifications to files within
// the directory. To do this with the current kqueue semantics would require
// kqueueing every file in the directory, and file descriptors are a limited
// resource. If you have a good idea on how to get around this, the source for a
// reasonable implementation of this class using kqueues is attached here:
// http://code.google.com/p/chromium/issues/detail?id=54822#c13
namespace {
// The latency parameter passed to FSEventsStreamCreate().
const CFAbsoluteTime kEventLatencySeconds = 0.3;
// Mac-specific file watcher implementation based on the FSEvents API.
class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate,
public MessageLoop::DestructionObserver {
public:
FilePathWatcherImpl();
// Called from the FSEvents callback whenever there is a change to the paths
void OnFilePathChanged();
// (Re-)Initialize the event stream to start reporting events from
// |start_event|.
void UpdateEventStream(FSEventStreamEventId start_event);
// FilePathWatcher::PlatformDelegate overrides.
virtual bool Watch(const FilePath& path,
FilePathWatcher::Delegate* delegate,
base::MessageLoopProxy* loop) OVERRIDE;
virtual void Cancel() OVERRIDE;
// Deletion of the FilePathWatcher will call Cancel() to dispose of this
// object in the right thread. This also observes destruction of the required
// cleanup thread, in case it quits before Cancel() is called.
virtual void WillDestroyCurrentMessageLoop() OVERRIDE;
scoped_refptr<base::MessageLoopProxy> run_loop_message_loop() {
return run_loop_message_loop_;
}
private:
virtual ~FilePathWatcherImpl() {}
// Destroy the event stream.
void DestroyEventStream();
// Start observing the destruction of the |run_loop_message_loop_| thread,
// and watching the FSEventStream.
void StartObserverAndEventStream(FSEventStreamEventId start_event);
// Cleans up and stops observing the |run_loop_message_loop_| thread.
void CancelOnMessageLoopThread() OVERRIDE;
// Delegate to notify upon changes.
scoped_refptr<FilePathWatcher::Delegate> delegate_;
// Target path to watch (passed to delegate).
FilePath target_;
// Keep track of the last modified time of the file. We use nulltime
// to represent the file not existing.
base::Time last_modified_;
// The time at which we processed the first notification with the
// |last_modified_| time stamp.
base::Time first_notification_;
// Backend stream we receive event callbacks from (strong reference).
FSEventStreamRef fsevent_stream_;
// Run loop for FSEventStream to run on.
scoped_refptr<base::MessageLoopProxy> run_loop_message_loop_;
DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
};
// The callback passed to FSEventStreamCreate().
void FSEventsCallback(ConstFSEventStreamRef stream,
void* event_watcher, size_t num_events,
void* event_paths, const FSEventStreamEventFlags flags[],
const FSEventStreamEventId event_ids[]) {
FilePathWatcherImpl* watcher =
reinterpret_cast<FilePathWatcherImpl*>(event_watcher);
DCHECK(watcher->run_loop_message_loop()->BelongsToCurrentThread());
bool root_changed = false;
FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream);
for (size_t i = 0; i < num_events; i++) {
if (flags[i] & kFSEventStreamEventFlagRootChanged)
root_changed = true;
if (event_ids[i])
root_change_at = std::min(root_change_at, event_ids[i]);
}
// Reinitialize the event stream if we find changes to the root. This is
// necessary since FSEvents doesn't report any events for the subtree after
// the directory to be watched gets created.
if (root_changed) {
// Resetting the event stream from within the callback fails (FSEvents spews
// bad file descriptor errors), so post a task to do the reset.
watcher->run_loop_message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(watcher, &FilePathWatcherImpl::UpdateEventStream,
root_change_at));
}
watcher->OnFilePathChanged();
}
// FilePathWatcherImpl implementation:
FilePathWatcherImpl::FilePathWatcherImpl()
: fsevent_stream_(NULL) {
}
void FilePathWatcherImpl::OnFilePathChanged() {
// Switch to the CFRunLoop based thread if necessary, so we can tear down
// the event stream.
if (!message_loop()->BelongsToCurrentThread()) {
message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &FilePathWatcherImpl::OnFilePathChanged));
return;
}
DCHECK(message_loop()->BelongsToCurrentThread());
DCHECK(!target_.empty());
base::PlatformFileInfo file_info;
bool file_exists = file_util::GetFileInfo(target_, &file_info);
if (file_exists && (last_modified_.is_null() ||
last_modified_ != file_info.last_modified)) {
last_modified_ = file_info.last_modified;
first_notification_ = base::Time::Now();
delegate_->OnFilePathChanged(target_);
} else if (file_exists && !first_notification_.is_null()) {
// The target's last modification time is equal to what's on record. This
// means that either an unrelated event occurred, or the target changed
// again (file modification times only have a resolution of 1s). Comparing
// file modification times against the wall clock is not reliable to find
// out whether the change is recent, since this code might just run too
// late. Moreover, there's no guarantee that file modification time and wall
// clock times come from the same source.
//
// Instead, the time at which the first notification carrying the current
// |last_notified_| time stamp is recorded. Later notifications that find
// the same file modification time only need to be forwarded until wall
// clock has advanced one second from the initial notification. After that
// interval, client code is guaranteed to having seen the current revision
// of the file.
if (base::Time::Now() - first_notification_ >
base::TimeDelta::FromSeconds(1)) {
// Stop further notifications for this |last_modification_| time stamp.
first_notification_ = base::Time();
}
delegate_->OnFilePathChanged(target_);
} else if (!file_exists && !last_modified_.is_null()) {
last_modified_ = base::Time();
delegate_->OnFilePathChanged(target_);
}
}
bool FilePathWatcherImpl::Watch(const FilePath& path,
FilePathWatcher::Delegate* delegate,
base::MessageLoopProxy* loop) {
DCHECK(target_.value().empty());
DCHECK(MessageLoopForIO::current());
set_message_loop(base::MessageLoopProxy::CreateForCurrentThread());
run_loop_message_loop_ = loop;
target_ = path;
delegate_ = delegate;
FSEventStreamEventId start_event = FSEventsGetCurrentEventId();
base::PlatformFileInfo file_info;
if (file_util::GetFileInfo(target_, &file_info)) {
last_modified_ = file_info.last_modified;
first_notification_ = base::Time::Now();
}
run_loop_message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(this, &FilePathWatcherImpl::StartObserverAndEventStream,
start_event));
return true;
}
void FilePathWatcherImpl::StartObserverAndEventStream(
FSEventStreamEventId start_event) {
DCHECK(run_loop_message_loop()->BelongsToCurrentThread());
MessageLoop::current()->AddDestructionObserver(this);
UpdateEventStream(start_event);
}
void FilePathWatcherImpl::Cancel() {
if (!run_loop_message_loop().get()) {
// Watch was never called, so exit.
set_cancelled();
return;
}
// Switch to the CFRunLoop based thread if necessary, so we can tear down
// the event stream.
if (!run_loop_message_loop()->BelongsToCurrentThread()) {
run_loop_message_loop()->PostTask(FROM_HERE,
new FilePathWatcher::CancelTask(this));
} else {
CancelOnMessageLoopThread();
}
}
void FilePathWatcherImpl::CancelOnMessageLoopThread() {
set_cancelled();
if (fsevent_stream_) {
DestroyEventStream();
MessageLoop::current()->RemoveDestructionObserver(this);
delegate_ = NULL;
}
}
void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() {
CancelOnMessageLoopThread();
}
void FilePathWatcherImpl::UpdateEventStream(FSEventStreamEventId start_event) {
DCHECK(run_loop_message_loop()->BelongsToCurrentThread());
DCHECK(MessageLoopForUI::current());
// It can happen that the watcher gets canceled while tasks that call this
// function are still in flight, so abort if this situation is detected.
if (is_cancelled())
return;
if (fsevent_stream_)
DestroyEventStream();
base::mac::ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString(
NULL, target_.value().c_str(), kCFStringEncodingMacHFS));
base::mac::ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString(
NULL, target_.DirName().value().c_str(), kCFStringEncodingMacHFS));
CFStringRef paths_array[] = { cf_path.get(), cf_dir_path.get() };
base::mac::ScopedCFTypeRef<CFArrayRef> watched_paths(CFArrayCreate(
NULL, reinterpret_cast<const void**>(paths_array), arraysize(paths_array),
&kCFTypeArrayCallBacks));
FSEventStreamContext context;
context.version = 0;
context.info = this;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
fsevent_stream_ = FSEventStreamCreate(NULL, &FSEventsCallback, &context,
watched_paths,
start_event,
kEventLatencySeconds,
kFSEventStreamCreateFlagWatchRoot);
FSEventStreamScheduleWithRunLoop(fsevent_stream_, CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
if (!FSEventStreamStart(fsevent_stream_)) {
message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(delegate_.get(),
&FilePathWatcher::Delegate::OnError));
}
}
void FilePathWatcherImpl::DestroyEventStream() {
FSEventStreamStop(fsevent_stream_);
FSEventStreamUnscheduleFromRunLoop(fsevent_stream_, CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
FSEventStreamRelease(fsevent_stream_);
fsevent_stream_ = NULL;
}
} // namespace
FilePathWatcher::FilePathWatcher() {
impl_ = new FilePathWatcherImpl();
}
|