summaryrefslogtreecommitdiffstats
path: root/chrome
diff options
context:
space:
mode:
authordmaclach@chromium.org <dmaclach@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2011-03-18 04:11:49 +0000
committerdmaclach@chromium.org <dmaclach@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2011-03-18 04:11:49 +0000
commitb8ca91f78cf0ba682787ec1c4605021b304f1305 (patch)
treefa497cdf8396758fc777387c428ad1d9772cb4cd /chrome
parent0a7031a43ea2b15e606882e9c5e3da58f565b701 (diff)
downloadchromium_src-b8ca91f78cf0ba682787ec1c4605021b304f1305.zip
chromium_src-b8ca91f78cf0ba682787ec1c4605021b304f1305.tar.gz
chromium_src-b8ca91f78cf0ba682787ec1c4605021b304f1305.tar.bz2
Move FilePathWatcher class from chrome/browser/... to content/common...
The service process needs FilePathWatcher, and with this change I got rid of the dependency on BrowserThread which allows it to be moved to common/... I also tried my hand at a kqueue impl on the Mac, but failed. See http://code.google.com/p/chromium/issues/detail?id=54822#c13 for details. BUG=74983 TEST=BUILD Review URL: http://codereview.chromium.org/6670081 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@78664 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome')
-rw-r--r--chrome/browser/file_path_watcher/file_path_watcher.cc19
-rw-r--r--chrome/browser/file_path_watcher/file_path_watcher.h68
-rw-r--r--chrome/browser/file_path_watcher/file_path_watcher_browsertest.cc454
-rw-r--r--chrome/browser/file_path_watcher/file_path_watcher_inotify.cc413
-rw-r--r--chrome/browser/file_path_watcher/file_path_watcher_mac.cc234
-rw-r--r--chrome/browser/file_path_watcher/file_path_watcher_stub.cc19
-rw-r--r--chrome/browser/file_path_watcher/file_path_watcher_win.cc244
-rw-r--r--chrome/browser/policy/file_based_policy_loader.cc10
-rw-r--r--chrome/browser/policy/file_based_policy_loader.h4
-rw-r--r--chrome/browser/user_style_sheet_watcher.cc6
-rw-r--r--chrome/browser/user_style_sheet_watcher.h2
-rw-r--r--chrome/browser/user_style_sheet_watcher_unittest.cc23
-rw-r--r--chrome/chrome_browser.gypi9
-rw-r--r--chrome/chrome_tests.gypi2
14 files changed, 31 insertions, 1476 deletions
diff --git a/chrome/browser/file_path_watcher/file_path_watcher.cc b/chrome/browser/file_path_watcher/file_path_watcher.cc
deleted file mode 100644
index c516172..0000000
--- a/chrome/browser/file_path_watcher/file_path_watcher.cc
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright (c) 2010 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.
-
-// Cross platform methods for FilePathWatcher. See the various platform
-// specific implementation files, too.
-
-#include "chrome/browser/file_path_watcher/file_path_watcher.h"
-
-FilePathWatcher::~FilePathWatcher() {
- impl_->Cancel();
-}
-
-bool FilePathWatcher::Watch(const FilePath& path,
- Delegate* delegate) {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
- DCHECK(path.IsAbsolute());
- return impl_->Watch(path, delegate);
-}
diff --git a/chrome/browser/file_path_watcher/file_path_watcher.h b/chrome/browser/file_path_watcher/file_path_watcher.h
deleted file mode 100644
index 530962e..0000000
--- a/chrome/browser/file_path_watcher/file_path_watcher.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright (c) 2010 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.
-
-// This module provides a way to monitor a file or directory for changes.
-
-#ifndef CHROME_BROWSER_FILE_PATH_WATCHER_FILE_PATH_WATCHER_H_
-#define CHROME_BROWSER_FILE_PATH_WATCHER_FILE_PATH_WATCHER_H_
-#pragma once
-
-#include "base/basictypes.h"
-#include "base/file_path.h"
-#include "base/ref_counted.h"
-#include "content/browser/browser_thread.h"
-
-// This class lets you register interest in changes on a FilePath.
-// The delegate will get called whenever the file or directory referenced by the
-// FilePath is changed, including created or deleted. Due to limitations in the
-// underlying OS APIs, spurious notifications might occur that don't relate to
-// an actual change to the watch target.
-class FilePathWatcher {
- public:
- // Declares the callback client code implements to receive notifications. Note
- // that implementations of this interface should not keep a reference to the
- // corresponding FileWatcher object to prevent a reference cycle.
- class Delegate : public base::RefCountedThreadSafe<Delegate> {
- public:
- virtual ~Delegate() {}
- virtual void OnFilePathChanged(const FilePath& path) = 0;
- // Called when platform specific code detected an error. The watcher will
- // not call OnFilePathChanged for future changes.
- virtual void OnError() {}
- };
-
- FilePathWatcher();
- ~FilePathWatcher();
-
- // Register interest in any changes on |path|. OnPathChanged will be called
- // back for each change. Returns true on success.
- bool Watch(const FilePath& path, Delegate* delegate) WARN_UNUSED_RESULT;
-
- // Used internally to encapsulate different members on different platforms.
- class PlatformDelegate
- : public base::RefCountedThreadSafe<PlatformDelegate,
- BrowserThread::DeleteOnFileThread> {
- public:
- // Start watching for the given |path| and notify |delegate| about changes.
- virtual bool Watch(const FilePath& path, Delegate* delegate)
- WARN_UNUSED_RESULT = 0;
-
- // Stop watching. This is called from FilePathWatcher's dtor in order to
- // allow to shut down properly while the object is still alive.
- virtual void Cancel() {}
-
- protected:
- friend struct BrowserThread::DeleteOnThread<BrowserThread::FILE>;
- friend class DeleteTask<PlatformDelegate>;
-
- virtual ~PlatformDelegate() {}
- };
-
- private:
- scoped_refptr<PlatformDelegate> impl_;
-
- DISALLOW_COPY_AND_ASSIGN(FilePathWatcher);
-};
-
-#endif // CHROME_BROWSER_FILE_PATH_WATCHER_FILE_PATH_WATCHER_H_
diff --git a/chrome/browser/file_path_watcher/file_path_watcher_browsertest.cc b/chrome/browser/file_path_watcher/file_path_watcher_browsertest.cc
deleted file mode 100644
index b733a9a..0000000
--- a/chrome/browser/file_path_watcher/file_path_watcher_browsertest.cc
+++ /dev/null
@@ -1,454 +0,0 @@
-// Copyright (c) 2010 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 "chrome/browser/file_path_watcher/file_path_watcher.h"
-
-#include <set>
-
-#include "base/basictypes.h"
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "base/message_loop.h"
-#include "base/message_loop_proxy.h"
-#include "base/path_service.h"
-#include "base/scoped_temp_dir.h"
-#include "base/string_util.h"
-#include "base/stl_util-inl.h"
-#include "base/synchronization/waitable_event.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-#if defined(OS_MACOSX)
-// TODO(mnissler): There are flakes on Mac (http://crbug.com/54822) at least for
-// FilePathWatcherTest.MultipleWatchersSingleFile.
-#define MAYBE(name) FLAKY_ ## name
-#else
-#define MAYBE(name) name
-#endif
-
-namespace {
-
-class TestDelegate;
-
-// Aggregates notifications from the test delegates and breaks the message loop
-// the test thread is waiting on once they all came in.
-class NotificationCollector
- : public base::RefCountedThreadSafe<NotificationCollector> {
- public:
- NotificationCollector()
- : loop_(base::MessageLoopProxy::CreateForCurrentThread()) {}
-
- // Called from the file thread by the delegates.
- void OnChange(TestDelegate* delegate) {
- loop_->PostTask(FROM_HERE,
- NewRunnableMethod(this,
- &NotificationCollector::RecordChange,
- make_scoped_refptr(delegate)));
- }
-
- void Register(TestDelegate* delegate) {
- delegates_.insert(delegate);
- }
-
- void Reset() {
- signaled_.clear();
- }
-
- private:
- void RecordChange(TestDelegate* delegate) {
- ASSERT_TRUE(loop_->BelongsToCurrentThread());
- ASSERT_TRUE(delegates_.count(delegate));
- signaled_.insert(delegate);
-
- // Check whether all delegates have been signaled.
- if (signaled_ == delegates_)
- loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
- }
-
- // Set of registered delegates.
- std::set<TestDelegate*> delegates_;
-
- // Set of signaled delegates.
- std::set<TestDelegate*> signaled_;
-
- // The loop we should break after all delegates signaled.
- scoped_refptr<base::MessageLoopProxy> loop_;
-};
-
-// A mock FilePathWatcher::Delegate for testing. I'd rather use gmock, but it's
-// not thread safe for setting expectations, so the test code couldn't safely
-// reset expectations while the file watcher is running. In order to allow this,
-// we keep simple thread safe status flags in TestDelegate.
-class TestDelegate : public FilePathWatcher::Delegate {
- public:
- // The message loop specified by |loop| will be quit if a notification is
- // received while the delegate is |armed_|. Note that the testing code must
- // guarantee |loop| outlives the file thread on which OnFilePathChanged runs.
- explicit TestDelegate(NotificationCollector* collector)
- : collector_(collector) {
- collector_->Register(this);
- }
-
- virtual void OnFilePathChanged(const FilePath&) {
- collector_->OnChange(this);
- }
-
- private:
- scoped_refptr<NotificationCollector> collector_;
-
- DISALLOW_COPY_AND_ASSIGN(TestDelegate);
-};
-
-// A helper class for setting up watches on the file thread.
-class SetupWatchTask : public Task {
- public:
- SetupWatchTask(const FilePath& target,
- FilePathWatcher* watcher,
- FilePathWatcher::Delegate* delegate,
- bool* result,
- base::WaitableEvent* completion)
- : target_(target),
- watcher_(watcher),
- delegate_(delegate),
- result_(result),
- completion_(completion) {}
-
- void Run() {
- *result_ = watcher_->Watch(target_, delegate_);
- completion_->Signal();
- }
-
- private:
- const FilePath target_;
- FilePathWatcher* watcher_;
- FilePathWatcher::Delegate* delegate_;
- bool* result_;
- base::WaitableEvent* completion_;
-
- DISALLOW_COPY_AND_ASSIGN(SetupWatchTask);
-};
-
-class FilePathWatcherTest : public testing::Test {
- public:
- // Implementation of FilePathWatcher on Mac requires UI loop.
- FilePathWatcherTest()
- : loop_(MessageLoop::TYPE_UI),
- ui_thread_(BrowserThread::UI, &loop_) {
- }
-
- protected:
- virtual void SetUp() {
- // Create a separate file thread in order to test proper thread usage.
- file_thread_.reset(new BrowserThread(BrowserThread::FILE));
- file_thread_->Start();
- temp_dir_.reset(new ScopedTempDir);
- ASSERT_TRUE(temp_dir_->CreateUniqueTempDir());
- collector_ = new NotificationCollector();
- }
-
- virtual void TearDown() {
- loop_.RunAllPending();
- file_thread_.reset();
- }
-
- FilePath test_file() {
- return temp_dir_->path().AppendASCII("FilePathWatcherTest");
- }
-
- // Write |content| to |file|. Returns true on success.
- bool WriteFile(const FilePath& file, const std::string& content) {
- int write_size = file_util::WriteFile(file, content.c_str(),
- content.length());
- return write_size == static_cast<int>(content.length());
- }
-
- void SetupWatch(const FilePath& target,
- FilePathWatcher* watcher,
- FilePathWatcher::Delegate* delegate) {
- base::WaitableEvent completion(false, false);
- bool result;
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- new SetupWatchTask(target, watcher, delegate, &result, &completion));
- completion.Wait();
- ASSERT_TRUE(result);
- }
-
- void WaitForEvents() {
- collector_->Reset();
- loop_.Run();
- }
-
- NotificationCollector* collector() { return collector_.get(); }
-
- MessageLoop loop_;
- BrowserThread ui_thread_;
- scoped_ptr<BrowserThread> file_thread_;
- scoped_ptr<ScopedTempDir> temp_dir_;
- scoped_refptr<NotificationCollector> collector_;
-};
-
-// Basic test: Create the file and verify that we notice.
-TEST_F(FilePathWatcherTest, MAYBE(NewFile)) {
- FilePathWatcher watcher;
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- SetupWatch(test_file(), &watcher, delegate.get());
-
- ASSERT_TRUE(WriteFile(test_file(), "content"));
- WaitForEvents();
-}
-
-// Verify that modifying the file is caught.
-TEST_F(FilePathWatcherTest, MAYBE(ModifiedFile)) {
- ASSERT_TRUE(WriteFile(test_file(), "content"));
-
- FilePathWatcher watcher;
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- SetupWatch(test_file(), &watcher, delegate.get());
-
- // Now make sure we get notified if the file is modified.
- ASSERT_TRUE(WriteFile(test_file(), "new content"));
- WaitForEvents();
-}
-
-// Verify that moving the file into place is caught.
-TEST_F(FilePathWatcherTest, MAYBE(MovedFile)) {
- FilePath source_file(temp_dir_->path().AppendASCII("source"));
- ASSERT_TRUE(WriteFile(source_file, "content"));
-
- FilePathWatcher watcher;
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- SetupWatch(test_file(), &watcher, delegate.get());
-
- // Now make sure we get notified if the file is modified.
- ASSERT_TRUE(file_util::Move(source_file, test_file()));
- WaitForEvents();
-}
-
-TEST_F(FilePathWatcherTest, MAYBE(DeletedFile)) {
- ASSERT_TRUE(WriteFile(test_file(), "content"));
-
- FilePathWatcher watcher;
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- SetupWatch(test_file(), &watcher, delegate.get());
-
- // Now make sure we get notified if the file is deleted.
- file_util::Delete(test_file(), false);
- WaitForEvents();
-}
-
-// Used by the DeleteDuringNotify test below.
-// Deletes the FilePathWatcher when it's notified.
-class Deleter : public FilePathWatcher::Delegate {
- public:
- Deleter(FilePathWatcher* watcher, MessageLoop* loop)
- : watcher_(watcher),
- loop_(loop) {
- }
-
- virtual void OnFilePathChanged(const FilePath& path) {
- watcher_.reset(NULL);
- loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
- }
-
- scoped_ptr<FilePathWatcher> watcher_;
- MessageLoop* loop_;
-};
-
-// Verify that deleting a watcher during the callback doesn't crash.
-TEST_F(FilePathWatcherTest, DeleteDuringNotify) {
- FilePathWatcher* watcher = new FilePathWatcher;
- // Takes ownership of watcher.
- scoped_refptr<Deleter> deleter(new Deleter(watcher, &loop_));
- SetupWatch(test_file(), watcher, deleter.get());
-
- ASSERT_TRUE(WriteFile(test_file(), "content"));
- WaitForEvents();
-
- // We win if we haven't crashed yet.
- // Might as well double-check it got deleted, too.
- ASSERT_TRUE(deleter->watcher_.get() == NULL);
-}
-
-// Verify that deleting the watcher works even if there is a pending
-// notification.
-TEST_F(FilePathWatcherTest, DestroyWithPendingNotification) {
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- FilePathWatcher* watcher = new FilePathWatcher;
- SetupWatch(test_file(), watcher, delegate.get());
- ASSERT_TRUE(WriteFile(test_file(), "content"));
- BrowserThread::DeleteSoon(BrowserThread::FILE, FROM_HERE, watcher);
-}
-
-TEST_F(FilePathWatcherTest, MAYBE(MultipleWatchersSingleFile)) {
- FilePathWatcher watcher1, watcher2;
- scoped_refptr<TestDelegate> delegate1(new TestDelegate(collector()));
- scoped_refptr<TestDelegate> delegate2(new TestDelegate(collector()));
- SetupWatch(test_file(), &watcher1, delegate1.get());
- SetupWatch(test_file(), &watcher2, delegate2.get());
-
- ASSERT_TRUE(WriteFile(test_file(), "content"));
- WaitForEvents();
-}
-
-// Verify that watching a file whose parent directory doesn't exist yet works if
-// the directory and file are created eventually.
-TEST_F(FilePathWatcherTest, NonExistentDirectory) {
- FilePathWatcher watcher;
- FilePath dir(temp_dir_->path().AppendASCII("dir"));
- FilePath file(dir.AppendASCII("file"));
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- SetupWatch(file, &watcher, delegate.get());
-
- ASSERT_TRUE(file_util::CreateDirectory(dir));
-
- ASSERT_TRUE(WriteFile(file, "content"));
- VLOG(1) << "Waiting for file creation";
- WaitForEvents();
-
- ASSERT_TRUE(WriteFile(file, "content v2"));
- VLOG(1) << "Waiting for file change";
- WaitForEvents();
-
- ASSERT_TRUE(file_util::Delete(file, false));
- VLOG(1) << "Waiting for file deletion";
- WaitForEvents();
-}
-
-// Exercises watch reconfiguration for the case that directories on the path
-// are rapidly created.
-TEST_F(FilePathWatcherTest, DirectoryChain) {
- FilePath path(temp_dir_->path());
- std::vector<std::string> dir_names;
- for (int i = 0; i < 20; i++) {
- std::string dir(StringPrintf("d%d", i));
- dir_names.push_back(dir);
- path = path.AppendASCII(dir);
- }
-
- FilePathWatcher watcher;
- FilePath file(path.AppendASCII("file"));
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- SetupWatch(file, &watcher, delegate.get());
-
- FilePath sub_path(temp_dir_->path());
- for (std::vector<std::string>::const_iterator d(dir_names.begin());
- d != dir_names.end(); ++d) {
- sub_path = sub_path.AppendASCII(*d);
- ASSERT_TRUE(file_util::CreateDirectory(sub_path));
- }
- ASSERT_TRUE(WriteFile(file, "content"));
- VLOG(1) << "Waiting for file creation";
- WaitForEvents();
-
- ASSERT_TRUE(WriteFile(file, "content v2"));
- VLOG(1) << "Waiting for file modification";
- WaitForEvents();
-}
-
-TEST_F(FilePathWatcherTest, DisappearingDirectory) {
- FilePathWatcher watcher;
- FilePath dir(temp_dir_->path().AppendASCII("dir"));
- FilePath file(dir.AppendASCII("file"));
- ASSERT_TRUE(file_util::CreateDirectory(dir));
- ASSERT_TRUE(WriteFile(file, "content"));
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- SetupWatch(file, &watcher, delegate.get());
-
- ASSERT_TRUE(file_util::Delete(dir, true));
- WaitForEvents();
-}
-
-// Tests that a file that is deleted and reappears is tracked correctly.
-TEST_F(FilePathWatcherTest, DeleteAndRecreate) {
- ASSERT_TRUE(WriteFile(test_file(), "content"));
- FilePathWatcher watcher;
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- SetupWatch(test_file(), &watcher, delegate.get());
-
- ASSERT_TRUE(file_util::Delete(test_file(), false));
- VLOG(1) << "Waiting for file deletion";
- WaitForEvents();
-
- ASSERT_TRUE(WriteFile(test_file(), "content"));
- VLOG(1) << "Waiting for file creation";
- WaitForEvents();
-}
-
-TEST_F(FilePathWatcherTest, WatchDirectory) {
- FilePathWatcher watcher;
- FilePath dir(temp_dir_->path().AppendASCII("dir"));
- FilePath file1(dir.AppendASCII("file1"));
- FilePath file2(dir.AppendASCII("file2"));
- scoped_refptr<TestDelegate> delegate(new TestDelegate(collector()));
- SetupWatch(dir, &watcher, delegate.get());
-
- ASSERT_TRUE(file_util::CreateDirectory(dir));
- VLOG(1) << "Waiting for directory creation";
- WaitForEvents();
-
- ASSERT_TRUE(WriteFile(file1, "content"));
- VLOG(1) << "Waiting for file1 creation";
- WaitForEvents();
-
- ASSERT_TRUE(WriteFile(file1, "content v2"));
- VLOG(1) << "Waiting for file1 modification";
- WaitForEvents();
-
- ASSERT_TRUE(file_util::Delete(file1, false));
- VLOG(1) << "Waiting for file1 deletion";
- WaitForEvents();
-
- ASSERT_TRUE(WriteFile(file2, "content"));
- VLOG(1) << "Waiting for file2 creation";
- WaitForEvents();
-}
-
-TEST_F(FilePathWatcherTest, MoveParent) {
- FilePathWatcher file_watcher;
- FilePathWatcher subdir_watcher;
- FilePath dir(temp_dir_->path().AppendASCII("dir"));
- FilePath dest(temp_dir_->path().AppendASCII("dest"));
- FilePath subdir(dir.AppendASCII("subdir"));
- FilePath file(subdir.AppendASCII("file"));
- scoped_refptr<TestDelegate> file_delegate(new TestDelegate(collector()));
- SetupWatch(file, &file_watcher, file_delegate.get());
- scoped_refptr<TestDelegate> subdir_delegate(new TestDelegate(collector()));
- SetupWatch(subdir, &subdir_watcher, subdir_delegate.get());
-
- // Setup a directory hierarchy.
- ASSERT_TRUE(file_util::CreateDirectory(subdir));
- ASSERT_TRUE(WriteFile(file, "content"));
- VLOG(1) << "Waiting for file creation";
- WaitForEvents();
-
- // Move the parent directory.
- file_util::Move(dir, dest);
- VLOG(1) << "Waiting for directory move";
- WaitForEvents();
-}
-
-TEST_F(FilePathWatcherTest, MoveChild) {
- FilePathWatcher file_watcher;
- FilePathWatcher subdir_watcher;
- FilePath source_dir(temp_dir_->path().AppendASCII("source"));
- FilePath source_subdir(source_dir.AppendASCII("subdir"));
- FilePath source_file(source_subdir.AppendASCII("file"));
- FilePath dest_dir(temp_dir_->path().AppendASCII("dest"));
- FilePath dest_subdir(dest_dir.AppendASCII("subdir"));
- FilePath dest_file(dest_subdir.AppendASCII("file"));
-
- // Setup a directory hierarchy.
- ASSERT_TRUE(file_util::CreateDirectory(source_subdir));
- ASSERT_TRUE(WriteFile(source_file, "content"));
-
- scoped_refptr<TestDelegate> file_delegate(new TestDelegate(collector()));
- SetupWatch(dest_file, &file_watcher, file_delegate.get());
- scoped_refptr<TestDelegate> subdir_delegate(new TestDelegate(collector()));
- SetupWatch(dest_subdir, &subdir_watcher, subdir_delegate.get());
-
- // Move the directory into place, s.t. the watched file appears.
- ASSERT_TRUE(file_util::Move(source_dir, dest_dir));
- WaitForEvents();
-}
-
-} // namespace
diff --git a/chrome/browser/file_path_watcher/file_path_watcher_inotify.cc b/chrome/browser/file_path_watcher/file_path_watcher_inotify.cc
deleted file mode 100644
index f067481..0000000
--- a/chrome/browser/file_path_watcher/file_path_watcher_inotify.cc
+++ /dev/null
@@ -1,413 +0,0 @@
-// Copyright (c) 2010 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 "chrome/browser/file_path_watcher/file_path_watcher.h"
-
-#include <errno.h>
-#include <string.h>
-#include <sys/inotify.h>
-#include <sys/ioctl.h>
-#include <sys/select.h>
-#include <unistd.h>
-
-#include <algorithm>
-#include <set>
-#include <utility>
-#include <vector>
-
-#include "base/eintr_wrapper.h"
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "base/hash_tables.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/message_loop.h"
-#include "base/scoped_ptr.h"
-#include "base/synchronization/lock.h"
-#include "base/task.h"
-#include "base/threading/thread.h"
-
-namespace {
-
-class FilePathWatcherImpl;
-
-// Singleton to manage all inotify watches.
-// TODO(tony): It would be nice if this wasn't a singleton.
-// http://crbug.com/38174
-class InotifyReader {
- public:
- typedef int Watch; // Watch descriptor used by AddWatch and RemoveWatch.
- static const Watch kInvalidWatch = -1;
-
- // Watch directory |path| for changes. |watcher| will be notified on each
- // change. Returns kInvalidWatch on failure.
- Watch AddWatch(const FilePath& path, FilePathWatcherImpl* watcher);
-
- // Remove |watch|. Returns true on success.
- bool RemoveWatch(Watch watch, FilePathWatcherImpl* watcher);
-
- // Callback for InotifyReaderTask.
- void OnInotifyEvent(const inotify_event* event);
-
- private:
- friend struct ::base::DefaultLazyInstanceTraits<InotifyReader>;
-
- typedef std::set<FilePathWatcherImpl*> WatcherSet;
-
- InotifyReader();
- ~InotifyReader();
-
- // We keep track of which delegates want to be notified on which watches.
- base::hash_map<Watch, WatcherSet> watchers_;
-
- // Lock to protect watchers_.
- base::Lock lock_;
-
- // Separate thread on which we run blocking read for inotify events.
- base::Thread thread_;
-
- // File descriptor returned by inotify_init.
- const int inotify_fd_;
-
- // Use self-pipe trick to unblock select during shutdown.
- int shutdown_pipe_[2];
-
- // Flag set to true when startup was successful.
- bool valid_;
-
- DISALLOW_COPY_AND_ASSIGN(InotifyReader);
-};
-
-class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate {
- public:
- FilePathWatcherImpl();
-
- // Called for each event coming from the watch. |fired_watch| identifies the
- // watch that fired, |child| indicates what has changed, and is relative to
- // the currently watched path for |fired_watch|. The flag |created| is true if
- // the object appears, and |is_directory| is set when the event refers to a
- // directory.
- void OnFilePathChanged(InotifyReader::Watch fired_watch,
- const FilePath::StringType& child,
- bool created,
- bool is_directory);
-
- // Start watching |path| for changes and notify |delegate| on each change.
- // Returns true if watch for |path| has been added successfully.
- virtual bool Watch(const FilePath& path, FilePathWatcher::Delegate* delegate);
-
- // Cancel the watch. This unregisters the instance with InotifyReader.
- virtual void Cancel();
-
- private:
- virtual ~FilePathWatcherImpl() {}
-
- // Inotify watches are installed for all directory components of |target_|. A
- // WatchEntry instance holds the watch descriptor for a component and the
- // subdirectory for that identifies the next component.
- struct WatchEntry {
- WatchEntry(InotifyReader::Watch watch, const FilePath::StringType& subdir)
- : watch_(watch),
- subdir_(subdir) {}
-
- InotifyReader::Watch watch_;
- FilePath::StringType subdir_;
- };
- typedef std::vector<WatchEntry> WatchVector;
-
- // Reconfigure to watch for the most specific parent directory of |target_|
- // that exists. Updates |watched_path_|. Returns true on success.
- bool UpdateWatches() WARN_UNUSED_RESULT;
-
- // Delegate to notify upon changes.
- scoped_refptr<FilePathWatcher::Delegate> delegate_;
-
- // The file or directory we're supposed to watch.
- FilePath target_;
-
- // The vector of watches and next component names for all path components,
- // starting at the root directory. The last entry corresponds to the watch for
- // |target_| and always stores an empty next component name in |subdir_|.
- WatchVector watches_;
-
- DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
-};
-
-class InotifyReaderTask : public Task {
- public:
- InotifyReaderTask(InotifyReader* reader, int inotify_fd, int shutdown_fd)
- : reader_(reader),
- inotify_fd_(inotify_fd),
- shutdown_fd_(shutdown_fd) {
- }
-
- virtual void Run() {
- while (true) {
- fd_set rfds;
- FD_ZERO(&rfds);
- FD_SET(inotify_fd_, &rfds);
- FD_SET(shutdown_fd_, &rfds);
-
- // Wait until some inotify events are available.
- int select_result =
- HANDLE_EINTR(select(std::max(inotify_fd_, shutdown_fd_) + 1,
- &rfds, NULL, NULL, NULL));
- if (select_result < 0) {
- DPLOG(WARNING) << "select failed";
- return;
- }
-
- if (FD_ISSET(shutdown_fd_, &rfds))
- return;
-
- // Adjust buffer size to current event queue size.
- int buffer_size;
- int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd_, FIONREAD,
- &buffer_size));
-
- if (ioctl_result != 0) {
- DPLOG(WARNING) << "ioctl failed";
- return;
- }
-
- std::vector<char> buffer(buffer_size);
-
- ssize_t bytes_read = HANDLE_EINTR(read(inotify_fd_, &buffer[0],
- buffer_size));
-
- if (bytes_read < 0) {
- DPLOG(WARNING) << "read from inotify fd failed";
- return;
- }
-
- ssize_t i = 0;
- while (i < bytes_read) {
- inotify_event* event = reinterpret_cast<inotify_event*>(&buffer[i]);
- size_t event_size = sizeof(inotify_event) + event->len;
- DCHECK(i + event_size <= static_cast<size_t>(bytes_read));
- reader_->OnInotifyEvent(event);
- i += event_size;
- }
- }
- }
-
- private:
- InotifyReader* reader_;
- int inotify_fd_;
- int shutdown_fd_;
-
- DISALLOW_COPY_AND_ASSIGN(InotifyReaderTask);
-};
-
-static base::LazyInstance<InotifyReader> g_inotify_reader(
- base::LINKER_INITIALIZED);
-
-InotifyReader::InotifyReader()
- : thread_("inotify_reader"),
- inotify_fd_(inotify_init()),
- valid_(false) {
- shutdown_pipe_[0] = -1;
- shutdown_pipe_[1] = -1;
- if (inotify_fd_ >= 0 && pipe(shutdown_pipe_) == 0 && thread_.Start()) {
- thread_.message_loop()->PostTask(
- FROM_HERE, new InotifyReaderTask(this, inotify_fd_, shutdown_pipe_[0]));
- valid_ = true;
- }
-}
-
-InotifyReader::~InotifyReader() {
- if (valid_) {
- // Write to the self-pipe so that the select call in InotifyReaderTask
- // returns.
- ssize_t ret = HANDLE_EINTR(write(shutdown_pipe_[1], "", 1));
- DPCHECK(ret > 0);
- DCHECK_EQ(ret, 1);
- thread_.Stop();
- }
- if (inotify_fd_ >= 0)
- close(inotify_fd_);
- if (shutdown_pipe_[0] >= 0)
- close(shutdown_pipe_[0]);
- if (shutdown_pipe_[1] >= 0)
- close(shutdown_pipe_[1]);
-}
-
-InotifyReader::Watch InotifyReader::AddWatch(
- const FilePath& path, FilePathWatcherImpl* watcher) {
- if (!valid_)
- return kInvalidWatch;
-
- base::AutoLock auto_lock(lock_);
-
- Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(),
- IN_CREATE | IN_DELETE |
- IN_CLOSE_WRITE | IN_MOVE |
- IN_ONLYDIR);
-
- if (watch == kInvalidWatch)
- return kInvalidWatch;
-
- watchers_[watch].insert(watcher);
-
- return watch;
-}
-
-bool InotifyReader::RemoveWatch(Watch watch,
- FilePathWatcherImpl* watcher) {
- if (!valid_)
- return false;
-
- base::AutoLock auto_lock(lock_);
-
- watchers_[watch].erase(watcher);
-
- if (watchers_[watch].empty()) {
- watchers_.erase(watch);
- return (inotify_rm_watch(inotify_fd_, watch) == 0);
- }
-
- return true;
-}
-
-void InotifyReader::OnInotifyEvent(const inotify_event* event) {
- if (event->mask & IN_IGNORED)
- return;
-
- FilePath::StringType child(event->len ? event->name : FILE_PATH_LITERAL(""));
- base::AutoLock auto_lock(lock_);
-
- for (WatcherSet::iterator watcher = watchers_[event->wd].begin();
- watcher != watchers_[event->wd].end();
- ++watcher) {
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- NewRunnableMethod(*watcher,
- &FilePathWatcherImpl::OnFilePathChanged,
- event->wd,
- child,
- event->mask & (IN_CREATE | IN_MOVED_TO),
- event->mask & IN_ISDIR));
- }
-}
-
-FilePathWatcherImpl::FilePathWatcherImpl()
- : delegate_(NULL) {
-}
-
-void FilePathWatcherImpl::OnFilePathChanged(InotifyReader::Watch fired_watch,
- const FilePath::StringType& child,
- bool created,
- bool is_directory) {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
-
- // Find the entry in |watches_| that corresponds to |fired_watch|.
- WatchVector::const_iterator watch_entry(watches_.begin());
- for ( ; watch_entry != watches_.end(); ++watch_entry) {
- if (fired_watch == watch_entry->watch_)
- break;
- }
-
- // If this notification is from a previous generation of watches or the watch
- // has been cancelled (|watches_| is empty then), bail out.
- if (watch_entry == watches_.end())
- return;
-
- // Check whether a path component of |target_| changed.
- bool change_on_target_path = child.empty() || child == watch_entry->subdir_;
-
- // Check whether the change references |target_| or a direct child.
- DCHECK(watch_entry->subdir_.empty() || (watch_entry + 1) != watches_.end());
- bool target_changed = watch_entry->subdir_.empty() ||
- (watch_entry->subdir_ == child && (++watch_entry)->subdir_.empty());
-
- // Update watches if a directory component of the |target_| path (dis)appears.
- if (is_directory && change_on_target_path && !UpdateWatches()) {
- delegate_->OnError();
- return;
- }
-
- // Report the following events:
- // - The target or a direct child of the target got changed (in case the
- // watched path refers to a directory).
- // - One of the parent directories got moved or deleted, since the target
- // disappears in this case.
- // - One of the parent directories appears. The event corresponding to the
- // target appearing might have been missed in this case, so recheck.
- if (target_changed ||
- (change_on_target_path && !created) ||
- (change_on_target_path && file_util::PathExists(target_))) {
- delegate_->OnFilePathChanged(target_);
- }
-}
-
-bool FilePathWatcherImpl::Watch(const FilePath& path,
- FilePathWatcher::Delegate* delegate) {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
- DCHECK(target_.empty());
-
- delegate_ = delegate;
- target_ = path;
- std::vector<FilePath::StringType> comps;
- target_.GetComponents(&comps);
- DCHECK(!comps.empty());
- for (std::vector<FilePath::StringType>::const_iterator comp(++comps.begin());
- comp != comps.end(); ++comp) {
- watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch, *comp));
- }
- watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch,
- FilePath::StringType()));
- return UpdateWatches();
-}
-
-void FilePathWatcherImpl::Cancel() {
- // Switch to the file thread if necessary so we can access |watches_|.
- if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- NewRunnableMethod(this, &FilePathWatcherImpl::Cancel));
- return;
- }
-
- for (WatchVector::iterator watch_entry(watches_.begin());
- watch_entry != watches_.end(); ++watch_entry) {
- if (watch_entry->watch_ != InotifyReader::kInvalidWatch)
- g_inotify_reader.Get().RemoveWatch(watch_entry->watch_, this);
- }
- watches_.clear();
- delegate_ = NULL;
- target_.clear();
-}
-
-bool FilePathWatcherImpl::UpdateWatches() {
- // Ensure this runs on the file thread exclusively in order to avoid
- // concurrency issues.
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
-
- // Walk the list of watches and update them as we go.
- FilePath path(FILE_PATH_LITERAL("/"));
- bool path_valid = true;
- for (WatchVector::iterator watch_entry(watches_.begin());
- watch_entry != watches_.end(); ++watch_entry) {
- InotifyReader::Watch old_watch = watch_entry->watch_;
- if (path_valid) {
- watch_entry->watch_ = g_inotify_reader.Get().AddWatch(path, this);
- if (watch_entry->watch_ == InotifyReader::kInvalidWatch) {
- path_valid = false;
- }
- } else {
- watch_entry->watch_ = InotifyReader::kInvalidWatch;
- }
- if (old_watch != InotifyReader::kInvalidWatch &&
- old_watch != watch_entry->watch_) {
- g_inotify_reader.Get().RemoveWatch(old_watch, this);
- }
- path = path.Append(watch_entry->subdir_);
- }
-
- return true;
-}
-
-} // namespace
-
-FilePathWatcher::FilePathWatcher() {
- impl_ = new FilePathWatcherImpl();
-}
diff --git a/chrome/browser/file_path_watcher/file_path_watcher_mac.cc b/chrome/browser/file_path_watcher/file_path_watcher_mac.cc
deleted file mode 100644
index e89cf87..0000000
--- a/chrome/browser/file_path_watcher/file_path_watcher_mac.cc
+++ /dev/null
@@ -1,234 +0,0 @@
-// Copyright (c) 2010 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 "chrome/browser/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/singleton.h"
-#include "base/time.h"
-
-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:
- 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);
- virtual void Cancel();
-
- private:
- virtual ~FilePathWatcherImpl() {}
-
- // Destroy the event stream.
- void DestroyEventStream();
-
- // 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_;
-
- // Used to detect early cancellation.
- bool canceled_;
-
- 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[]) {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
-
- FilePathWatcherImpl* watcher =
- reinterpret_cast<FilePathWatcherImpl*>(event_watcher);
- 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.
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- NewRunnableMethod(watcher, &FilePathWatcherImpl::UpdateEventStream,
- root_change_at));
- }
-
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- NewRunnableMethod(watcher, &FilePathWatcherImpl::OnFilePathChanged));
-}
-
-// FilePathWatcherImpl implementation:
-
-FilePathWatcherImpl::FilePathWatcherImpl()
- : fsevent_stream_(NULL),
- canceled_(false) {
-}
-
-void FilePathWatcherImpl::OnFilePathChanged() {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
- 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) {
- DCHECK(target_.value().empty());
-
- 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();
- }
-
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- NewRunnableMethod(this, &FilePathWatcherImpl::UpdateEventStream,
- start_event));
-
- return true;
-}
-
-void FilePathWatcherImpl::Cancel() {
- // Switch to the UI thread if necessary, so we can tear down the event stream.
- if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
- BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
- NewRunnableMethod(this, &FilePathWatcherImpl::Cancel));
- return;
- }
-
- canceled_ = true;
- if (fsevent_stream_)
- DestroyEventStream();
-}
-
-void FilePathWatcherImpl::UpdateEventStream(FSEventStreamEventId start_event) {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
-
- // 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 (canceled_)
- 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_)) {
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- NewRunnableMethod(delegate_.get(),
- &FilePathWatcher::Delegate::OnError));
- }
-}
-
-void FilePathWatcherImpl::DestroyEventStream() {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- FSEventStreamStop(fsevent_stream_);
- FSEventStreamUnscheduleFromRunLoop(fsevent_stream_, CFRunLoopGetCurrent(),
- kCFRunLoopDefaultMode);
- FSEventStreamRelease(fsevent_stream_);
- fsevent_stream_ = NULL;
-}
-
-} // namespace
-
-FilePathWatcher::FilePathWatcher() {
- impl_ = new FilePathWatcherImpl();
-}
diff --git a/chrome/browser/file_path_watcher/file_path_watcher_stub.cc b/chrome/browser/file_path_watcher/file_path_watcher_stub.cc
deleted file mode 100644
index 6387715..0000000
--- a/chrome/browser/file_path_watcher/file_path_watcher_stub.cc
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright (c) 2010 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.
-
-// This file exists for Unix systems which don't have the inotify headers, and
-// thus cannot build file_watcher_inotify.cc
-
-#include "chrome/browser/file_path_watcher/file_path_watcher.h"
-
-class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate {
- public:
- virtual bool Watch(const FilePath& path, FileWatcher::Delegate* delegate) {
- return false;
- }
-};
-
-FilePathWatcher::FilePathWatcher() {
- impl_ = new FilePathWatcherImpl();
-}
diff --git a/chrome/browser/file_path_watcher/file_path_watcher_win.cc b/chrome/browser/file_path_watcher/file_path_watcher_win.cc
deleted file mode 100644
index c2f49b9..0000000
--- a/chrome/browser/file_path_watcher/file_path_watcher_win.cc
+++ /dev/null
@@ -1,244 +0,0 @@
-// Copyright (c) 2010 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 "chrome/browser/file_path_watcher/file_path_watcher.h"
-
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "base/logging.h"
-#include "base/ref_counted.h"
-#include "base/time.h"
-#include "base/win/object_watcher.h"
-
-namespace {
-
-class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate,
- public base::win::ObjectWatcher::Delegate {
- public:
- FilePathWatcherImpl() : delegate_(NULL), handle_(INVALID_HANDLE_VALUE) {}
-
- virtual bool Watch(const FilePath& path, FilePathWatcher::Delegate* delegate);
- virtual void Cancel();
-
- // Callback from MessageLoopForIO.
- virtual void OnObjectSignaled(HANDLE object);
-
- private:
- virtual ~FilePathWatcherImpl();
-
- // Setup a watch handle for directory |dir|. Returns true if no fatal error
- // occurs. |handle| will receive the handle value if |dir| is watchable,
- // otherwise INVALID_HANDLE_VALUE.
- static bool SetupWatchHandle(const FilePath& dir, HANDLE* handle)
- WARN_UNUSED_RESULT;
-
- // (Re-)Initialize the watch handle.
- bool UpdateWatch() WARN_UNUSED_RESULT;
-
- // Destroy the watch handle.
- void DestroyWatch();
-
- // Delegate to notify upon changes.
- scoped_refptr<FilePathWatcher::Delegate> delegate_;
-
- // Path we're supposed to watch (passed to delegate).
- FilePath target_;
-
- // Handle for FindFirstChangeNotification.
- HANDLE handle_;
-
- // ObjectWatcher to watch handle_ for events.
- base::win::ObjectWatcher watcher_;
-
- // 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_;
-
- DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
-};
-
-bool FilePathWatcherImpl::Watch(const FilePath& path,
- FilePathWatcher::Delegate* delegate) {
- DCHECK(target_.value().empty()); // Can only watch one path.
- delegate_ = delegate;
- target_ = path;
-
- if (!UpdateWatch())
- return false;
-
- watcher_.StartWatching(handle_, this);
-
- return true;
-}
-
-void FilePathWatcherImpl::Cancel() {
- // Switch to the file thread if necessary so we can stop |watcher_|.
- if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
- BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
- NewRunnableMethod(this, &FilePathWatcherImpl::Cancel));
- return;
- }
-
- if (handle_ != INVALID_HANDLE_VALUE)
- DestroyWatch();
-}
-
-void FilePathWatcherImpl::OnObjectSignaled(HANDLE object) {
- DCHECK(object == handle_);
- // Make sure we stay alive through the body of this function.
- scoped_refptr<FilePathWatcherImpl> keep_alive(this);
-
- if (!UpdateWatch()) {
- delegate_->OnError();
- return;
- }
-
- // Check whether the event applies to |target_| and notify the delegate.
- 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_);
- }
-
- // The watch may have been cancelled by the callback.
- if (handle_ != INVALID_HANDLE_VALUE)
- watcher_.StartWatching(handle_, this);
-}
-
-FilePathWatcherImpl::~FilePathWatcherImpl() {
- if (handle_ != INVALID_HANDLE_VALUE)
- DestroyWatch();
-}
-
-// static
-bool FilePathWatcherImpl::SetupWatchHandle(const FilePath& dir,
- HANDLE* handle) {
- *handle = FindFirstChangeNotification(
- dir.value().c_str(),
- false, // Don't watch subtrees
- FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE |
- FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_DIR_NAME |
- FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SECURITY);
- if (*handle != INVALID_HANDLE_VALUE) {
- // Make sure the handle we got points to an existing directory. It seems
- // that windows sometimes hands out watches to direectories that are
- // about to go away, but doesn't sent notifications if that happens.
- if (!file_util::DirectoryExists(dir)) {
- FindCloseChangeNotification(*handle);
- *handle = INVALID_HANDLE_VALUE;
- }
- return true;
- }
-
- // If FindFirstChangeNotification failed because the target directory
- // doesn't exist, access is denied (happens if the file is already gone but
- // there are still handles open), or the target is not a directory, try the
- // immediate parent directory instead.
- DWORD error_code = GetLastError();
- if (error_code != ERROR_FILE_NOT_FOUND &&
- error_code != ERROR_PATH_NOT_FOUND &&
- error_code != ERROR_ACCESS_DENIED &&
- error_code != ERROR_SHARING_VIOLATION &&
- error_code != ERROR_DIRECTORY) {
- PLOG(ERROR) << "FindFirstChangeNotification failed for "
- << dir.value();
- return false;
- }
-
- return true;
-}
-
-bool FilePathWatcherImpl::UpdateWatch() {
- if (handle_ != INVALID_HANDLE_VALUE)
- DestroyWatch();
-
- base::PlatformFileInfo file_info;
- if (file_util::GetFileInfo(target_, &file_info)) {
- last_modified_ = file_info.last_modified;
- first_notification_ = base::Time::Now();
- }
-
- // Start at the target and walk up the directory chain until we succesfully
- // create a watch handle in |handle_|. |child_dirs| keeps a stack of child
- // directories stripped from target, in reverse order.
- std::vector<FilePath> child_dirs;
- FilePath watched_path(target_);
- while (true) {
- if (!SetupWatchHandle(watched_path, &handle_))
- return false;
-
- // Break if a valid handle is returned. Try the parent directory otherwise.
- if (handle_ != INVALID_HANDLE_VALUE)
- break;
-
- // Abort if we hit the root directory.
- child_dirs.push_back(watched_path.BaseName());
- FilePath parent(watched_path.DirName());
- if (parent == watched_path) {
- LOG(ERROR) << "Reached the root directory";
- return false;
- }
- watched_path = parent;
- }
-
- // At this point, handle_ is valid. However, the bottom-up search that the
- // above code performs races against directory creation. So try to walk back
- // down and see whether any children appeared in the mean time.
- while (!child_dirs.empty()) {
- watched_path = watched_path.Append(child_dirs.back());
- child_dirs.pop_back();
- HANDLE temp_handle = INVALID_HANDLE_VALUE;
- if (!SetupWatchHandle(watched_path, &temp_handle))
- return false;
- if (temp_handle == INVALID_HANDLE_VALUE)
- break;
- FindCloseChangeNotification(handle_);
- handle_ = temp_handle;
- }
-
- return true;
-}
-
-void FilePathWatcherImpl::DestroyWatch() {
- watcher_.StopWatching();
- FindCloseChangeNotification(handle_);
- handle_ = INVALID_HANDLE_VALUE;
-}
-
-} // namespace
-
-FilePathWatcher::FilePathWatcher() {
- impl_ = new FilePathWatcherImpl();
-}
diff --git a/chrome/browser/policy/file_based_policy_loader.cc b/chrome/browser/policy/file_based_policy_loader.cc
index cc89d13..c12bbcf 100644
--- a/chrome/browser/policy/file_based_policy_loader.cc
+++ b/chrome/browser/policy/file_based_policy_loader.cc
@@ -1,9 +1,11 @@
-// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// 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 "chrome/browser/policy/file_based_policy_loader.h"
+#include "content/browser/browser_thread.h"
+
namespace {
// Amount of time we wait for the files on disk to settle before trying to load
@@ -93,8 +95,10 @@ void FileBasedPolicyLoader::InitOnFileThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
watcher_.reset(new FilePathWatcher);
if (!config_file_path().empty() &&
- !watcher_->Watch(config_file_path(),
- new FileBasedPolicyWatcherDelegate(this))) {
+ !watcher_->Watch(
+ config_file_path(),
+ new FileBasedPolicyWatcherDelegate(this),
+ BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI))) {
OnError();
}
diff --git a/chrome/browser/policy/file_based_policy_loader.h b/chrome/browser/policy/file_based_policy_loader.h
index 97c3198..52aa52b 100644
--- a/chrome/browser/policy/file_based_policy_loader.h
+++ b/chrome/browser/policy/file_based_policy_loader.h
@@ -1,4 +1,4 @@
-// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// 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.
@@ -6,9 +6,9 @@
#define CHROME_BROWSER_POLICY_FILE_BASED_POLICY_LOADER_H_
#pragma once
-#include "chrome/browser/file_path_watcher/file_path_watcher.h"
#include "chrome/browser/policy/asynchronous_policy_loader.h"
#include "chrome/browser/policy/file_based_policy_provider.h"
+#include "content/common/file_path_watcher/file_path_watcher.h"
namespace policy {
diff --git a/chrome/browser/user_style_sheet_watcher.cc b/chrome/browser/user_style_sheet_watcher.cc
index 347462c..9a314b3 100644
--- a/chrome/browser/user_style_sheet_watcher.cc
+++ b/chrome/browser/user_style_sheet_watcher.cc
@@ -148,8 +148,12 @@ void UserStyleSheetWatcher::Init() {
file_watcher_.reset(new FilePathWatcher);
FilePath style_sheet_file = profile_path_.AppendASCII(kStyleSheetDir)
.AppendASCII(kUserStyleSheetFile);
- if (!file_watcher_->Watch(style_sheet_file, loader_.get()))
+ if (!file_watcher_->Watch(
+ style_sheet_file,
+ loader_.get(),
+ BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI))) {
LOG(ERROR) << "Failed to setup watch for " << style_sheet_file.value();
+ }
loader_->LoadStyleSheet(style_sheet_file);
}
}
diff --git a/chrome/browser/user_style_sheet_watcher.h b/chrome/browser/user_style_sheet_watcher.h
index 1e5ce1a..d846bdf 100644
--- a/chrome/browser/user_style_sheet_watcher.h
+++ b/chrome/browser/user_style_sheet_watcher.h
@@ -9,8 +9,8 @@
#include "base/file_path.h"
#include "base/ref_counted.h"
#include "base/scoped_ptr.h"
-#include "chrome/browser/file_path_watcher/file_path_watcher.h"
#include "content/browser/browser_thread.h"
+#include "content/common/file_path_watcher/file_path_watcher.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "googleurl/src/gurl.h"
diff --git a/chrome/browser/user_style_sheet_watcher_unittest.cc b/chrome/browser/user_style_sheet_watcher_unittest.cc
index e3f0d06..2172404 100644
--- a/chrome/browser/user_style_sheet_watcher_unittest.cc
+++ b/chrome/browser/user_style_sheet_watcher_unittest.cc
@@ -1,14 +1,16 @@
-// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// 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 "chrome/browser/user_style_sheet_watcher.h"
+#include "base/basictypes.h"
#include "base/base64.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
+#include "base/threading/thread.h"
#include "content/browser/browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -25,20 +27,25 @@ TEST(UserStyleSheetWatcherTest, StyleLoad) {
scoped_refptr<UserStyleSheetWatcher> style_sheet_watcher(
new UserStyleSheetWatcher(dir.path()));
- MessageLoop loop;
- BrowserThread ui_thread(BrowserThread::UI, &loop);
- BrowserThread file_thread(BrowserThread::FILE, &loop);
+
+ MessageLoop loop(MessageLoop::TYPE_UI);
+ base::Thread io_thread("UserStyleSheetWatcherTestIOThread");
+ base::Thread::Options options(MessageLoop::TYPE_IO, 0);
+ io_thread.StartWithOptions(options);
+ BrowserThread browser_ui_thread(BrowserThread::UI, &loop);
+ BrowserThread browser_file_thread(BrowserThread::FILE,
+ io_thread.message_loop());
style_sheet_watcher->Init();
+ io_thread.Stop();
loop.RunAllPending();
GURL result_url = style_sheet_watcher->user_style_sheet();
std::string result = result_url.spec();
std::string prefix = "data:text/css;charset=utf-8;base64,";
- EXPECT_TRUE(StartsWithASCII(result, prefix, true));
+ ASSERT_TRUE(StartsWithASCII(result, prefix, true));
result = result.substr(prefix.length());
std::string decoded;
- EXPECT_TRUE(base::Base64Decode(result, &decoded));
- EXPECT_EQ(css_file_contents, decoded);
- style_sheet_watcher = NULL;
+ ASSERT_TRUE(base::Base64Decode(result, &decoded));
+ ASSERT_EQ(css_file_contents, decoded);
}
diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi
index 8176a79..37397d5 100644
--- a/chrome/chrome_browser.gypi
+++ b/chrome/chrome_browser.gypi
@@ -1062,11 +1062,6 @@
'browser/favicon_helper.h',
'browser/favicon_service.cc',
'browser/favicon_service.h',
- 'browser/file_path_watcher/file_path_watcher.cc',
- 'browser/file_path_watcher/file_path_watcher.h',
- 'browser/file_path_watcher/file_path_watcher_inotify.cc',
- 'browser/file_path_watcher/file_path_watcher_mac.cc',
- 'browser/file_path_watcher/file_path_watcher_win.cc',
'browser/file_select_helper.cc',
'browser/file_select_helper.h',
'browser/first_run/first_run.cc',
@@ -3408,7 +3403,6 @@
],
}, { # OS != "linux"
'sources!': [
- 'browser/file_path_watcher/file_path_watcher_inotify.cc',
'browser/ui/webui/options/certificate_manager_handler.cc',
'browser/ui/webui/options/certificate_manager_handler.h',
],
@@ -3420,9 +3414,6 @@
'../build/linux/system.gyp:nss',
'../build/linux/system.gyp:x11',
],
- 'sources': [
- 'browser/file_path_watcher/file_path_watcher_stub.cc',
- ],
}],
# Use system SSL settings on Mac and Windows. Use preferences
# for SSL settings on other platforms.
diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi
index 9a118cc..39c15cd 100644
--- a/chrome/chrome_tests.gypi
+++ b/chrome/chrome_tests.gypi
@@ -2247,7 +2247,6 @@
'browser/extensions/permissions_apitest.cc',
'browser/extensions/stubs_apitest.cc',
'browser/extensions/window_open_apitest.cc',
- 'browser/file_path_watcher/file_path_watcher_browsertest.cc',
'browser/first_run/first_run_browsertest.cc',
'browser/geolocation/access_token_store_browsertest.cc',
'browser/geolocation/geolocation_browsertest.cc',
@@ -2322,6 +2321,7 @@
'../content/browser/webui/web_ui_browsertest.h',
'../content/browser/webui/web_ui_handler_browsertest.cc',
'../content/browser/webui/web_ui_handler_browsertest.h',
+ '../content/common/file_path_watcher/file_path_watcher_browsertest.cc',
],
'conditions': [
['chromeos==0', {