| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "net/base/file_path_watcher_callback.h" |
| 6 |
| 7 #include "base/callback.h" |
| 8 #include "base/files/file_path_watcher.h" |
| 9 #include "base/logging.h" |
| 10 |
| 11 namespace net { |
| 12 |
| 13 // A FilePathWatcher::Delegate that forwards calls to FilePathWatcherCallback. |
| 14 class FilePathWatcherCallback::WatcherDelegate |
| 15 : public base::files::FilePathWatcher::Delegate { |
| 16 public: |
| 17 explicit WatcherDelegate(FilePathWatcherCallback* watcher) |
| 18 : watcher_(watcher) {} |
| 19 |
| 20 void Cancel() { |
| 21 watcher_ = NULL; |
| 22 } |
| 23 |
| 24 void OnFilePathChanged(const FilePath& path) OVERRIDE { |
| 25 if (watcher_) |
| 26 watcher_->OnFilePathChanged(); |
| 27 } |
| 28 |
| 29 void OnFilePathError(const FilePath& path) OVERRIDE { |
| 30 if (watcher_) |
| 31 watcher_->OnFilePathError(); |
| 32 } |
| 33 |
| 34 private: |
| 35 virtual ~WatcherDelegate() {} |
| 36 FilePathWatcherCallback* watcher_; |
| 37 }; |
| 38 |
| 39 FilePathWatcherCallback::FilePathWatcherCallback() { |
| 40 // No need to restrict the thread until the state is created in Watch. |
| 41 DetachFromThread(); |
| 42 } |
| 43 |
| 44 FilePathWatcherCallback::~FilePathWatcherCallback() { |
| 45 Cancel(); |
| 46 } |
| 47 |
| 48 void FilePathWatcherCallback::Cancel() { |
| 49 DCHECK(CalledOnValidThread()); |
| 50 if (delegate_) { |
| 51 delegate_->Cancel(); |
| 52 delegate_.release(); |
| 53 } |
| 54 watcher_.reset(NULL); |
| 55 // All state is gone so it's okay to detach from thread. |
| 56 DetachFromThread(); |
| 57 } |
| 58 |
| 59 bool FilePathWatcherCallback::Watch( |
| 60 const FilePath& path, |
| 61 const base::Callback<void(bool succeeded)>& callback) { |
| 62 DCHECK(CalledOnValidThread()); |
| 63 if (delegate_) |
| 64 delegate_->Cancel(); |
| 65 watcher_.reset(new base::files::FilePathWatcher()); |
| 66 delegate_ = new WatcherDelegate(this); |
| 67 if (watcher_->Watch(path, delegate_.get())) |
| 68 return true; |
| 69 |
| 70 Cancel(); |
| 71 return false; |
| 72 } |
| 73 |
| 74 void FilePathWatcherCallback::OnFilePathChanged() { |
| 75 DCHECK(CalledOnValidThread()); |
| 76 callback_.Run(true); |
| 77 } |
| 78 |
| 79 void FilePathWatcherCallback::OnFilePathError() { |
| 80 DCHECK(CalledOnValidThread()); |
| 81 base::Callback<void(bool succeeded)> callback = callback_; |
| 82 Cancel(); |
| 83 callback.Run(false); |
| 84 } |
| 85 |
| 86 } // namespace net |
| 87 |
| OLD | NEW |