Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(12)

Side by Side Diff: content/common/file_path_watcher/file_path_watcher_mac.cc

Issue 6731064: kqueue implementation of FilePathWatcher on Mac. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 9 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/common/file_path_watcher/file_path_watcher.h" 5 #include "content/common/file_path_watcher/file_path_watcher.h"
6 6
7 #include <CoreServices/CoreServices.h> 7 #include <fcntl.h>
8 #include <set> 8 #include <sys/event.h>
9 9 #include <sys/param.h>
10 #include "base/file_path.h" 10
11 #include <vector>
12
11 #include "base/file_util.h" 13 #include "base/file_util.h"
12 #include "base/logging.h"
13 #include "base/mac/scoped_cftyperef.h"
14 #include "base/message_loop.h" 14 #include "base/message_loop.h"
15 #include "base/singleton.h" 15 #include "base/message_loop_proxy.h"
16 #include "base/time.h"
17
18 // Note to future well meaning engineers. Unless kqueue semantics have changed
19 // considerably, do NOT try to reimplement this class using kqueue. The main
20 // problem is that this class requires the ability to watch a directory
21 // and notice changes to any files within it. A kqueue on a directory can watch
22 // for creation and deletion of files, but not for modifications to files within
23 // the directory. To do this with the current kqueue semantics would require
24 // kqueueing every file in the directory, and file descriptors are a limited
25 // resource. If you have a good idea on how to get around this, the source for a
26 // reasonable implementation of this class using kqueues is attached here:
27 // http://code.google.com/p/chromium/issues/detail?id=54822#c13
28 16
29 namespace { 17 namespace {
30 18
31 // The latency parameter passed to FSEventsStreamCreate(). 19 // Mac-specific file watcher implementation based on kqueue.
32 const CFAbsoluteTime kEventLatencySeconds = 0.3; 20 // Originally it was based on FSEvents so that the semantics were equivalent
33 21 // on Linux, OSX and Windows where it was able to detect:
34 // Mac-specific file watcher implementation based on the FSEvents API. 22 // - file creation/deletion/modification in a watched directory
23 // - file creation/deletion/modification for a watched file
24 // - modifications to the paths to a watched object that would affect the
25 // object such as renaming/attibute changes etc.
26 // The FSEvents version did all of the above except handling attribute changes
27 // to path components. Unfortunately FSEvents appears to have an issue where the
28 // current implementation (Mac OS X 10.6.7) sometimes drops events and doesn't
29 // send notifications. See
30 // http://code.google.com/p/chromium/issues/detail?id=54822#c31 for source that
31 // will reproduce the problem. The kqueue implementation will handle all of the
32 // items in the list above except for detecting modifications to files in a
33 // watched directory. It will detect the creation and deletion of files, just
34 // not the modification of files. It does however detect the attribute changes
35 // that the FSEvents impl would miss.
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 Maybe also mention that FSEvents needs a runloop b
dmac 2011/03/30 17:18:47 Done.
35 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate, 36 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate,
37 public MessageLoopForIO::Watcher,
36 public MessageLoop::DestructionObserver { 38 public MessageLoop::DestructionObserver {
37 public: 39 public:
38 FilePathWatcherImpl(); 40 FilePathWatcherImpl() : kqueue_(-1) {}
39 41 virtual ~FilePathWatcherImpl() {}
40 // Called from the FSEvents callback whenever there is a change to the paths 42
41 void OnFilePathChanged(); 43 // MessageLoopForIO::Watcher overrides.
42 44 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
43 // (Re-)Initialize the event stream to start reporting events from 45 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE;
44 // |start_event|. 46
45 void UpdateEventStream(FSEventStreamEventId start_event); 47 // MessageLoop::DestructionObserver overrides.
48 virtual void WillDestroyCurrentMessageLoop() OVERRIDE;
46 49
47 // FilePathWatcher::PlatformDelegate overrides. 50 // FilePathWatcher::PlatformDelegate overrides.
48 virtual bool Watch(const FilePath& path, 51 virtual bool Watch(const FilePath& path,
49 FilePathWatcher::Delegate* delegate, 52 FilePathWatcher::Delegate* delegate) OVERRIDE;
50 base::MessageLoopProxy* loop) OVERRIDE;
51 virtual void Cancel() OVERRIDE; 53 virtual void Cancel() OVERRIDE;
52 54
53 // Deletion of the FilePathWatcher will call Cancel() to dispose of this
54 // object in the right thread. This also observes destruction of the required
55 // cleanup thread, in case it quits before Cancel() is called.
56 virtual void WillDestroyCurrentMessageLoop() OVERRIDE;
57
58 scoped_refptr<base::MessageLoopProxy> run_loop_message_loop() {
59 return run_loop_message_loop_;
60 }
61
62 private: 55 private:
63 virtual ~FilePathWatcherImpl() {} 56 class EventData {
64 57 public:
65 // Destroy the event stream. 58 EventData(const FilePath& path, const FilePath::StringType& subdir)
66 void DestroyEventStream(); 59 : path_(path), subdir_(subdir) { }
67 60 FilePath path_; // Full path to this item.
68 // Start observing the destruction of the |run_loop_message_loop_| thread, 61 FilePath::StringType subdir_; // Path to any sub item.
69 // and watching the FSEventStream. 62 };
70 void StartObserverAndEventStream(FSEventStreamEventId start_event); 63 typedef std::vector<struct kevent> EventVector;
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 Ah, does this mean we consume one file descriptor
dmac 2011/03/30 17:18:47 That's kind of a requirement for the kqueue implem
71 64
72 // Cleans up and stops observing the |run_loop_message_loop_| thread. 65 virtual void CancelOnMessageLoopThread() OVERRIDE;
Mark Mentovai 2011/03/29 21:27:25 This deserves a comment. Does it mean that it can
dmac 2011/03/30 17:18:47 Done.
73 void CancelOnMessageLoopThread() OVERRIDE; 66
74 67 // Fills |events| with one kevent per component in |path|.
75 // Delegate to notify upon changes. 68 // Returns the number of valid events created where a valid event is
69 // defined as one that has a ident (file descriptor) field != -1.
70 static int EventsForPath(FilePath path, EventVector *events);
71
72 // Release a kevent generated by EventsForPath.
73 static void ReleaseEvent(struct kevent& event);
Mark Mentovai 2011/03/29 21:27:25 It’s unorthodox in our style to pass a non-const r
dmac 2011/03/30 17:18:47 I'm only doing it this way because I use foreach b
74
75 // Returns a file descriptor that will not block the system from deleting
76 // the file it references.
77 static int FileDescriptorForPath(const FilePath& path);
78
79 // Closes |*fd| and sets |*fd| to -1.
80 static void CloseFileDescriptor(int *fd);
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 use int* instead of int *
dmac 2011/03/30 17:18:47 Done.
81
82 EventVector events_;
83 scoped_refptr<base::MessageLoopProxy> io_message_loop_;
84 MessageLoopForIO::FileDescriptorWatcher kqueue_watcher_;
76 scoped_refptr<FilePathWatcher::Delegate> delegate_; 85 scoped_refptr<FilePathWatcher::Delegate> delegate_;
77
78 // Target path to watch (passed to delegate).
79 FilePath target_; 86 FilePath target_;
80 87 int kqueue_;
81 // Keep track of the last modified time of the file. We use nulltime
82 // to represent the file not existing.
83 base::Time last_modified_;
84
85 // The time at which we processed the first notification with the
86 // |last_modified_| time stamp.
87 base::Time first_notification_;
88
89 // Backend stream we receive event callbacks from (strong reference).
90 FSEventStreamRef fsevent_stream_;
91
92 // Run loop for FSEventStream to run on.
93 scoped_refptr<base::MessageLoopProxy> run_loop_message_loop_;
94 88
95 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); 89 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
96 }; 90 };
97 91
98 // The callback passed to FSEventStreamCreate(). 92 void FilePathWatcherImpl::ReleaseEvent(struct kevent& event) {
99 void FSEventsCallback(ConstFSEventStreamRef stream, 93 EventData* entry = reinterpret_cast<EventData*>(event.udata);
100 void* event_watcher, size_t num_events, 94 delete entry;
101 void* event_paths, const FSEventStreamEventFlags flags[], 95 event.udata = NULL;
102 const FSEventStreamEventId event_ids[]) { 96 }
103 FilePathWatcherImpl* watcher = 97
104 reinterpret_cast<FilePathWatcherImpl*>(event_watcher); 98 int FilePathWatcherImpl::EventsForPath(FilePath path, EventVector *events) {
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 Asterisk by the type.
dmac 2011/03/30 17:18:47 Done.
105 DCHECK(watcher->run_loop_message_loop()->BelongsToCurrentThread()); 99 DCHECK(MessageLoopForIO::current());
106 100 // Make sure that we are working with a clean slate.
107 bool root_changed = false; 101 DCHECK(events->empty());
108 FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream); 102
109 for (size_t i = 0; i < num_events; i++) { 103 std::vector<FilePath::StringType> components;
110 if (flags[i] & kFSEventStreamEventFlagRootChanged) 104 path.GetComponents(&components);
111 root_changed = true; 105
112 if (event_ids[i]) 106 if (components.size() < 1) {
113 root_change_at = std::min(root_change_at, event_ids[i]); 107 return -1;
114 } 108 }
115 109
116 // Reinitialize the event stream if we find changes to the root. This is 110 int last_existing_entry = 0;
117 // necessary since FSEvents doesn't report any events for the subtree after 111 FilePath built_path;
118 // the directory to be watched gets created. 112 bool path_still_exists = true;
119 if (root_changed) { 113 for(std::vector<FilePath::StringType>::iterator i = components.begin();
120 // Resetting the event stream from within the callback fails (FSEvents spews 114 i != components.end(); ++i) {
121 // bad file descriptor errors), so post a task to do the reset. 115 if (i == components.begin()) {
122 watcher->run_loop_message_loop()->PostTask(FROM_HERE, 116 built_path = FilePath(*i);
123 NewRunnableMethod(watcher, &FilePathWatcherImpl::UpdateEventStream, 117 } else {
124 root_change_at)); 118 built_path = built_path.Append(*i);
125 } 119 }
126 120 int fd = -1;
127 watcher->OnFilePathChanged(); 121 if (path_still_exists) {
128 } 122 fd = FileDescriptorForPath(built_path);
Mark Mentovai 2011/03/29 21:27:25 Do you have to worry about closing these ever? You
dmac 2011/03/30 17:18:47 Good catch. ReleaseEvent now handles closing them.
129 123 if (fd == -1) {
130 // FilePathWatcherImpl implementation: 124 path_still_exists = false;
131 125 } else {
132 FilePathWatcherImpl::FilePathWatcherImpl() 126 ++last_existing_entry;
133 : fsevent_stream_(NULL) { 127 }
134 } 128 }
135 129 FilePath::StringType subdir = (i != (components.end() - 1)) ? *(i + 1) : "";
136 void FilePathWatcherImpl::OnFilePathChanged() { 130 EventData* data = new EventData(built_path, subdir);
137 // Switch to the CFRunLoop based thread if necessary, so we can tear down 131 struct kevent event;
138 // the event stream. 132 EV_SET(&event, fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR | EV_RECEIPT),
139 if (!message_loop()->BelongsToCurrentThread()) { 133 (NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB
140 message_loop()->PostTask( 134 | NOTE_RENAME | NOTE_REVOKE | NOTE_EXTEND), 0, data);
Mark Mentovai 2011/03/29 21:27:25 Put the operator at the end of the preceding line
dmac 2011/03/30 17:18:47 Done.
141 FROM_HERE, 135 events->push_back(event);
142 NewRunnableMethod(this, &FilePathWatcherImpl::OnFilePathChanged)); 136 }
137 return last_existing_entry;
138 }
139
140 int FilePathWatcherImpl::FileDescriptorForPath(const FilePath& path) {
141 return HANDLE_EINTR(open(path.value().c_str(), O_EVTONLY | O_NONBLOCK));
142 }
143
144 void FilePathWatcherImpl::CloseFileDescriptor(int *fd) {
145 if (*fd == -1) {
143 return; 146 return;
144 } 147 }
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 No need for curlies for single-line conditionals (
dmac 2011/03/30 17:18:47 I like them. With all the python programmers we ha
145 148
146 DCHECK(message_loop()->BelongsToCurrentThread()); 149 if (HANDLE_EINTR(close(*fd)) != 0) {
147 DCHECK(!target_.empty()); 150 PLOG(ERROR) << "close";
148 151 }
149 base::PlatformFileInfo file_info; 152 *fd = -1;
150 bool file_exists = file_util::GetFileInfo(target_, &file_info); 153 }
151 if (file_exists && (last_modified_.is_null() || 154
152 last_modified_ != file_info.last_modified)) { 155 void FilePathWatcherImpl::OnFileCanReadWithoutBlocking(int fd) {
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 This is a very long function that handles separate
dmac 2011/03/30 17:18:47 I tried breaking it up a bit, and it didn't really
153 last_modified_ = file_info.last_modified; 156 DCHECK(MessageLoopForIO::current());
154 first_notification_ = base::Time::Now(); 157 CHECK_EQ(fd, kqueue_);
158 std::vector<struct kevent> updates(events_.size());
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 Maybe a scoped_array is more appropriate?
Mark Mentovai 2011/03/30 13:59:08 Mattias Nissler wrote:
Mattias Nissler (ping if slow) 2011/03/30 14:07:52 Can you give reasons? He doesn't use any vector-sp
dmac 2011/03/30 17:18:47 This discussion was taken to email ;-) Left as a v
159 struct timespec timeout = {0, 0};
160 int count = kevent(kqueue_, NULL, 0, &updates[0], updates.size(), &timeout);
Mark Mentovai 2011/03/29 21:27:25 HANDLE_EINTR.
dmac 2011/03/30 17:18:47 Done.
161 if (count < 0) {
162 PLOG(ERROR) << "kevent";
163 delegate_->OnError();
164 Cancel();
165 return;
166 }
167 bool update_watches = false;
168 bool send_notification = false;
169
170 for (int i = 0; i < count; ++i) {
171 EventVector::iterator event(events_.begin());
172 for ( ; event != events_.end(); ++event) {
173 if (event->ident == updates[i].ident)
174 break;
175 }
176 CHECK(event != events_.end());
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 trusting the kernel to only pass valid fds? We've
dmac 2011/03/30 17:18:47 I've never seen this on the Mac (not to say it can
177 EventData* event_data = reinterpret_cast<EventData*>(event->udata);
178 bool target_file_affected = event_data->subdir_.empty();
179 if (updates[i].fflags & NOTE_DELETE || updates[i].fflags & NOTE_REVOKE) {
180 // This is no longer accessible, so close the descriptor for it.
181 CloseFileDescriptor(reinterpret_cast<int*>(&event->ident));
182 update_watches = true;
183 } else if (updates[i].fflags & NOTE_RENAME) {
184 target_file_affected = true;
185 for (; event != events_.end(); ++event) {
186 // Close all nodes from the event down.
187 CloseFileDescriptor(reinterpret_cast<int*>(&event->ident));
188 }
189 update_watches = true;
190 } else if (updates[i].fflags & NOTE_WRITE) {
191 if (!target_file_affected) {
192 // In a directory this means a file has been added or deleted.
193 // Deletions are taken care of above so check for addition.
194 EventVector::iterator next_event = event + 1;
195 EventData* next_event_data =
196 reinterpret_cast<EventData*>(next_event->udata);
Mark Mentovai 2011/03/29 21:27:25 Continuation lines are indented by 4.
dmac 2011/03/30 17:18:47 Done.
197 if (next_event->ident == static_cast<uintptr_t>(-1)) {
198 next_event->ident = FileDescriptorForPath(next_event_data->path_);
199 if (next_event->ident != static_cast<uintptr_t>(-1)) {
200 update_watches = true;
201 if (next_event_data->subdir_.empty()) {
202 target_file_affected = true;
203 }
204 }
205 }
206 }
207 }
208 send_notification |= target_file_affected;
209 }
210
211 // Iterate over events adding kevents for items that exist to the kqueue.
212 // Then check to see if new components in the path have been created.
213 // Repeat until no new components in the path are detected.
214 // This is to get around races in directory creation in a watched path.
215 while (update_watches) {
216 size_t valid;
217 for (valid = 0; valid < events_.size(); ++valid) {
218 if (events_[valid].ident == static_cast<uintptr_t>(-1)) {
219 break;
220 }
221 }
222 count = kevent(kqueue_, &events_[0], valid, NULL, 0, NULL);
Mark Mentovai 2011/03/29 21:27:25 HANDLE_EINTR (mostly just paranoia in this case).
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 Don't we need EV_ERROR checking for the responses?
dmac 2011/03/30 17:18:47 Done.
dmac 2011/03/30 17:18:47 Done.
223 if (count < 0) {
224 PLOG(ERROR) << "kevent";
225 delegate_->OnError();
226 Cancel();
227 return;
228 }
229 update_watches = false;
230 for(; valid < events_.size(); ++valid) {
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 space after for
dmac 2011/03/30 17:18:47 Done.
231 EventData* event_data =
232 reinterpret_cast<EventData*>(events_[valid].udata);
233 events_[valid].ident = FileDescriptorForPath(event_data->path_);
234 if (events_[valid].ident != static_cast<uintptr_t>(-1)) {
235 update_watches = true;
236 if (event_data->subdir_.empty()) {
237 send_notification = true;
238 }
239 } else {
240 break;
241 }
242 }
243 }
244
245 if (send_notification) {
155 delegate_->OnFilePathChanged(target_); 246 delegate_->OnFilePathChanged(target_);
156 } else if (file_exists && !first_notification_.is_null()) { 247 }
157 // The target's last modification time is equal to what's on record. This 248 }
158 // means that either an unrelated event occurred, or the target changed 249
159 // again (file modification times only have a resolution of 1s). Comparing 250 void FilePathWatcherImpl::OnFileCanWriteWithoutBlocking(int fd) {
160 // file modification times against the wall clock is not reliable to find 251 NOTREACHED();
161 // out whether the change is recent, since this code might just run too 252 }
162 // late. Moreover, there's no guarantee that file modification time and wall 253
163 // clock times come from the same source. 254 void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() {
164 // 255 CancelOnMessageLoopThread();
165 // Instead, the time at which the first notification carrying the current
166 // |last_notified_| time stamp is recorded. Later notifications that find
167 // the same file modification time only need to be forwarded until wall
168 // clock has advanced one second from the initial notification. After that
169 // interval, client code is guaranteed to having seen the current revision
170 // of the file.
171 if (base::Time::Now() - first_notification_ >
172 base::TimeDelta::FromSeconds(1)) {
173 // Stop further notifications for this |last_modification_| time stamp.
174 first_notification_ = base::Time();
175 }
176 delegate_->OnFilePathChanged(target_);
177 } else if (!file_exists && !last_modified_.is_null()) {
178 last_modified_ = base::Time();
179 delegate_->OnFilePathChanged(target_);
180 }
181 } 256 }
182 257
183 bool FilePathWatcherImpl::Watch(const FilePath& path, 258 bool FilePathWatcherImpl::Watch(const FilePath& path,
184 FilePathWatcher::Delegate* delegate, 259 FilePathWatcher::Delegate* delegate) {
185 base::MessageLoopProxy* loop) {
186 DCHECK(target_.value().empty());
187 DCHECK(MessageLoopForIO::current()); 260 DCHECK(MessageLoopForIO::current());
188 261 DCHECK(target_.value().empty()); // Can only watch one path.
189 set_message_loop(base::MessageLoopProxy::CreateForCurrentThread()); 262 DCHECK(delegate);
190 run_loop_message_loop_ = loop; 263 DCHECK_EQ(kqueue_, -1);
264
265 delegate_ = delegate;
191 target_ = path; 266 target_ = path;
192 delegate_ = delegate; 267
193
194 FSEventStreamEventId start_event = FSEventsGetCurrentEventId();
195
196 base::PlatformFileInfo file_info;
197 if (file_util::GetFileInfo(target_, &file_info)) {
198 last_modified_ = file_info.last_modified;
199 first_notification_ = base::Time::Now();
200 }
201
202 run_loop_message_loop()->PostTask(FROM_HERE,
203 NewRunnableMethod(this, &FilePathWatcherImpl::StartObserverAndEventStream,
204 start_event));
205
206 return true;
207 }
208
209 void FilePathWatcherImpl::StartObserverAndEventStream(
210 FSEventStreamEventId start_event) {
211 DCHECK(run_loop_message_loop()->BelongsToCurrentThread());
212 MessageLoop::current()->AddDestructionObserver(this); 268 MessageLoop::current()->AddDestructionObserver(this);
213 UpdateEventStream(start_event); 269 io_message_loop_ = base::MessageLoopProxy::CreateForCurrentThread();
270
271 kqueue_ = kqueue();
272 if (kqueue_ == -1) {
273 PLOG(ERROR) << "kqueue";
274 return false;
275 }
276
277 int last_entry = EventsForPath(target_, &events_);
278 std::vector<struct kevent> responses(last_entry);
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 a scoped_array might be more appropriate here?
dmac 2011/03/30 17:18:47 comment about vector vs scoped_array above.
279
280 if (HANDLE_EINTR(kevent(kqueue_, &events_[0], last_entry, &responses[0],
281 last_entry, NULL)) == -1) {
282 PLOG(ERROR) << "kevent";
283 return false;
Mattias Nissler (ping if slow) 2011/03/30 11:30:52 Do we need to close the directory FDs when we hit
dmac 2011/03/30 17:18:47 They would be closed off in the dtor, but I can se
284 }
285
286 bool error_occurred = false;
287 for(int i = 0; i < last_entry; ++i) {
288 if (responses[i].flags & EV_ERROR && responses[i].data) {
289 LOG(ERROR) << "Error: " << responses[i].data;
290 error_occurred = true;
291 }
292 }
293 if (error_occurred) {
294 return false;
295 }
296
297 return MessageLoopForIO::current()->WatchFileDescriptor(
298 kqueue_, true, MessageLoopForIO::WATCH_READ, &kqueue_watcher_, this);
214 } 299 }
215 300
216 void FilePathWatcherImpl::Cancel() { 301 void FilePathWatcherImpl::Cancel() {
217 if (!run_loop_message_loop().get()) { 302 base::MessageLoopProxy* proxy = io_message_loop_.get();
218 // Watch was never called, so exit. 303 if (!proxy) {
219 set_cancelled(); 304 set_cancelled();
220 return; 305 return;
221 } 306 }
222 307 if (!proxy->BelongsToCurrentThread()) {
223 // Switch to the CFRunLoop based thread if necessary, so we can tear down 308 proxy->PostTask(FROM_HERE,
224 // the event stream. 309 NewRunnableMethod(this, &FilePathWatcherImpl::Cancel));
225 if (!run_loop_message_loop()->BelongsToCurrentThread()) { 310 return;
226 run_loop_message_loop()->PostTask(FROM_HERE, 311 }
227 new FilePathWatcher::CancelTask(this)); 312 CancelOnMessageLoopThread();
228 } else {
229 CancelOnMessageLoopThread();
230 }
231 } 313 }
232 314
233 void FilePathWatcherImpl::CancelOnMessageLoopThread() { 315 void FilePathWatcherImpl::CancelOnMessageLoopThread() {
234 set_cancelled(); 316 if (!is_cancelled()) {
235 if (fsevent_stream_) { 317 set_cancelled();
236 DestroyEventStream(); 318 kqueue_watcher_.StopWatchingFileDescriptor();
319 CloseFileDescriptor(&kqueue_);
320 std::for_each(events_.begin(), events_.end(), ReleaseEvent);
321 events_.clear();
322 io_message_loop_.release();
237 MessageLoop::current()->RemoveDestructionObserver(this); 323 MessageLoop::current()->RemoveDestructionObserver(this);
238 delegate_ = NULL; 324 delegate_ = NULL;
239 } 325 }
240 } 326 }
241 327
242 void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() {
243 CancelOnMessageLoopThread();
244 }
245
246 void FilePathWatcherImpl::UpdateEventStream(FSEventStreamEventId start_event) {
247 DCHECK(run_loop_message_loop()->BelongsToCurrentThread());
248 DCHECK(MessageLoopForUI::current());
249
250 // It can happen that the watcher gets canceled while tasks that call this
251 // function are still in flight, so abort if this situation is detected.
252 if (is_cancelled())
253 return;
254
255 if (fsevent_stream_)
256 DestroyEventStream();
257
258 base::mac::ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString(
259 NULL, target_.value().c_str(), kCFStringEncodingMacHFS));
260 base::mac::ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString(
261 NULL, target_.DirName().value().c_str(), kCFStringEncodingMacHFS));
262 CFStringRef paths_array[] = { cf_path.get(), cf_dir_path.get() };
263 base::mac::ScopedCFTypeRef<CFArrayRef> watched_paths(CFArrayCreate(
264 NULL, reinterpret_cast<const void**>(paths_array), arraysize(paths_array),
265 &kCFTypeArrayCallBacks));
266
267 FSEventStreamContext context;
268 context.version = 0;
269 context.info = this;
270 context.retain = NULL;
271 context.release = NULL;
272 context.copyDescription = NULL;
273
274 fsevent_stream_ = FSEventStreamCreate(NULL, &FSEventsCallback, &context,
275 watched_paths,
276 start_event,
277 kEventLatencySeconds,
278 kFSEventStreamCreateFlagWatchRoot);
279 FSEventStreamScheduleWithRunLoop(fsevent_stream_, CFRunLoopGetCurrent(),
280 kCFRunLoopDefaultMode);
281 if (!FSEventStreamStart(fsevent_stream_)) {
282 message_loop()->PostTask(FROM_HERE,
283 NewRunnableMethod(delegate_.get(),
284 &FilePathWatcher::Delegate::OnError));
285 }
286 }
287
288 void FilePathWatcherImpl::DestroyEventStream() {
289 FSEventStreamStop(fsevent_stream_);
290 FSEventStreamUnscheduleFromRunLoop(fsevent_stream_, CFRunLoopGetCurrent(),
291 kCFRunLoopDefaultMode);
292 FSEventStreamRelease(fsevent_stream_);
293 fsevent_stream_ = NULL;
294 }
295
296 } // namespace 328 } // namespace
297 329
298 FilePathWatcher::FilePathWatcher() { 330 FilePathWatcher::FilePathWatcher() {
299 impl_ = new FilePathWatcherImpl(); 331 impl_ = new FilePathWatcherImpl();
300 } 332 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698