OLD | NEW |
---|---|
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/memory/singleton.h" | |
15 #include "base/message_loop.h" | 14 #include "base/message_loop.h" |
16 #include "base/time.h" | 15 #include "base/message_loop_proxy.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. FSEvents also required having a CFRunLoop | |
32 // backing the thread that it was running on, that caused added complexity | |
33 // in the interfaces. | |
34 // The kqueue implementation will handle all of the | |
35 // items in the list above except for detecting modifications to files in a | |
36 // watched directory. It will detect the creation and deletion of files, just | |
37 // not the modification of files. It does however detect the attribute changes | |
38 // that the FSEvents impl would miss. | |
35 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate, | 39 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate, |
40 public MessageLoopForIO::Watcher, | |
36 public MessageLoop::DestructionObserver { | 41 public MessageLoop::DestructionObserver { |
37 public: | 42 public: |
38 FilePathWatcherImpl(); | 43 FilePathWatcherImpl() : kqueue_(-1) {} |
39 | 44 virtual ~FilePathWatcherImpl() {} |
40 // Called from the FSEvents callback whenever there is a change to the paths | 45 |
41 void OnFilePathChanged(); | 46 // MessageLoopForIO::Watcher overrides. |
42 | 47 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE; |
43 // (Re-)Initialize the event stream to start reporting events from | 48 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE; |
44 // |start_event|. | 49 |
45 void UpdateEventStream(FSEventStreamEventId start_event); | 50 // MessageLoop::DestructionObserver overrides. |
51 virtual void WillDestroyCurrentMessageLoop() OVERRIDE; | |
46 | 52 |
47 // FilePathWatcher::PlatformDelegate overrides. | 53 // FilePathWatcher::PlatformDelegate overrides. |
48 virtual bool Watch(const FilePath& path, | 54 virtual bool Watch(const FilePath& path, |
49 FilePathWatcher::Delegate* delegate, | 55 FilePathWatcher::Delegate* delegate) OVERRIDE; |
50 base::MessageLoopProxy* loop) OVERRIDE; | |
51 virtual void Cancel() OVERRIDE; | 56 virtual void Cancel() OVERRIDE; |
52 | 57 |
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: | 58 private: |
63 virtual ~FilePathWatcherImpl() {} | 59 class EventData { |
64 | 60 public: |
65 // Destroy the event stream. | 61 EventData(const FilePath& path, const FilePath::StringType& subdir) |
66 void DestroyEventStream(); | 62 : path_(path), subdir_(subdir) { } |
67 | 63 FilePath path_; // Full path to this item. |
68 // Start observing the destruction of the |run_loop_message_loop_| thread, | 64 FilePath::StringType subdir_; // Path to any sub item. |
69 // and watching the FSEventStream. | 65 }; |
70 void StartObserverAndEventStream(FSEventStreamEventId start_event); | 66 typedef std::vector<struct kevent> EventVector; |
71 | 67 |
72 // Cleans up and stops observing the |run_loop_message_loop_| thread. | 68 // Can only be called on |io_message_loop_|'s thread. |
73 void CancelOnMessageLoopThread() OVERRIDE; | 69 virtual void CancelOnMessageLoopThread() OVERRIDE; |
74 | 70 |
75 // Delegate to notify upon changes. | 71 // Fills |events| with one kevent per component in |path|. |
72 // Returns the number of valid events created where a valid event is | |
73 // defined as one that has a ident (file descriptor) field != -1. | |
74 static int EventsForPath(FilePath path, EventVector *events); | |
75 | |
76 // Release a kevent generated by EventsForPath. | |
77 static void ReleaseEvent(struct kevent& event); | |
78 | |
79 // Returns a file descriptor that will not block the system from deleting | |
80 // the file it references. | |
81 static int FileDescriptorForPath(const FilePath& path); | |
82 | |
83 // Closes |*fd| and sets |*fd| to -1. | |
84 static void CloseFileDescriptor(int* fd); | |
85 | |
86 // Returns true if the kevent values are error free. | |
87 static bool AreKeventValuesValid(struct kevent* events, int count); | |
88 | |
89 EventVector events_; | |
90 scoped_refptr<base::MessageLoopProxy> io_message_loop_; | |
91 MessageLoopForIO::FileDescriptorWatcher kqueue_watcher_; | |
76 scoped_refptr<FilePathWatcher::Delegate> delegate_; | 92 scoped_refptr<FilePathWatcher::Delegate> delegate_; |
77 | |
78 // Target path to watch (passed to delegate). | |
79 FilePath target_; | 93 FilePath target_; |
80 | 94 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 | 95 |
95 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); | 96 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); |
96 }; | 97 }; |
97 | 98 |
98 // The callback passed to FSEventStreamCreate(). | 99 void FilePathWatcherImpl::ReleaseEvent(struct kevent& event) { |
99 void FSEventsCallback(ConstFSEventStreamRef stream, | 100 CloseFileDescriptor(reinterpret_cast<int*>(&event.ident)); |
100 void* event_watcher, size_t num_events, | 101 EventData* entry = reinterpret_cast<EventData*>(event.udata); |
101 void* event_paths, const FSEventStreamEventFlags flags[], | 102 delete entry; |
102 const FSEventStreamEventId event_ids[]) { | 103 event.udata = NULL; |
103 FilePathWatcherImpl* watcher = | 104 } |
104 reinterpret_cast<FilePathWatcherImpl*>(event_watcher); | 105 |
105 DCHECK(watcher->run_loop_message_loop()->BelongsToCurrentThread()); | 106 int FilePathWatcherImpl::EventsForPath(FilePath path, EventVector* events) { |
106 | 107 DCHECK(MessageLoopForIO::current()); |
107 bool root_changed = false; | 108 // Make sure that we are working with a clean slate. |
108 FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream); | 109 DCHECK(events->empty()); |
109 for (size_t i = 0; i < num_events; i++) { | 110 |
110 if (flags[i] & kFSEventStreamEventFlagRootChanged) | 111 std::vector<FilePath::StringType> components; |
111 root_changed = true; | 112 path.GetComponents(&components); |
112 if (event_ids[i]) | 113 |
113 root_change_at = std::min(root_change_at, event_ids[i]); | 114 if (components.size() < 1) { |
114 } | 115 return -1; |
115 | 116 } |
116 // Reinitialize the event stream if we find changes to the root. This is | 117 |
117 // necessary since FSEvents doesn't report any events for the subtree after | 118 int last_existing_entry = 0; |
118 // the directory to be watched gets created. | 119 FilePath built_path; |
119 if (root_changed) { | 120 bool path_still_exists = true; |
120 // Resetting the event stream from within the callback fails (FSEvents spews | 121 for(std::vector<FilePath::StringType>::iterator i = components.begin(); |
121 // bad file descriptor errors), so post a task to do the reset. | 122 i != components.end(); ++i) { |
122 watcher->run_loop_message_loop()->PostTask(FROM_HERE, | 123 if (i == components.begin()) { |
123 NewRunnableMethod(watcher, &FilePathWatcherImpl::UpdateEventStream, | 124 built_path = FilePath(*i); |
124 root_change_at)); | 125 } else { |
125 } | 126 built_path = built_path.Append(*i); |
126 | 127 } |
127 watcher->OnFilePathChanged(); | 128 int fd = -1; |
128 } | 129 if (path_still_exists) { |
129 | 130 fd = FileDescriptorForPath(built_path); |
130 // FilePathWatcherImpl implementation: | 131 if (fd == -1) { |
131 | 132 path_still_exists = false; |
132 FilePathWatcherImpl::FilePathWatcherImpl() | 133 } else { |
133 : fsevent_stream_(NULL) { | 134 ++last_existing_entry; |
134 } | 135 } |
135 | 136 } |
136 void FilePathWatcherImpl::OnFilePathChanged() { | 137 FilePath::StringType subdir = (i != (components.end() - 1)) ? *(i + 1) : ""; |
137 // Switch to the CFRunLoop based thread if necessary, so we can tear down | 138 EventData* data = new EventData(built_path, subdir); |
138 // the event stream. | 139 struct kevent event; |
139 if (!message_loop()->BelongsToCurrentThread()) { | 140 EV_SET(&event, fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR | EV_RECEIPT), |
140 message_loop()->PostTask( | 141 (NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB | |
141 FROM_HERE, | 142 NOTE_RENAME | NOTE_REVOKE | NOTE_EXTEND), 0, data); |
142 NewRunnableMethod(this, &FilePathWatcherImpl::OnFilePathChanged)); | 143 events->push_back(event); |
144 } | |
145 return last_existing_entry; | |
146 } | |
147 | |
148 int FilePathWatcherImpl::FileDescriptorForPath(const FilePath& path) { | |
149 return HANDLE_EINTR(open(path.value().c_str(), O_EVTONLY | O_NONBLOCK)); | |
150 } | |
151 | |
152 void FilePathWatcherImpl::CloseFileDescriptor(int *fd) { | |
153 if (*fd == -1) { | |
143 return; | 154 return; |
144 } | 155 } |
145 | 156 |
146 DCHECK(message_loop()->BelongsToCurrentThread()); | 157 if (HANDLE_EINTR(close(*fd)) != 0) { |
147 DCHECK(!target_.empty()); | 158 PLOG(ERROR) << "close"; |
148 | 159 } |
149 base::PlatformFileInfo file_info; | 160 *fd = -1; |
150 bool file_exists = file_util::GetFileInfo(target_, &file_info); | 161 } |
151 if (file_exists && (last_modified_.is_null() || | 162 |
152 last_modified_ != file_info.last_modified)) { | 163 bool FilePathWatcherImpl::AreKeventValuesValid(struct kevent* events, |
153 last_modified_ = file_info.last_modified; | 164 int count) { |
154 first_notification_ = base::Time::Now(); | 165 if (count < 0) { |
166 PLOG(ERROR) << "kevent"; | |
167 return false; | |
168 } | |
169 bool valid = true; | |
170 for (int i = 0; i < count; ++i) { | |
171 if (events[i].flags & EV_ERROR && events[i].data) { | |
172 LOG(ERROR) << "Error: " << events[i].data; | |
Mark Mentovai
2011/03/30 18:20:39
Will these messages provide enough context to be a
dmac
2011/03/30 22:39:28
Done.
| |
173 valid = false; | |
174 } | |
175 } | |
176 return valid; | |
177 } | |
178 | |
179 void FilePathWatcherImpl::OnFileCanReadWithoutBlocking(int fd) { | |
180 DCHECK(MessageLoopForIO::current()); | |
181 CHECK_EQ(fd, kqueue_); | |
182 | |
Mark Mentovai
2011/03/30 18:20:39
CHECK(events_.size()) or bail if it’s zero.
dmac
2011/03/30 22:39:28
Done.
| |
183 // Request the file system update notifications that have occurred. | |
184 std::vector<struct kevent> updates(events_.size()); | |
185 struct timespec timeout = {0, 0}; | |
186 int count = HANDLE_EINTR(kevent(kqueue_, NULL, 0, &updates[0], updates.size(), | |
187 &timeout)); | |
188 if (!AreKeventValuesValid(&updates[0], count)) { | |
189 delegate_->OnError(); | |
190 Cancel(); | |
191 return; | |
192 } | |
193 | |
194 bool update_watches = false; | |
195 bool send_notification = false; | |
196 for (int i = 0; i < count; ++i) { | |
197 // Find our kevent record that matches the update notification. | |
198 EventVector::iterator event(events_.begin()); | |
199 for ( ; event != events_.end(); ++event) { | |
200 if (event->ident == updates[i].ident) | |
Mark Mentovai
2011/03/30 18:20:39
After your anti-Python pro-brace rant, you left th
dmac
2011/03/30 22:39:28
Always fun being caught being a hypocrite. :) Fixe
| |
201 break; | |
202 } | |
203 if (event == events_.end()) { | |
204 delegate_->OnError(); | |
205 Cancel(); | |
206 return; | |
207 } | |
208 | |
209 EventData* event_data = reinterpret_cast<EventData*>(event->udata); | |
210 | |
211 // If the subdir is empty, this is the last item on the path and is the | |
212 // target file. | |
213 bool target_file_affected = event_data->subdir_.empty(); | |
214 if (updates[i].fflags & NOTE_DELETE || updates[i].fflags & NOTE_REVOKE) { | |
215 // This is no longer accessible, so close the descriptor for it. | |
216 CloseFileDescriptor(reinterpret_cast<int*>(&event->ident)); | |
Mark Mentovai
2011/03/30 18:20:39
Do you need to remove it from the kqueue too? (Lin
dmac
2011/03/30 22:39:28
Added comments explaining why this isn't necessary
| |
217 update_watches = true; | |
218 } else if (updates[i].fflags & NOTE_RENAME) { | |
219 // A move operation has occurred. | |
220 target_file_affected = true; | |
221 for (; event != events_.end(); ++event) { | |
222 // Close all nodes from the event down. | |
223 CloseFileDescriptor(reinterpret_cast<int*>(&event->ident)); | |
224 } | |
225 update_watches = true; | |
226 } else if (updates[i].fflags & NOTE_WRITE) { | |
227 if (!target_file_affected) { | |
228 // In a directory this means a file has been added or deleted. | |
229 // Deletions are taken care of above so check for addition. | |
230 EventVector::iterator next_event = event + 1; | |
231 EventData* next_event_data = | |
232 reinterpret_cast<EventData*>(next_event->udata); | |
233 if (next_event->ident == static_cast<uintptr_t>(-1)) { | |
234 next_event->ident = FileDescriptorForPath(next_event_data->path_); | |
235 if (next_event->ident != static_cast<uintptr_t>(-1)) { | |
236 update_watches = true; | |
237 if (next_event_data->subdir_.empty()) { | |
238 target_file_affected = true; | |
239 } | |
240 } | |
241 } | |
242 } | |
243 } | |
244 send_notification |= target_file_affected; | |
245 } | |
246 | |
247 // Iterate over events adding kevents for items that exist to the kqueue. | |
248 // Then check to see if new components in the path have been created. | |
249 // Repeat until no new components in the path are detected. | |
250 // This is to get around races in directory creation in a watched path. | |
251 while (update_watches) { | |
252 size_t valid; | |
253 for (valid = 0; valid < events_.size(); ++valid) { | |
254 if (events_[valid].ident == static_cast<uintptr_t>(-1)) { | |
255 break; | |
256 } | |
257 } | |
258 std::vector<struct kevent> updates(valid); | |
Mark Mentovai
2011/03/30 18:20:39
If valid is 0, you need to stop right here.
dmac
2011/03/30 22:39:28
Done.
| |
259 count = HANDLE_EINTR(kevent(kqueue_, &events_[0], valid, &updates[0], valid, | |
Mark Mentovai
2011/03/30 18:20:39
The second argument to kevent is a list of changes
dmac
2011/03/30 22:39:28
Hopefully this has been dealt with adequately.
| |
260 NULL)); | |
261 if (!AreKeventValuesValid(&updates[0], count)) { | |
262 delegate_->OnError(); | |
263 Cancel(); | |
264 return; | |
265 } | |
266 update_watches = false; | |
267 for (; valid < events_.size(); ++valid) { | |
268 EventData* event_data = | |
269 reinterpret_cast<EventData*>(events_[valid].udata); | |
270 events_[valid].ident = FileDescriptorForPath(event_data->path_); | |
271 if (events_[valid].ident != static_cast<uintptr_t>(-1)) { | |
272 update_watches = true; | |
273 if (event_data->subdir_.empty()) { | |
274 send_notification = true; | |
275 } | |
276 } else { | |
277 break; | |
278 } | |
279 } | |
280 } | |
281 | |
282 if (send_notification) { | |
155 delegate_->OnFilePathChanged(target_); | 283 delegate_->OnFilePathChanged(target_); |
156 } else if (file_exists && !first_notification_.is_null()) { | 284 } |
157 // The target's last modification time is equal to what's on record. This | 285 } |
158 // means that either an unrelated event occurred, or the target changed | 286 |
159 // again (file modification times only have a resolution of 1s). Comparing | 287 void FilePathWatcherImpl::OnFileCanWriteWithoutBlocking(int fd) { |
160 // file modification times against the wall clock is not reliable to find | 288 NOTREACHED(); |
161 // out whether the change is recent, since this code might just run too | 289 } |
162 // late. Moreover, there's no guarantee that file modification time and wall | 290 |
163 // clock times come from the same source. | 291 void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() { |
164 // | 292 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 } | 293 } |
182 | 294 |
183 bool FilePathWatcherImpl::Watch(const FilePath& path, | 295 bool FilePathWatcherImpl::Watch(const FilePath& path, |
184 FilePathWatcher::Delegate* delegate, | 296 FilePathWatcher::Delegate* delegate) { |
185 base::MessageLoopProxy* loop) { | |
186 DCHECK(target_.value().empty()); | |
187 DCHECK(MessageLoopForIO::current()); | 297 DCHECK(MessageLoopForIO::current()); |
188 | 298 DCHECK(target_.value().empty()); // Can only watch one path. |
189 set_message_loop(base::MessageLoopProxy::CreateForCurrentThread()); | 299 DCHECK(delegate); |
190 run_loop_message_loop_ = loop; | 300 DCHECK_EQ(kqueue_, -1); |
301 | |
302 delegate_ = delegate; | |
191 target_ = path; | 303 target_ = path; |
192 delegate_ = delegate; | 304 |
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); | 305 MessageLoop::current()->AddDestructionObserver(this); |
213 UpdateEventStream(start_event); | 306 io_message_loop_ = base::MessageLoopProxy::CreateForCurrentThread(); |
307 | |
308 kqueue_ = kqueue(); | |
309 if (kqueue_ == -1) { | |
310 PLOG(ERROR) << "kqueue"; | |
311 return false; | |
312 } | |
313 | |
314 int last_entry = EventsForPath(target_, &events_); | |
Mark Mentovai
2011/03/30 18:20:39
CHECK(last_entry) or bail if it’s zero.
dmac
2011/03/30 22:39:28
Done.
| |
315 std::vector<struct kevent> responses(last_entry); | |
316 | |
317 int count = HANDLE_EINTR(kevent(kqueue_, &events_[0], last_entry, | |
318 &responses[0], last_entry, NULL)); | |
319 if (!AreKeventValuesValid(&responses[0], count)) { | |
320 // Calling Cancel() here to close any file descriptors that were opened. | |
321 // This would happen in the destructor anyways, but FilePathWatchers tend to | |
322 // be long lived, and if an error has occurred, there is no reason to waste | |
323 // the file descriptors. | |
324 Cancel(); | |
325 return false; | |
326 } | |
327 | |
328 return MessageLoopForIO::current()->WatchFileDescriptor( | |
329 kqueue_, true, MessageLoopForIO::WATCH_READ, &kqueue_watcher_, this); | |
214 } | 330 } |
215 | 331 |
216 void FilePathWatcherImpl::Cancel() { | 332 void FilePathWatcherImpl::Cancel() { |
217 if (!run_loop_message_loop().get()) { | 333 base::MessageLoopProxy* proxy = io_message_loop_.get(); |
218 // Watch was never called, so exit. | 334 if (!proxy) { |
219 set_cancelled(); | 335 set_cancelled(); |
220 return; | 336 return; |
221 } | 337 } |
222 | 338 if (!proxy->BelongsToCurrentThread()) { |
223 // Switch to the CFRunLoop based thread if necessary, so we can tear down | 339 proxy->PostTask(FROM_HERE, |
224 // the event stream. | 340 NewRunnableMethod(this, &FilePathWatcherImpl::Cancel)); |
225 if (!run_loop_message_loop()->BelongsToCurrentThread()) { | 341 return; |
226 run_loop_message_loop()->PostTask(FROM_HERE, | 342 } |
227 new FilePathWatcher::CancelTask(this)); | 343 CancelOnMessageLoopThread(); |
228 } else { | |
229 CancelOnMessageLoopThread(); | |
230 } | |
231 } | 344 } |
232 | 345 |
233 void FilePathWatcherImpl::CancelOnMessageLoopThread() { | 346 void FilePathWatcherImpl::CancelOnMessageLoopThread() { |
234 set_cancelled(); | 347 DCHECK(MessageLoopForIO::current()); |
235 if (fsevent_stream_) { | 348 if (!is_cancelled()) { |
236 DestroyEventStream(); | 349 set_cancelled(); |
350 kqueue_watcher_.StopWatchingFileDescriptor(); | |
351 CloseFileDescriptor(&kqueue_); | |
352 std::for_each(events_.begin(), events_.end(), ReleaseEvent); | |
353 events_.clear(); | |
354 io_message_loop_.release(); | |
237 MessageLoop::current()->RemoveDestructionObserver(this); | 355 MessageLoop::current()->RemoveDestructionObserver(this); |
238 delegate_ = NULL; | 356 delegate_ = NULL; |
239 } | 357 } |
240 } | 358 } |
241 | 359 |
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 | 360 } // namespace |
297 | 361 |
298 FilePathWatcher::FilePathWatcher() { | 362 FilePathWatcher::FilePathWatcher() { |
299 impl_ = new FilePathWatcherImpl(); | 363 impl_ = new FilePathWatcherImpl(); |
300 } | 364 } |
OLD | NEW |