diff options
author | ricow@chromium.org <ricow@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-01-10 11:14:37 +0000 |
---|---|---|
committer | ricow@chromium.org <ricow@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-01-10 11:14:37 +0000 |
commit | 78acaf6d0ac35af3081e20511afdd9565520d067 (patch) | |
tree | 5ba4004249e535cf12d624a66aedce51aebaa874 | |
parent | 85db26ae55f5b20a32884e38ce39b8ba449238b1 (diff) | |
download | chromium_src-78acaf6d0ac35af3081e20511afdd9565520d067.zip chromium_src-78acaf6d0ac35af3081e20511afdd9565520d067.tar.gz chromium_src-78acaf6d0ac35af3081e20511afdd9565520d067.tar.bz2 |
Revert 176047
> Revert 176015
> > Run the JSON Schema Compiler's bundle compilation on JSON files. Previously it
> > was only run on IDL files. Clean up all the code which that simplifies.
> >
> > TBR=isherman@chromium.org,battre@chromium.org,akalin@chromium.org
> > BUG=141318
> >
> > Review URL: https://chromiumcodereview.appspot.com/11747025
>
> This seems to be causing complation failures on release win builders:
> http://chromegw/i/chromium.chrome/builders/Google%20Chrome%20Win/builds/15702
>
> TBR=kalman@chromium.org
> Review URL: https://codereview.chromium.org/11826048
Drover messed up this revert, reverting it
TBR=ricow@chromium.org
Review URL: https://codereview.chromium.org/11778096
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176051 0039d316-1c4b-4281-b951-d872f2087c98
120 files changed, 1192 insertions, 8804 deletions
diff --git a/build/json_schema_bundle_compile.gypi b/build/json_schema_bundle_compile.gypi index ecefe41..11a6a28 100644 --- a/build/json_schema_bundle_compile.gypi +++ b/build/json_schema_bundle_compile.gypi @@ -5,7 +5,7 @@ { 'variables': { # When including this gypi, the following variables must be set: - # idl_schema_files: an array of idl files that comprise the api model. + # schema_files: an array of json or idl files that comprise the api model. # cc_dir: path to generated files # root_namespace: the C++ namespace that all generated files go under # Functions and namespaces can be excluded by setting "nocompile" to true. @@ -27,7 +27,7 @@ '<(api_gen_dir)/model.py', '<(api_gen_dir)/schema_bundle_generator.py', '<(api_gen_dir)/util_cc_helper.py', - '<@(idl_schema_files)', + '<@(schema_files)', ], 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/<(cc_dir)/generated_api.h', @@ -41,7 +41,7 @@ '--destdir=<(SHARED_INTERMEDIATE_DIR)', '--namespace=<(root_namespace)', '--bundle', - '<@(idl_schema_files)', + '<@(schema_files)', ], 'message': 'Generating C++ API bundle code', 'process_outputs_as_sources': 1, diff --git a/build/json_schema_compile.gypi b/build/json_schema_compile.gypi index 6c8f69c..6da8961 100644 --- a/build/json_schema_compile.gypi +++ b/build/json_schema_compile.gypi @@ -5,8 +5,7 @@ { 'variables': { # When including this gypi, the following variables must be set: - # json_schema_files: a list of json files that comprise the api model. - # idl_schema_files: a list of IDL files that comprise the api model. + # schema_files: a list of json or IDL files that comprise the api model. # cc_dir: path to generated files # root_namespace: the C++ namespace that all generated files go under # Functions and namespaces can be excluded by setting "nocompile" to true. diff --git a/chrome/browser/chromeos/extensions/file_browser_handler_api.cc b/chrome/browser/chromeos/extensions/file_browser_handler_api.cc index 940a04f..45e8161 100644 --- a/chrome/browser/chromeos/extensions/file_browser_handler_api.cc +++ b/chrome/browser/chromeos/extensions/file_browser_handler_api.cc @@ -10,10 +10,10 @@ // - Display 'save as' dialog using FileSelectorImpl which waits for the user // feedback. // - Once the user selects the file path (or cancels the selection), -// FileSelectorImpl notifies FileHandlerSelectFileFunction of the selection -// result by calling FileHandlerSelectFile::OnFilePathSelected. -// - If the selection was canceled, FileHandlerSelectFileFunction returns -// reporting failure. +// FileSelectorImpl notifies FileBrowserHandlerInternalSelectFileFunction of +// the selection result by calling FileHandlerSelectFile::OnFilePathSelected. +// - If the selection was canceled, +// FileBrowserHandlerInternalSelectFileFunction returns reporting failure. // - If the file path was selected, the function opens external file system // needed to create FileEntry object for the selected path // (opening file system will create file system name and root url for the @@ -119,10 +119,11 @@ class FileSelectorImpl : public FileSelector, // After this method is called, the selector implementation should not be // deleted by the caller. It will delete itself after it receives response // from SelectFielDialog. - virtual void SelectFile(const FilePath& suggested_name, - const std::vector<std::string>& allowed_extensions, - Browser* browser, - FileHandlerSelectFileFunction* function) OVERRIDE; + virtual void SelectFile( + const FilePath& suggested_name, + const std::vector<std::string>& allowed_extensions, + Browser* browser, + FileBrowserHandlerInternalSelectFileFunction* function) OVERRIDE; // ui::SelectFileDialog::Listener overrides. virtual void FileSelected(const FilePath& path, @@ -158,7 +159,7 @@ class FileSelectorImpl : public FileSelector, scoped_refptr<ui::SelectFileDialog> dialog_; // Extension function that uses the selector. - scoped_refptr<FileHandlerSelectFileFunction> function_; + scoped_refptr<FileBrowserHandlerInternalSelectFileFunction> function_; DISALLOW_COPY_AND_ASSIGN(FileSelectorImpl); }; @@ -177,7 +178,7 @@ void FileSelectorImpl::SelectFile( const FilePath& suggested_name, const std::vector<std::string>& allowed_extensions, Browser* browser, - FileHandlerSelectFileFunction* function) { + FileBrowserHandlerInternalSelectFileFunction* function) { // We will hold reference to the function until it is notified of selection // result. function_ = function; @@ -289,22 +290,25 @@ void RunOpenFileSystemCallback( } // namespace -FileHandlerSelectFileFunction::FileHandlerSelectFileFunction() - : file_selector_factory_(new FileSelectorFactoryImpl()), - user_gesture_check_enabled_(true) { +FileBrowserHandlerInternalSelectFileFunction:: + FileBrowserHandlerInternalSelectFileFunction() + : file_selector_factory_(new FileSelectorFactoryImpl()), + user_gesture_check_enabled_(true) { } -FileHandlerSelectFileFunction::FileHandlerSelectFileFunction( - FileSelectorFactory* file_selector_factory, - bool enable_user_gesture_check) - : file_selector_factory_(file_selector_factory), - user_gesture_check_enabled_(enable_user_gesture_check) { +FileBrowserHandlerInternalSelectFileFunction:: + FileBrowserHandlerInternalSelectFileFunction( + FileSelectorFactory* file_selector_factory, + bool enable_user_gesture_check) + : file_selector_factory_(file_selector_factory), + user_gesture_check_enabled_(enable_user_gesture_check) { DCHECK(file_selector_factory); } -FileHandlerSelectFileFunction::~FileHandlerSelectFileFunction() {} +FileBrowserHandlerInternalSelectFileFunction:: + ~FileBrowserHandlerInternalSelectFileFunction() {} -bool FileHandlerSelectFileFunction::RunImpl() { +bool FileBrowserHandlerInternalSelectFileFunction::RunImpl() { scoped_ptr<SelectFile::Params> params(SelectFile::Params::Create(*args_)); FilePath suggested_name(params->selection_params.suggested_name); @@ -325,7 +329,7 @@ bool FileHandlerSelectFileFunction::RunImpl() { return true; } -void FileHandlerSelectFileFunction::OnFilePathSelected( +void FileBrowserHandlerInternalSelectFileFunction::OnFilePathSelected( bool success, const FilePath& full_path) { if (!success) { @@ -342,11 +346,12 @@ void FileHandlerSelectFileFunction::OnFilePathSelected( source_url_.GetOrigin(), fileapi::kFileSystemTypeExternal, false, base::Bind( &RunOpenFileSystemCallback, - base::Bind(&FileHandlerSelectFileFunction::OnFileSystemOpened, + base::Bind(&FileBrowserHandlerInternalSelectFileFunction:: + OnFileSystemOpened, this))); }; -void FileHandlerSelectFileFunction::OnFileSystemOpened( +void FileBrowserHandlerInternalSelectFileFunction::OnFileSystemOpened( bool success, const std::string& file_system_name, const GURL& file_system_root) { @@ -364,7 +369,7 @@ void FileHandlerSelectFileFunction::OnFileSystemOpened( GrantPermissions(); } -void FileHandlerSelectFileFunction::GrantPermissions() { +void FileBrowserHandlerInternalSelectFileFunction::GrantPermissions() { fileapi::ExternalFileSystemMountPointProvider* external_provider = BrowserContext::GetDefaultStoragePartition(profile_)-> GetFileSystemContext()->external_provider(); @@ -400,11 +405,12 @@ void FileHandlerSelectFileFunction::GrantPermissions() { profile(), gdata_paths.Pass(), &permissions_to_grant_, - base::Bind(&FileHandlerSelectFileFunction::OnGotPermissionsToGrant, + base::Bind(&FileBrowserHandlerInternalSelectFileFunction:: + OnGotPermissionsToGrant, this)); } -void FileHandlerSelectFileFunction::OnGotPermissionsToGrant() { +void FileBrowserHandlerInternalSelectFileFunction::OnGotPermissionsToGrant() { // At this point all needed permissions should be collected, so let's grant // them. for (size_t i = 0; i < permissions_to_grant_.size(); i++) { @@ -417,7 +423,7 @@ void FileHandlerSelectFileFunction::OnGotPermissionsToGrant() { Respond(true); } -void FileHandlerSelectFileFunction::Respond(bool success) { +void FileBrowserHandlerInternalSelectFileFunction::Respond(bool success) { scoped_ptr<SelectFile::Results::Result> result( new SelectFile::Results::Result()); result->success = success; diff --git a/chrome/browser/chromeos/extensions/file_browser_handler_api.h b/chrome/browser/chromeos/extensions/file_browser_handler_api.h index a4a125d..db9a8db 100644 --- a/chrome/browser/chromeos/extensions/file_browser_handler_api.h +++ b/chrome/browser/chromeos/extensions/file_browser_handler_api.h @@ -19,14 +19,14 @@ #include "chrome/browser/extensions/extension_function.h" class Browser; -class FileHandlerSelectFileFunction; +class FileBrowserHandlerInternalSelectFileFunction; namespace file_handler { -// Interface that is used by FileHandlerSelectFileFunction to select the file -// path that should be reported back to the extension function caller. -// Nobody will take the ownership of the interface implementation, so it should -// delete itself once it's done. +// Interface that is used by FileBrowserHandlerInternalSelectFileFunction to +// select the file path that should be reported back to the extension function +// caller. Nobody will take the ownership of the interface implementation, so +// it should delete itself once it's done. class FileSelector { public: virtual ~FileSelector() {} @@ -48,19 +48,21 @@ class FileSelector { // |SelectFile| will be called at most once by a single extension function. // The interface implementation should delete itself after the extension // function is notified of file selection result. - virtual void SelectFile(const FilePath& suggested_name, - const std::vector<std::string>& allowed_extensions, - Browser* browser, - FileHandlerSelectFileFunction* function) = 0; + virtual void SelectFile( + const FilePath& suggested_name, + const std::vector<std::string>& allowed_extensions, + Browser* browser, + FileBrowserHandlerInternalSelectFileFunction* function) = 0; }; -// Interface that is used by FileHandlerSelectFileFunction to create a -// FileSelector it can use to select a file path. +// Interface that is used by FileBrowserHandlerInternalSelectFileFunction to +// create a FileSelector it can use to select a file path. class FileSelectorFactory { public: virtual ~FileSelectorFactory() {} - // Creates a FileSelector instance for the FileHandlerSelectFileFunction. + // Creates a FileSelector instance for the + // FileBrowserHandlerInternalSelectFileFunction. virtual FileSelector* CreateFileSelector() const = 0; }; @@ -68,18 +70,19 @@ class FileSelectorFactory { // The fileBrowserHandlerInternal.selectFile extension function implementation. // See the file description for more info. -class FileHandlerSelectFileFunction : public AsyncExtensionFunction { +class FileBrowserHandlerInternalSelectFileFunction + : public AsyncExtensionFunction { public: // Default constructor used in production code. // It will create its own FileSelectorFactory implementation, and set the // value of |user_gesture_check_enabled| to true. - FileHandlerSelectFileFunction(); + FileBrowserHandlerInternalSelectFileFunction(); // This constructor should be used only in tests to inject test file selector // factory and to allow extension function to run even if it hasn't been // invoked by user gesture. // Created object will take the ownership of the |file_selector_factory|. - FileHandlerSelectFileFunction( + FileBrowserHandlerInternalSelectFileFunction( file_handler::FileSelectorFactory* file_selector_factory, bool enable_user_gesture_check); @@ -93,7 +96,7 @@ class FileHandlerSelectFileFunction : public AsyncExtensionFunction { protected: // The class is ref counted, so destructor should not be public. - virtual ~FileHandlerSelectFileFunction() OVERRIDE; + virtual ~FileBrowserHandlerInternalSelectFileFunction(); // AsyncExtensionFunction implementation. // Runs the extension function implementation. diff --git a/chrome/browser/chromeos/extensions/file_browser_handler_api_test.cc b/chrome/browser/chromeos/extensions/file_browser_handler_api_test.cc index 5689100..c605ab7 100644 --- a/chrome/browser/chromeos/extensions/file_browser_handler_api_test.cc +++ b/chrome/browser/chromeos/extensions/file_browser_handler_api_test.cc @@ -64,7 +64,7 @@ void ExpectFileContentEquals(const FilePath& selected_path, EXPECT_EQ(expected_contents, test_file_contents); } -// Mocks FileSelector used by FileHandlerSelectFileFunction. +// Mocks FileSelector used by FileBrowserHandlerInternalSelectFileFunction. // When |SelectFile| is called, it will check that file name suggestion is as // expected, and respond to the extension function with specified selection // results. @@ -83,10 +83,11 @@ class MockFileSelector : public file_handler::FileSelector { // file_handler::FileSelector implementation. // |browser| is not used. - virtual void SelectFile(const FilePath& suggested_name, - const std::vector<std::string>& allowed_extensions, - Browser* browser, - FileHandlerSelectFileFunction* function) OVERRIDE { + virtual void SelectFile( + const FilePath& suggested_name, + const std::vector<std::string>& allowed_extensions, + Browser* browser, + FileBrowserHandlerInternalSelectFileFunction* function) OVERRIDE { // Confirm that the function suggested us the right name. EXPECT_EQ(suggested_name_, suggested_name); // Confirm that the function allowed us the right extensions. @@ -100,8 +101,9 @@ class MockFileSelector : public file_handler::FileSelector { // Send response to the extension function. // The callback will take a reference to the function and keep it alive. base::MessageLoopProxy::current()->PostTask(FROM_HERE, - base::Bind(&FileHandlerSelectFileFunction::OnFilePathSelected, - function, success_, selected_path_)); + base::Bind(&FileBrowserHandlerInternalSelectFileFunction:: + OnFilePathSelected, + function, success_, selected_path_)); delete this; } @@ -182,10 +184,10 @@ class FileBrowserHandlerExtensionTest : public ExtensionApiTest { return tmp_mount_point_.Append(relative_path); } - // Creates a new FileHandlerSelectFileFunction to be used in the test. - // This function will be called from ExtensionFunctinoDispatcher whenever - // an extension function for fileBrowserHandlerInternal.selectFile will be - // needed. + // Creates a new FileBrowserHandlerInternalSelectFileFunction to be used in + // the test. This function will be called from ExtensionFunctinoDispatcher + // whenever an extension function for fileBrowserHandlerInternal.selectFile + // will be needed. static ExtensionFunction* TestSelectFileFunctionFactory() { EXPECT_TRUE(test_cases_); EXPECT_TRUE(current_test_case_ < test_cases_->size()); @@ -193,14 +195,15 @@ class FileBrowserHandlerExtensionTest : public ExtensionApiTest { // If this happens, test failed. But, we still don't want to crash, so // return valid extension function. if (!test_cases_ && current_test_case_ >= test_cases_->size()) - return new FileHandlerSelectFileFunction(); + return new FileBrowserHandlerInternalSelectFileFunction(); // Create file creator factory for the current test case. MockFileSelectorFactory* mock_factory = new MockFileSelectorFactory(test_cases_->at(current_test_case_)); current_test_case_++; - return new FileHandlerSelectFileFunction(mock_factory, false); + return new FileBrowserHandlerInternalSelectFileFunction( + mock_factory, false); } // Sets up test parameters for extension function invocations that will be @@ -289,8 +292,9 @@ IN_PROC_BROWSER_TEST_F(FileBrowserHandlerExtensionTest, EndToEnd) { // Tests that verifies the fileBrowserHandlerInternal.selectFile function fails // when invoked without user gesture. IN_PROC_BROWSER_TEST_F(FileBrowserHandlerExtensionTest, NoUserGesture) { - scoped_refptr<FileHandlerSelectFileFunction> select_file_function( - new FileHandlerSelectFileFunction()); + scoped_refptr<FileBrowserHandlerInternalSelectFileFunction> + select_file_function( + new FileBrowserHandlerInternalSelectFileFunction()); std::string error = utils::RunFunctionAndReturnError( @@ -313,9 +317,11 @@ IN_PROC_BROWSER_TEST_F(FileBrowserHandlerExtensionTest, SelectionFailed) { false, FilePath()); - scoped_refptr<FileHandlerSelectFileFunction> select_file_function( - new FileHandlerSelectFileFunction(new MockFileSelectorFactory(test_case), - false)); + scoped_refptr<FileBrowserHandlerInternalSelectFileFunction> + select_file_function( + new FileBrowserHandlerInternalSelectFileFunction( + new MockFileSelectorFactory(test_case), + false)); select_file_function->set_has_callback(true); select_file_function->set_user_gesture(true); @@ -340,9 +346,11 @@ IN_PROC_BROWSER_TEST_F(FileBrowserHandlerExtensionTest, SuggestedFullPath) { false, FilePath()); - scoped_refptr<FileHandlerSelectFileFunction> select_file_function( - new FileHandlerSelectFileFunction(new MockFileSelectorFactory(test_case), - false)); + scoped_refptr<FileBrowserHandlerInternalSelectFileFunction> + select_file_function( + new FileBrowserHandlerInternalSelectFileFunction( + new MockFileSelectorFactory(test_case), + false)); select_file_function->set_has_callback(true); select_file_function->set_user_gesture(true); diff --git a/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc b/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc index 6e48b67..8f736a5 100644 --- a/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc +++ b/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc @@ -88,12 +88,6 @@ bool AutotestPrivateLoginStatusFunction::RunImpl() { } AutotestPrivateAPI::AutotestPrivateAPI() : test_mode_(false) { - ExtensionFunctionRegistry* registry = - ExtensionFunctionRegistry::GetInstance(); - registry->RegisterFunction<AutotestPrivateLogoutFunction>(); - registry->RegisterFunction<AutotestPrivateRestartFunction>(); - registry->RegisterFunction<AutotestPrivateShutdownFunction>(); - registry->RegisterFunction<AutotestPrivateLoginStatusFunction>(); } AutotestPrivateAPI::~AutotestPrivateAPI() { diff --git a/chrome/browser/extensions/api/bluetooth/bluetooth_apitest.cc b/chrome/browser/extensions/api/bluetooth/bluetooth_apitest.cc index c3e3a65..a245283 100644 --- a/chrome/browser/extensions/api/bluetooth/bluetooth_apitest.cc +++ b/chrome/browser/extensions/api/bluetooth/bluetooth_apitest.cc @@ -449,8 +449,8 @@ IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevicesError) { } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, Permissions) { - RequestPermissionsFunction::SetAutoConfirmForTests(true); - RequestPermissionsFunction::SetIgnoreUserGestureForTests(true); + PermissionsRequestFunction::SetAutoConfirmForTests(true); + PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); EXPECT_CALL(*mock_adapter_, GetDevice(device1_->address())) .WillOnce(testing::Return(device1_.get())); diff --git a/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h b/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h index 0ed0bb2..77b5850 100644 --- a/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h +++ b/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h @@ -7,7 +7,7 @@ #include "base/values.h" #include "chrome/browser/bookmarks/bookmark_node_data.h" -#include "chrome/browser/extensions/api/bookmarks/bookmark_api.h" +#include "chrome/browser/extensions/api/bookmarks/bookmarks_api.h" #include "chrome/browser/extensions/extension_function.h" #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h" diff --git a/chrome/browser/extensions/api/bookmarks/bookmark_api_factory.cc b/chrome/browser/extensions/api/bookmarks/bookmark_api_factory.cc index 3f20629..9c649bb 100644 --- a/chrome/browser/extensions/api/bookmarks/bookmark_api_factory.cc +++ b/chrome/browser/extensions/api/bookmarks/bookmark_api_factory.cc @@ -4,7 +4,7 @@ #include "chrome/browser/extensions/api/bookmarks/bookmark_api_factory.h" -#include "chrome/browser/extensions/api/bookmarks/bookmark_api.h" +#include "chrome/browser/extensions/api/bookmarks/bookmarks_api.h" #include "chrome/browser/extensions/extension_system_factory.h" #include "chrome/browser/profiles/profile_dependency_manager.h" diff --git a/chrome/browser/extensions/api/bookmarks/bookmark_api.cc b/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc index c076813..08fa4ab3 100644 --- a/chrome/browser/extensions/api/bookmarks/bookmark_api.cc +++ b/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/extensions/api/bookmarks/bookmark_api.h" +#include "chrome/browser/extensions/api/bookmarks/bookmarks_api.h" #include "base/bind.h" #include "base/file_path.h" @@ -303,7 +303,7 @@ void BookmarkAPI::OnListenerAdded(const EventListenerInfo& details) { ExtensionSystem::Get(profile_)->event_router()->UnregisterObserver(this); } -bool GetBookmarksFunction::RunImpl() { +bool BookmarksGetTreeFunction::RunImpl() { scoped_ptr<bookmarks::Get::Params> params( bookmarks::Get::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -343,7 +343,7 @@ bool GetBookmarksFunction::RunImpl() { return true; } -bool GetBookmarkChildrenFunction::RunImpl() { +bool BookmarksGetChildrenFunction::RunImpl() { scoped_ptr<bookmarks::GetChildren::Params> params( bookmarks::GetChildren::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -369,7 +369,7 @@ bool GetBookmarkChildrenFunction::RunImpl() { return true; } -bool GetBookmarkRecentFunction::RunImpl() { +bool BookmarksGetFunction::RunImpl() { scoped_ptr<bookmarks::GetRecent::Params> params( bookmarks::GetRecent::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -393,7 +393,7 @@ bool GetBookmarkRecentFunction::RunImpl() { return true; } -bool GetBookmarkTreeFunction::RunImpl() { +bool BookmarksGetSubTreeFunction::RunImpl() { std::vector<linked_ptr<BookmarkTreeNode> > nodes; const BookmarkNode* node = BookmarkModelFactory::GetForProfile(profile())->root_node(); @@ -402,7 +402,7 @@ bool GetBookmarkTreeFunction::RunImpl() { return true; } -bool GetBookmarkSubTreeFunction::RunImpl() { +bool BookmarksGetRecentFunction::RunImpl() { scoped_ptr<bookmarks::GetSubTree::Params> params( bookmarks::GetSubTree::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -424,7 +424,7 @@ bool GetBookmarkSubTreeFunction::RunImpl() { return true; } -bool SearchBookmarksFunction::RunImpl() { +bool BookmarksSearchFunction::RunImpl() { scoped_ptr<bookmarks::Search::Params> params( bookmarks::Search::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -450,7 +450,7 @@ bool SearchBookmarksFunction::RunImpl() { } // static -bool RemoveBookmarkFunction::ExtractIds(const ListValue* args, +bool BookmarksRemoveFunction::ExtractIds(const ListValue* args, std::list<int64>* ids, bool* invalid_id) { std::string id_string; @@ -464,7 +464,7 @@ bool RemoveBookmarkFunction::ExtractIds(const ListValue* args, return true; } -bool RemoveBookmarkFunction::RunImpl() { +bool BookmarksRemoveFunction::RunImpl() { if (!EditBookmarksEnabled()) return false; @@ -479,7 +479,7 @@ bool RemoveBookmarkFunction::RunImpl() { } bool recursive = false; - if (name() == RemoveTreeBookmarkFunction::function_name()) + if (name() == BookmarksRemoveTreeFunction::function_name()) recursive = true; BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile()); @@ -489,7 +489,7 @@ bool RemoveBookmarkFunction::RunImpl() { return true; } -bool CreateBookmarkFunction::RunImpl() { +bool BookmarksCreateFunction::RunImpl() { if (!EditBookmarksEnabled()) return false; @@ -561,14 +561,14 @@ bool CreateBookmarkFunction::RunImpl() { } // static -bool MoveBookmarkFunction::ExtractIds(const ListValue* args, +bool BookmarksMoveFunction::ExtractIds(const ListValue* args, std::list<int64>* ids, bool* invalid_id) { // For now, Move accepts ID parameters in the same way as an Update. - return UpdateBookmarkFunction::ExtractIds(args, ids, invalid_id); + return BookmarksUpdateFunction::ExtractIds(args, ids, invalid_id); } -bool MoveBookmarkFunction::RunImpl() { +bool BookmarksMoveFunction::RunImpl() { if (!EditBookmarksEnabled()) return false; @@ -635,14 +635,14 @@ bool MoveBookmarkFunction::RunImpl() { } // static -bool UpdateBookmarkFunction::ExtractIds(const ListValue* args, +bool BookmarksUpdateFunction::ExtractIds(const ListValue* args, std::list<int64>* ids, bool* invalid_id) { // For now, Update accepts ID parameters in the same way as an Remove. - return RemoveBookmarkFunction::ExtractIds(args, ids, invalid_id); + return BookmarksRemoveFunction::ExtractIds(args, ids, invalid_id); } -bool UpdateBookmarkFunction::RunImpl() { +bool BookmarksUpdateFunction::RunImpl() { if (!EditBookmarksEnabled()) return false; @@ -719,7 +719,7 @@ class BookmarkBucketMapper : public BucketMapper { class CreateBookmarkBucketMapper : public BookmarkBucketMapper<std::string> { public: explicit CreateBookmarkBucketMapper(Profile* profile) : profile_(profile) {} - // TODO(tim): This should share code with CreateBookmarkFunction::RunImpl, + // TODO(tim): This should share code with BookmarksCreateFunction::RunImpl, // but I can't figure out a good way to do that with all the macros. virtual void GetBucketsForArgs(const ListValue* args, BucketList* buckets) { const DictionaryValue* json; @@ -763,7 +763,7 @@ class RemoveBookmarksBucketMapper : public BookmarkBucketMapper<std::string> { typedef std::list<int64> IdList; IdList ids; bool invalid_id = false; - if (!RemoveBookmarkFunction::ExtractIds(args, &ids, &invalid_id) || + if (!BookmarksRemoveFunction::ExtractIds(args, &ids, &invalid_id) || invalid_id) { return; } @@ -856,22 +856,22 @@ class BookmarksQuotaLimitFactory { }; // And finally, building the individual heuristics for each function. -void RemoveBookmarkFunction::GetQuotaLimitHeuristics( +void BookmarksRemoveFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristics* heuristics) const { BookmarksQuotaLimitFactory::BuildForRemove(heuristics, profile()); } -void MoveBookmarkFunction::GetQuotaLimitHeuristics( +void BookmarksMoveFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristics* heuristics) const { - BookmarksQuotaLimitFactory::Build<MoveBookmarkFunction>(heuristics); + BookmarksQuotaLimitFactory::Build<BookmarksMoveFunction>(heuristics); } -void UpdateBookmarkFunction::GetQuotaLimitHeuristics( +void BookmarksUpdateFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristics* heuristics) const { - BookmarksQuotaLimitFactory::Build<UpdateBookmarkFunction>(heuristics); + BookmarksQuotaLimitFactory::Build<BookmarksUpdateFunction>(heuristics); }; -void CreateBookmarkFunction::GetQuotaLimitHeuristics( +void BookmarksCreateFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristics* heuristics) const { BookmarksQuotaLimitFactory::BuildForCreate(heuristics, profile()); } @@ -949,14 +949,14 @@ void BookmarksIOFunction::MultiFilesSelected( NOTREACHED() << "Should not be able to select multiple files"; } -bool ImportBookmarksFunction::RunImpl() { +bool BookmarksImportFunction::RunImpl() { if (!EditBookmarksEnabled()) return false; SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE); return true; } -void ImportBookmarksFunction::FileSelected(const FilePath& path, +void BookmarksImportFunction::FileSelected(const FilePath& path, int index, void* params) { #if !defined(OS_ANDROID) @@ -976,12 +976,12 @@ void ImportBookmarksFunction::FileSelected(const FilePath& path, Release(); // Balanced in BookmarksIOFunction::SelectFile() } -bool ExportBookmarksFunction::RunImpl() { +bool BookmarksExportFunction::RunImpl() { SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE); return true; } -void ExportBookmarksFunction::FileSelected(const FilePath& path, +void BookmarksExportFunction::FileSelected(const FilePath& path, int index, void* params) { #if !defined(OS_ANDROID) diff --git a/chrome/browser/extensions/api/bookmarks/bookmark_api.h b/chrome/browser/extensions/api/bookmarks/bookmarks_api.h index c3008246..0d2a240 100644 --- a/chrome/browser/extensions/api/bookmarks/bookmark_api.h +++ b/chrome/browser/extensions/api/bookmarks/bookmarks_api.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_EXTENSIONS_API_BOOKMARKS_BOOKMARK_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_BOOKMARKS_BOOKMARK_API_H_ +#ifndef CHROME_BROWSER_EXTENSIONS_API_BOOKMARKS_BOOKMARKS_API_H_ +#define CHROME_BROWSER_EXTENSIONS_API_BOOKMARKS_BOOKMARKS_API_H_ #include <list> #include <string> @@ -116,73 +116,73 @@ class BookmarksFunction : public AsyncExtensionFunction, content::NotificationRegistrar registrar_; }; -class GetBookmarksFunction : public BookmarksFunction { +class BookmarksGetTreeFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.get") protected: - virtual ~GetBookmarksFunction() {} + virtual ~BookmarksGetTreeFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class GetBookmarkChildrenFunction : public BookmarksFunction { +class BookmarksGetChildrenFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.getChildren") protected: - virtual ~GetBookmarkChildrenFunction() {} + virtual ~BookmarksGetChildrenFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class GetBookmarkRecentFunction : public BookmarksFunction { +class BookmarksGetFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.getRecent") protected: - virtual ~GetBookmarkRecentFunction() {} + virtual ~BookmarksGetFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class GetBookmarkTreeFunction : public BookmarksFunction { +class BookmarksGetSubTreeFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.getTree") protected: - virtual ~GetBookmarkTreeFunction() {} + virtual ~BookmarksGetSubTreeFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class GetBookmarkSubTreeFunction : public BookmarksFunction { +class BookmarksGetRecentFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.getSubTree") protected: - virtual ~GetBookmarkSubTreeFunction() {} + virtual ~BookmarksGetRecentFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class SearchBookmarksFunction : public BookmarksFunction { +class BookmarksSearchFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.search") protected: - virtual ~SearchBookmarksFunction() {} + virtual ~BookmarksSearchFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class RemoveBookmarkFunction : public BookmarksFunction { +class BookmarksRemoveFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.remove") @@ -195,21 +195,21 @@ class RemoveBookmarkFunction : public BookmarksFunction { QuotaLimitHeuristics* heuristics) const OVERRIDE; protected: - virtual ~RemoveBookmarkFunction() {} + virtual ~BookmarksRemoveFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class RemoveTreeBookmarkFunction : public RemoveBookmarkFunction { +class BookmarksRemoveTreeFunction : public BookmarksRemoveFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.removeTree") protected: - virtual ~RemoveTreeBookmarkFunction() {} + virtual ~BookmarksRemoveTreeFunction() {} }; -class CreateBookmarkFunction : public BookmarksFunction { +class BookmarksCreateFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.create") @@ -218,13 +218,13 @@ class CreateBookmarkFunction : public BookmarksFunction { QuotaLimitHeuristics* heuristics) const OVERRIDE; protected: - virtual ~CreateBookmarkFunction() {} + virtual ~BookmarksCreateFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class MoveBookmarkFunction : public BookmarksFunction { +class BookmarksMoveFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.move") @@ -236,13 +236,13 @@ class MoveBookmarkFunction : public BookmarksFunction { QuotaLimitHeuristics* heuristics) const OVERRIDE; protected: - virtual ~MoveBookmarkFunction() {} + virtual ~BookmarksMoveFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class UpdateBookmarkFunction : public BookmarksFunction { +class BookmarksUpdateFunction : public BookmarksFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.update") @@ -254,7 +254,7 @@ class UpdateBookmarkFunction : public BookmarksFunction { QuotaLimitHeuristics* heuristics) const OVERRIDE; protected: - virtual ~UpdateBookmarkFunction() {} + virtual ~BookmarksUpdateFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; @@ -286,7 +286,7 @@ class BookmarksIOFunction : public BookmarksFunction, scoped_refptr<ui::SelectFileDialog> select_file_dialog_; }; -class ImportBookmarksFunction : public BookmarksIOFunction { +class BookmarksImportFunction : public BookmarksIOFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.import"); @@ -295,13 +295,13 @@ class ImportBookmarksFunction : public BookmarksIOFunction { OVERRIDE; private: - virtual ~ImportBookmarksFunction() {} + virtual ~BookmarksImportFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class ExportBookmarksFunction : public BookmarksIOFunction { +class BookmarksExportFunction : public BookmarksIOFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("bookmarks.export"); @@ -310,7 +310,7 @@ class ExportBookmarksFunction : public BookmarksIOFunction { OVERRIDE; private: - virtual ~ExportBookmarksFunction() {} + virtual ~BookmarksExportFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; @@ -318,4 +318,4 @@ class ExportBookmarksFunction : public BookmarksIOFunction { } // namespace extensions -#endif // CHROME_BROWSER_EXTENSIONS_API_BOOKMARKS_BOOKMARK_API_H_ +#endif // CHROME_BROWSER_EXTENSIONS_API_BOOKMARKS_BOOKMARKS_API_H_ diff --git a/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.cc b/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.cc index 2bb3a84..0c77b09 100644 --- a/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.cc +++ b/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.cc @@ -31,14 +31,16 @@ CloudPrintTestsDelegate::~CloudPrintTestsDelegate() { instance_ = NULL; } -CloudPrintSetupConnectorFunction::CloudPrintSetupConnectorFunction() { +CloudPrintPrivateSetupConnectorFunction:: + CloudPrintPrivateSetupConnectorFunction() { } -CloudPrintSetupConnectorFunction::~CloudPrintSetupConnectorFunction() { +CloudPrintPrivateSetupConnectorFunction:: + ~CloudPrintPrivateSetupConnectorFunction() { } -bool CloudPrintSetupConnectorFunction::RunImpl() { +bool CloudPrintPrivateSetupConnectorFunction::RunImpl() { using extensions::api::cloud_print_private::SetupConnector::Params; scoped_ptr<Params> params(Params::Create(*args_)); if (CloudPrintTestsDelegate::instance()) { @@ -60,13 +62,13 @@ bool CloudPrintSetupConnectorFunction::RunImpl() { return true; } -CloudPrintGetHostNameFunction::CloudPrintGetHostNameFunction() { +CloudPrintPrivateGetHostNameFunction::CloudPrintPrivateGetHostNameFunction() { } -CloudPrintGetHostNameFunction::~CloudPrintGetHostNameFunction() { +CloudPrintPrivateGetHostNameFunction::~CloudPrintPrivateGetHostNameFunction() { } -bool CloudPrintGetHostNameFunction::RunImpl() { +bool CloudPrintPrivateGetHostNameFunction::RunImpl() { SetResult(Value::CreateStringValue( CloudPrintTestsDelegate::instance() ? CloudPrintTestsDelegate::instance()->GetHostName() : @@ -75,19 +77,19 @@ bool CloudPrintGetHostNameFunction::RunImpl() { return true; } -CloudPrintGetPrintersFunction::CloudPrintGetPrintersFunction() { +CloudPrintPrivateGetPrintersFunction::CloudPrintPrivateGetPrintersFunction() { } -CloudPrintGetPrintersFunction::~CloudPrintGetPrintersFunction() { +CloudPrintPrivateGetPrintersFunction::~CloudPrintPrivateGetPrintersFunction() { } -void CloudPrintGetPrintersFunction::ReturnResult( +void CloudPrintPrivateGetPrintersFunction::ReturnResult( const base::ListValue* printers) { SetResult(printers->DeepCopy()); SendResponse(true); } -void CloudPrintGetPrintersFunction::CollectPrinters() { +void CloudPrintPrivateGetPrintersFunction::CollectPrinters() { scoped_ptr<base::ListValue> result(new base::ListValue()); if (CloudPrintTestsDelegate::instance()) { std::vector<std::string> printers = @@ -104,14 +106,14 @@ void CloudPrintGetPrintersFunction::CollectPrinters() { result->Append(Value::CreateStringValue(printers[i].printer_name)); } content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, - base::Bind(&CloudPrintGetPrintersFunction::ReturnResult, this, + base::Bind(&CloudPrintPrivateGetPrintersFunction::ReturnResult, this, base::Owned(result.release()))); } -bool CloudPrintGetPrintersFunction::RunImpl() { +bool CloudPrintPrivateGetPrintersFunction::RunImpl() { content::BrowserThread::GetBlockingPool()->PostTask(FROM_HERE, - base::Bind(&CloudPrintGetPrintersFunction::CollectPrinters, this)); + base::Bind(&CloudPrintPrivateGetPrintersFunction::CollectPrinters, this)); return true; } diff --git a/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h b/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h index 2a23b9e..030bf67 100644 --- a/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h +++ b/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h @@ -36,40 +36,40 @@ class CloudPrintTestsDelegate { static CloudPrintTestsDelegate* instance_; }; -class CloudPrintSetupConnectorFunction : public AsyncExtensionFunction { +class CloudPrintPrivateSetupConnectorFunction : public AsyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("cloudPrintPrivate.setupConnector"); - CloudPrintSetupConnectorFunction(); + CloudPrintPrivateSetupConnectorFunction(); protected: - virtual ~CloudPrintSetupConnectorFunction(); + virtual ~CloudPrintPrivateSetupConnectorFunction(); // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class CloudPrintGetHostNameFunction : public AsyncExtensionFunction { +class CloudPrintPrivateGetHostNameFunction : public AsyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("cloudPrintPrivate.getHostName"); - CloudPrintGetHostNameFunction(); + CloudPrintPrivateGetHostNameFunction(); protected: - virtual ~CloudPrintGetHostNameFunction(); + virtual ~CloudPrintPrivateGetHostNameFunction(); // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class CloudPrintGetPrintersFunction : public AsyncExtensionFunction { +class CloudPrintPrivateGetPrintersFunction : public AsyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("cloudPrintPrivate.getPrinters"); - CloudPrintGetPrintersFunction(); + CloudPrintPrivateGetPrintersFunction(); protected: - virtual ~CloudPrintGetPrintersFunction(); + virtual ~CloudPrintPrivateGetPrintersFunction(); void CollectPrinters(); void ReturnResult(const base::ListValue* printers); diff --git a/chrome/browser/extensions/api/content_settings/content_settings_api.cc b/chrome/browser/extensions/api/content_settings/content_settings_api.cc index 87c1798..e1c4a08 100644 --- a/chrome/browser/extensions/api/content_settings/content_settings_api.cc +++ b/chrome/browser/extensions/api/content_settings/content_settings_api.cc @@ -62,7 +62,7 @@ namespace extensions { namespace helpers = content_settings_helpers; namespace keys = content_settings_api_constants; -bool ClearContentSettingsFunction::RunImpl() { +bool ContentSettingsClearFunction::RunImpl() { ContentSettingsType content_type; EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); @@ -96,7 +96,7 @@ bool ClearContentSettingsFunction::RunImpl() { return true; } -bool GetContentSettingFunction::RunImpl() { +bool ContentSettingsGetFunction::RunImpl() { ContentSettingsType content_type; EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); @@ -169,7 +169,7 @@ bool GetContentSettingFunction::RunImpl() { return true; } -bool SetContentSettingFunction::RunImpl() { +bool ContentSettingsSetFunction::RunImpl() { ContentSettingsType content_type; EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); @@ -250,7 +250,7 @@ bool SetContentSettingFunction::RunImpl() { return true; } -bool GetResourceIdentifiersFunction::RunImpl() { +bool ContentSettingsGetResourceIdentifiersFunction::RunImpl() { ContentSettingsType content_type; EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); @@ -261,14 +261,15 @@ bool GetResourceIdentifiersFunction::RunImpl() { if (!g_testing_plugins_) { PluginService::GetInstance()->GetPlugins( - base::Bind(&GetResourceIdentifiersFunction::OnGotPlugins, this)); + base::Bind(&ContentSettingsGetResourceIdentifiersFunction::OnGotPlugins, + this)); } else { OnGotPlugins(*g_testing_plugins_); } return true; } -void GetResourceIdentifiersFunction::OnGotPlugins( +void ContentSettingsGetResourceIdentifiersFunction::OnGotPlugins( const std::vector<webkit::WebPluginInfo>& plugins) { PluginFinder* finder = PluginFinder::GetInstance(); std::set<std::string> group_identifiers; @@ -289,11 +290,13 @@ void GetResourceIdentifiersFunction::OnGotPlugins( SetResult(list); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( - &GetResourceIdentifiersFunction::SendResponse, this, true)); + &ContentSettingsGetResourceIdentifiersFunction::SendResponse, + this, + true)); } // static -void GetResourceIdentifiersFunction::SetPluginsForTesting( +void ContentSettingsGetResourceIdentifiersFunction::SetPluginsForTesting( const std::vector<webkit::WebPluginInfo>* plugins) { g_testing_plugins_ = plugins; } diff --git a/chrome/browser/extensions/api/content_settings/content_settings_api.h b/chrome/browser/extensions/api/content_settings/content_settings_api.h index 20ffcc7..aac0b81 100644 --- a/chrome/browser/extensions/api/content_settings/content_settings_api.h +++ b/chrome/browser/extensions/api/content_settings/content_settings_api.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_EXTENSIONS_API_CONTENT_SETTINGS_CONTENT_SETTINGS_API_H__ -#define CHROME_BROWSER_EXTENSIONS_API_CONTENT_SETTINGS_CONTENT_SETTINGS_API_H__ +#ifndef CHROME_BROWSER_EXTENSIONS_API_CONTENT_SETTINGS_CONTENT_SETTINGS_API_H_ +#define CHROME_BROWSER_EXTENSIONS_API_CONTENT_SETTINGS_CONTENT_SETTINGS_API_H_ #include "chrome/browser/extensions/extension_function.h" @@ -15,45 +15,46 @@ struct WebPluginInfo; namespace extensions { -class ClearContentSettingsFunction : public SyncExtensionFunction { +class ContentSettingsClearFunction : public SyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("contentSettings.clear") protected: - virtual ~ClearContentSettingsFunction() {} + virtual ~ContentSettingsClearFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class GetContentSettingFunction : public SyncExtensionFunction { +class ContentSettingsGetFunction : public SyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("contentSettings.get") protected: - virtual ~GetContentSettingFunction() {} + virtual ~ContentSettingsGetFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class SetContentSettingFunction : public SyncExtensionFunction { +class ContentSettingsSetFunction : public SyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("contentSettings.set") protected: - virtual ~SetContentSettingFunction() {} + virtual ~ContentSettingsSetFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class GetResourceIdentifiersFunction : public AsyncExtensionFunction { +class ContentSettingsGetResourceIdentifiersFunction + : public AsyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("contentSettings.getResourceIdentifiers") protected: - virtual ~GetResourceIdentifiersFunction() {} + virtual ~ContentSettingsGetResourceIdentifiersFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; @@ -73,4 +74,4 @@ class GetResourceIdentifiersFunction : public AsyncExtensionFunction { } // namespace extensions -#endif // CHROME_BROWSER_EXTENSIONS_API_CONTENT_SETTINGS_CONTENT_SETTINGS_API_H__ +#endif // CHROME_BROWSER_EXTENSIONS_API_CONTENT_SETTINGS_CONTENT_SETTINGS_API_H_ diff --git a/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc b/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc index 69227d1..381346e 100644 --- a/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc +++ b/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc @@ -3,9 +3,9 @@ // found in the LICENSE file. #include "base/utf_string_conversions.h" -#include "chrome/browser/extensions/api/content_settings/content_settings_api.h" #include "chrome/browser/content_settings/cookie_settings.h" #include "chrome/browser/content_settings/host_content_settings_map.h" +#include "chrome/browser/extensions/api/content_settings/content_settings_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" @@ -120,12 +120,12 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, std::vector<webkit::WebPluginInfo> plugins; plugin_list.GetPlugins(&plugins); - GetResourceIdentifiersFunction::SetPluginsForTesting(&plugins); + ContentSettingsGetResourceIdentifiersFunction::SetPluginsForTesting(&plugins); EXPECT_TRUE(RunExtensionTest("content_settings/getresourceidentifiers")) << message_; - GetResourceIdentifiersFunction::SetPluginsForTesting(NULL); + ContentSettingsGetResourceIdentifiersFunction::SetPluginsForTesting(NULL); } } // namespace extensions diff --git a/chrome/browser/extensions/api/context_menu/context_menu_api.cc b/chrome/browser/extensions/api/context_menu/context_menu_api.cc deleted file mode 100644 index 0d98897..0000000 --- a/chrome/browser/extensions/api/context_menu/context_menu_api.cc +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright (c) 2012 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/extensions/api/context_menu/context_menu_api.h" - -#include <string> - -#include "base/string_number_conversions.h" -#include "base/string_util.h" -#include "base/values.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/menu_manager.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/extensions/api/context_menus.h" -#include "extensions/common/error_utils.h" -#include "extensions/common/url_pattern_set.h" - -using extensions::ErrorUtils; - -namespace { - -const char kGeneratedIdKey[] = "generatedId"; - -const char kCannotFindItemError[] = "Cannot find menu item with id *"; -const char kOnclickDisallowedError[] = "Extensions using event pages cannot " - "pass an onclick parameter to chrome.contextMenus.create. Instead, use " - "the chrome.contextMenus.onClicked event."; -const char kCheckedError[] = - "Only items with type \"radio\" or \"checkbox\" can be checked"; -const char kDuplicateIDError[] = - "Cannot create item with duplicate id *"; -const char kIdRequiredError[] = "Extensions using event pages must pass an " - "id parameter to chrome.contextMenus.create"; -const char kParentsMustBeNormalError[] = - "Parent items must have type \"normal\""; -const char kTitleNeededError[] = - "All menu items except for separators must have a title"; -const char kLauncherNotAllowedError[] = - "Only packaged apps are allowed to use 'launcher' context"; - -std::string GetIDString(const extensions::MenuItem::Id& id) { - if (id.uid == 0) - return id.string_uid; - else - return base::IntToString(id.uid); -} - -template<typename PropertyWithEnumT> -extensions::MenuItem::ContextList GetContexts( - const PropertyWithEnumT& property) { - extensions::MenuItem::ContextList contexts; - for (size_t i = 0; i < property.contexts->size(); ++i) { - switch (property.contexts->at(i)) { - case PropertyWithEnumT::CONTEXTS_ELEMENT_ALL: - contexts.Add(extensions::MenuItem::ALL); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_PAGE: - contexts.Add(extensions::MenuItem::PAGE); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_SELECTION: - contexts.Add(extensions::MenuItem::SELECTION); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_LINK: - contexts.Add(extensions::MenuItem::LINK); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_EDITABLE: - contexts.Add(extensions::MenuItem::EDITABLE); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_IMAGE: - contexts.Add(extensions::MenuItem::IMAGE); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_VIDEO: - contexts.Add(extensions::MenuItem::VIDEO); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_AUDIO: - contexts.Add(extensions::MenuItem::AUDIO); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_FRAME: - contexts.Add(extensions::MenuItem::FRAME); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_LAUNCHER: - contexts.Add(extensions::MenuItem::LAUNCHER); - break; - case PropertyWithEnumT::CONTEXTS_ELEMENT_NONE: - NOTREACHED(); - } - } - return contexts; -} - -template<typename PropertyWithEnumT> -extensions::MenuItem::Type GetType(const PropertyWithEnumT& property) { - switch (property.type) { - case PropertyWithEnumT::TYPE_NONE: - case PropertyWithEnumT::TYPE_NORMAL: - return extensions::MenuItem::NORMAL; - case PropertyWithEnumT::TYPE_CHECKBOX: - return extensions::MenuItem::CHECKBOX; - case PropertyWithEnumT::TYPE_RADIO: - return extensions::MenuItem::RADIO; - case PropertyWithEnumT::TYPE_SEPARATOR: - return extensions::MenuItem::SEPARATOR; - } - return extensions::MenuItem::NORMAL; -} - -template<typename PropertyWithEnumT> -scoped_ptr<extensions::MenuItem::Id> GetParentId( - const PropertyWithEnumT& property, - bool is_off_the_record, - std::string extension_id) { - scoped_ptr<extensions::MenuItem::Id> parent_id( - new extensions::MenuItem::Id(is_off_the_record, extension_id)); - switch (property.parent_id_type) { - case PropertyWithEnumT::PARENT_ID_NONE: - return scoped_ptr<extensions::MenuItem::Id>().Pass(); - case PropertyWithEnumT::PARENT_ID_INTEGER: - parent_id->uid = *property.parent_id_integer; - break; - case PropertyWithEnumT::PARENT_ID_STRING: - parent_id->string_uid = *property.parent_id_string; - break; - } - return parent_id.Pass(); -} - -extensions::MenuItem* GetParent(extensions::MenuItem::Id parent_id, - const extensions::MenuManager* menu_manager, - std::string* error) { - extensions::MenuItem* parent = menu_manager->GetItemById(parent_id); - if (!parent) { - *error = ErrorUtils::FormatErrorMessage( - kCannotFindItemError, GetIDString(parent_id)); - return NULL; - } - if (parent->type() != extensions::MenuItem::NORMAL) { - *error = kParentsMustBeNormalError; - return NULL; - } - - return parent; -} - -} // namespace - -namespace extensions { - -namespace Create = api::context_menus::Create; -namespace Remove = api::context_menus::Remove; -namespace Update = api::context_menus::Update; - -bool CreateContextMenuFunction::RunImpl() { - MenuItem::Id id(profile()->IsOffTheRecord(), extension_id()); - scoped_ptr<Create::Params> params(Create::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - if (params->create_properties.id.get()) { - id.string_uid = *params->create_properties.id; - } else { - if (GetExtension()->has_lazy_background_page()) { - error_ = kIdRequiredError; - return false; - } - - // The Generated Id is added by context_menus_custom_bindings.js. - DictionaryValue* properties = NULL; - EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &properties)); - EXTENSION_FUNCTION_VALIDATE(properties->GetInteger(kGeneratedIdKey, - &id.uid)); - } - - std::string title; - if (params->create_properties.title.get()) - title = *params->create_properties.title; - - MenuManager* menu_manager = profile()->GetExtensionService()->menu_manager(); - - if (menu_manager->GetItemById(id)) { - error_ = ErrorUtils::FormatErrorMessage(kDuplicateIDError, - GetIDString(id)); - return false; - } - - if (GetExtension()->has_lazy_background_page() && - params->create_properties.onclick.get()) { - error_ = kOnclickDisallowedError; - return false; - } - - MenuItem::ContextList contexts; - if (params->create_properties.contexts.get()) - contexts = GetContexts(params->create_properties); - else - contexts.Add(MenuItem::PAGE); - - if (contexts.Contains(MenuItem::LAUNCHER) && - !GetExtension()->is_platform_app()) { - error_ = kLauncherNotAllowedError; - return false; - } - - MenuItem::Type type = GetType(params->create_properties); - - if (title.empty() && type != MenuItem::SEPARATOR) { - error_ = kTitleNeededError; - return false; - } - - bool checked = false; - if (params->create_properties.checked.get()) - checked = *params->create_properties.checked; - - bool enabled = true; - if (params->create_properties.enabled.get()) - enabled = *params->create_properties.enabled; - - scoped_ptr<MenuItem> item( - new MenuItem(id, title, checked, enabled, type, contexts)); - - if (!item->PopulateURLPatterns( - params->create_properties.document_url_patterns.get(), - params->create_properties.target_url_patterns.get(), - &error_)) { - return false; - } - - bool success = true; - scoped_ptr<MenuItem::Id> parent_id(GetParentId(params->create_properties, - profile()->IsOffTheRecord(), - extension_id())); - if (parent_id.get()) { - MenuItem* parent = GetParent(*parent_id, menu_manager, &error_); - if (!parent) - return false; - success = menu_manager->AddChildItem(parent->id(), item.release()); - } else { - success = menu_manager->AddContextItem(GetExtension(), item.release()); - } - - if (!success) - return false; - - menu_manager->WriteToStorage(GetExtension()); - return true; -} - -bool UpdateContextMenuFunction::RunImpl() { - bool radio_item_updated = false; - MenuItem::Id item_id(profile()->IsOffTheRecord(), extension_id()); - scoped_ptr<Update::Params> params(Update::Params::Create(*args_)); - - EXTENSION_FUNCTION_VALIDATE(params.get()); - switch (params->id_type) { - case Update::Params::ID_STRING: - item_id.string_uid = *params->id_string; - break; - case Update::Params::ID_INTEGER: - item_id.uid = *params->id_integer; - break; - case Update::Params::ID_NONE: - NOTREACHED(); - } - - ExtensionService* service = profile()->GetExtensionService(); - MenuManager* manager = service->menu_manager(); - MenuItem* item = manager->GetItemById(item_id); - if (!item || item->extension_id() != extension_id()) { - error_ = ErrorUtils::FormatErrorMessage( - kCannotFindItemError, GetIDString(item_id)); - return false; - } - - // Type. - MenuItem::Type type = GetType(params->update_properties); - - if (type != item->type()) { - if (type == MenuItem::RADIO || item->type() == MenuItem::RADIO) - radio_item_updated = true; - item->set_type(type); - } - - // Title. - if (params->update_properties.title.get()) { - std::string title(*params->update_properties.title); - if (title.empty() && item->type() != MenuItem::SEPARATOR) { - error_ = kTitleNeededError; - return false; - } - item->set_title(title); - } - - // Checked state. - if (params->update_properties.checked.get()) { - bool checked = *params->update_properties.checked; - if (checked && - item->type() != MenuItem::CHECKBOX && - item->type() != MenuItem::RADIO) { - error_ = kCheckedError; - return false; - } - if (checked != item->checked()) { - if (!item->SetChecked(checked)) { - error_ = kCheckedError; - return false; - } - radio_item_updated = true; - } - } - - // Enabled. - if (params->update_properties.enabled.get()) - item->set_enabled(*params->update_properties.enabled); - - // Contexts. - MenuItem::ContextList contexts; - if (params->update_properties.contexts.get()) { - contexts = GetContexts(params->update_properties); - - if (contexts.Contains(MenuItem::LAUNCHER) && - !GetExtension()->is_platform_app()) { - error_ = kLauncherNotAllowedError; - return false; - } - - if (contexts != item->contexts()) - item->set_contexts(contexts); - } - - // Parent id. - MenuItem* parent = NULL; - scoped_ptr<MenuItem::Id> parent_id(GetParentId(params->update_properties, - profile()->IsOffTheRecord(), - extension_id())); - if (parent_id.get()) { - MenuItem* parent = GetParent(*parent_id, manager, &error_); - if (!parent || !manager->ChangeParent(item->id(), &parent->id())) - return false; - } - - // URL Patterns. - if (!item->PopulateURLPatterns( - params->update_properties.document_url_patterns.get(), - params->update_properties.target_url_patterns.get(), &error_)) { - return false; - } - - // There is no need to call ItemUpdated if ChangeParent is called because - // all sanitation is taken care of in ChangeParent. - if (!parent && radio_item_updated && !manager->ItemUpdated(item->id())) - return false; - - manager->WriteToStorage(GetExtension()); - return true; -} - -bool RemoveContextMenuFunction::RunImpl() { - scoped_ptr<Remove::Params> params(Remove::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - ExtensionService* service = profile()->GetExtensionService(); - MenuManager* manager = service->menu_manager(); - - MenuItem::Id id(profile()->IsOffTheRecord(), extension_id()); - switch (params->menu_item_id_type) { - case Remove::Params::MENU_ITEM_ID_STRING: - id.string_uid = *params->menu_item_id_string; - break; - case Remove::Params::MENU_ITEM_ID_INTEGER: - id.uid = *params->menu_item_id_integer; - break; - case Remove::Params::MENU_ITEM_ID_NONE: - NOTREACHED(); - } - - MenuItem* item = manager->GetItemById(id); - // Ensure one extension can't remove another's menu items. - if (!item || item->extension_id() != extension_id()) { - error_ = ErrorUtils::FormatErrorMessage( - kCannotFindItemError, GetIDString(id)); - return false; - } - - if (!manager->RemoveContextMenuItem(id)) - return false; - manager->WriteToStorage(GetExtension()); - return true; -} - -bool RemoveAllContextMenusFunction::RunImpl() { - ExtensionService* service = profile()->GetExtensionService(); - MenuManager* manager = service->menu_manager(); - manager->RemoveAllContextItems(GetExtension()->id()); - manager->WriteToStorage(GetExtension()); - return true; -} - -} // namespace extensions diff --git a/chrome/browser/extensions/api/context_menu/context_menu_api.h b/chrome/browser/extensions/api/context_menu/context_menu_api.h deleted file mode 100644 index 5f15c92..0000000 --- a/chrome/browser/extensions/api/context_menu/context_menu_api.h +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_CONTEXT_MENU_CONTEXT_MENU_API_H__ -#define CHROME_BROWSER_EXTENSIONS_API_CONTEXT_MENU_CONTEXT_MENU_API_H__ - -#include "chrome/browser/extensions/extension_function.h" - -namespace extensions { - -class CreateContextMenuFunction : public SyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION_NAME("contextMenus.create") - - protected: - virtual ~CreateContextMenuFunction() {} - - // ExtensionFunction: - virtual bool RunImpl() OVERRIDE; -}; - -class UpdateContextMenuFunction : public SyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION_NAME("contextMenus.update") - - protected: - virtual ~UpdateContextMenuFunction() {} - - // ExtensionFunction: - virtual bool RunImpl() OVERRIDE; -}; - -class RemoveContextMenuFunction : public SyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION_NAME("contextMenus.remove") - - protected: - virtual ~RemoveContextMenuFunction() {} - - // ExtensionFunction: - virtual bool RunImpl() OVERRIDE; -}; - -class RemoveAllContextMenusFunction : public SyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION_NAME("contextMenus.removeAll") - - protected: - virtual ~RemoveAllContextMenusFunction() {} - - // ExtensionFunction: - virtual bool RunImpl() OVERRIDE; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_CONTEXT_MENU_CONTEXT_MENU_API_H__ diff --git a/chrome/browser/extensions/api/context_menu/context_menu_apitest.cc b/chrome/browser/extensions/api/context_menu/context_menu_apitest.cc deleted file mode 100644 index 85d2441..0000000 --- a/chrome/browser/extensions/api/context_menu/context_menu_apitest.cc +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2012 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/extensions/extension_action.h" -#include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/test/base/ui_test_utils.h" - -namespace extensions { - -// Times out on win asan, http://crbug.com/166026 -#if defined(OS_WIN) && defined(ADDRESS_SANITIZER) -#define MAYBE_ContextMenus DISABLED_ContextMenus -#else -#define MAYBE_ContextMenus ContextMenus -#endif -IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_ContextMenus) { - ASSERT_TRUE(RunExtensionTest("context_menus/basics")) << message_; - ASSERT_TRUE(RunExtensionTest("context_menus/no_perms")) << message_; - ASSERT_TRUE(RunExtensionTest("context_menus/item_ids")) << message_; - ASSERT_TRUE(RunExtensionTest("context_menus/event_page")) << message_; -} - -// crbug.com/51436 -- creating context menus from multiple script contexts -// should work. -IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ContextMenusFromMultipleContexts) { - ASSERT_TRUE(test_server()->Start()); - ASSERT_TRUE(RunExtensionTest("context_menus/add_from_multiple_contexts")) - << message_; - const extensions::Extension* extension = GetSingleLoadedExtension(); - ASSERT_TRUE(extension) << message_; - - { - // Tell the extension to update the page action state. - ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - extension->GetResourceURL("popup.html")); - ASSERT_TRUE(catcher.GetNextResult()); - } - - { - // Tell the extension to update the page action state again. - ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - extension->GetResourceURL("popup2.html")); - ASSERT_TRUE(catcher.GetNextResult()); - } -} - -} // namespace extensions diff --git a/chrome/browser/extensions/api/debugger/debugger_api.cc b/chrome/browser/extensions/api/debugger/debugger_api.cc index 79b28b7..d672af7 100644 --- a/chrome/browser/extensions/api/debugger/debugger_api.cc +++ b/chrome/browser/extensions/api/debugger/debugger_api.cc @@ -104,7 +104,7 @@ class ExtensionDevToolsClientHost : public DevToolsClientHost, bool MatchesContentsAndExtensionId(WebContents* web_contents, const std::string& extension_id); void Close(); - void SendMessageToBackend(SendCommandDebuggerFunction* function, + void SendMessageToBackend(DebuggerSendCommandFunction* function, const std::string& method, SendCommand::Params::CommandParams* command_params); @@ -129,7 +129,7 @@ class ExtensionDevToolsClientHost : public DevToolsClientHost, int tab_id_; content::NotificationRegistrar registrar_; int last_request_id_; - typedef std::map<int, scoped_refptr<SendCommandDebuggerFunction> > + typedef std::map<int, scoped_refptr<DebuggerSendCommandFunction> > PendingRequests; PendingRequests pending_requests_; ExtensionDevToolsInfoBarDelegate* infobar_delegate_; @@ -249,7 +249,7 @@ void ExtensionDevToolsClientHost::Close() { } void ExtensionDevToolsClientHost::SendMessageToBackend( - SendCommandDebuggerFunction* function, + DebuggerSendCommandFunction* function, const std::string& method, SendCommand::Params::CommandParams* command_params) { DictionaryValue protocol_request; @@ -343,7 +343,7 @@ void ExtensionDevToolsClientHost::DispatchOnInspectorFrontend( extensions::ExtensionSystem::Get(profile)->event_router()-> DispatchEventToExtension(extension_id_, event.Pass()); } else { - SendCommandDebuggerFunction* function = pending_requests_[id]; + DebuggerSendCommandFunction* function = pending_requests_[id]; if (!function) return; @@ -457,11 +457,11 @@ bool DebuggerFunction::InitClientHost() { return true; } -AttachDebuggerFunction::AttachDebuggerFunction() {} +DebuggerAttachFunction::DebuggerAttachFunction() {} -AttachDebuggerFunction::~AttachDebuggerFunction() {} +DebuggerAttachFunction::~DebuggerAttachFunction() {} -bool AttachDebuggerFunction::RunImpl() { +bool DebuggerAttachFunction::RunImpl() { scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -497,11 +497,11 @@ bool AttachDebuggerFunction::RunImpl() { return true; } -DetachDebuggerFunction::DetachDebuggerFunction() {} +DebuggerDetachFunction::DebuggerDetachFunction() {} -DetachDebuggerFunction::~DetachDebuggerFunction() {} +DebuggerDetachFunction::~DebuggerDetachFunction() {} -bool DetachDebuggerFunction::RunImpl() { +bool DebuggerDetachFunction::RunImpl() { scoped_ptr<Detach::Params> params(Detach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -514,11 +514,11 @@ bool DetachDebuggerFunction::RunImpl() { return true; } -SendCommandDebuggerFunction::SendCommandDebuggerFunction() {} +DebuggerSendCommandFunction::DebuggerSendCommandFunction() {} -SendCommandDebuggerFunction::~SendCommandDebuggerFunction() {} +DebuggerSendCommandFunction::~DebuggerSendCommandFunction() {} -bool SendCommandDebuggerFunction::RunImpl() { +bool DebuggerSendCommandFunction::RunImpl() { scoped_ptr<SendCommand::Params> params(SendCommand::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -531,7 +531,7 @@ bool SendCommandDebuggerFunction::RunImpl() { return true; } -void SendCommandDebuggerFunction::SendResponseBody( +void DebuggerSendCommandFunction::SendResponseBody( DictionaryValue* response) { Value* error_body; if (response->Get("error", &error_body)) { diff --git a/chrome/browser/extensions/api/debugger/debugger_api.h b/chrome/browser/extensions/api/debugger/debugger_api.h index 36b0cb5..44243d9 100644 --- a/chrome/browser/extensions/api/debugger/debugger_api.h +++ b/chrome/browser/extensions/api/debugger/debugger_api.h @@ -39,43 +39,43 @@ class DebuggerFunction : public AsyncExtensionFunction { }; // Implements the debugger.attach() extension function. -class AttachDebuggerFunction : public DebuggerFunction { +class DebuggerAttachFunction : public DebuggerFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("debugger.attach") - AttachDebuggerFunction(); + DebuggerAttachFunction(); protected: - virtual ~AttachDebuggerFunction(); + virtual ~DebuggerAttachFunction(); // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; // Implements the debugger.detach() extension function. -class DetachDebuggerFunction : public DebuggerFunction { +class DebuggerDetachFunction : public DebuggerFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("debugger.detach") - DetachDebuggerFunction(); + DebuggerDetachFunction(); protected: - virtual ~DetachDebuggerFunction(); + virtual ~DebuggerDetachFunction(); // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; // Implements the debugger.sendCommand() extension function. -class SendCommandDebuggerFunction : public DebuggerFunction { +class DebuggerSendCommandFunction : public DebuggerFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("debugger.sendCommand") - SendCommandDebuggerFunction(); + DebuggerSendCommandFunction(); void SendResponseBody(base::DictionaryValue* result); protected: - virtual ~SendCommandDebuggerFunction(); + virtual ~DebuggerSendCommandFunction(); // ExtensionFunction: virtual bool RunImpl() OVERRIDE; diff --git a/chrome/browser/extensions/api/declarative/declarative_api.cc b/chrome/browser/extensions/api/declarative/declarative_api.cc index 57cd0e8..8c57352 100644 --- a/chrome/browser/extensions/api/declarative/declarative_api.cc +++ b/chrome/browser/extensions/api/declarative/declarative_api.cc @@ -61,7 +61,7 @@ bool RulesFunction::RunImpl() { return true; } -bool AddRulesFunction::RunImplOnCorrectThread() { +bool EventsAddRulesFunction::RunImplOnCorrectThread() { scoped_ptr<AddRules::Params> params(AddRules::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -73,7 +73,7 @@ bool AddRulesFunction::RunImplOnCorrectThread() { return error_.empty(); } -bool RemoveRulesFunction::RunImplOnCorrectThread() { +bool EventsRemoveRulesFunction::RunImplOnCorrectThread() { scoped_ptr<RemoveRules::Params> params(RemoveRules::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -87,7 +87,7 @@ bool RemoveRulesFunction::RunImplOnCorrectThread() { return error_.empty(); } -bool GetRulesFunction::RunImplOnCorrectThread() { +bool EventsGetRulesFunction::RunImplOnCorrectThread() { scoped_ptr<GetRules::Params> params(GetRules::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); diff --git a/chrome/browser/extensions/api/declarative/declarative_api.h b/chrome/browser/extensions/api/declarative/declarative_api.h index 5f7acc0..5caf4ac 100644 --- a/chrome/browser/extensions/api/declarative/declarative_api.h +++ b/chrome/browser/extensions/api/declarative/declarative_api.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_EXTENSIONS_API_DECLARATIVE_DECLARATIVE_API_H__ -#define CHROME_BROWSER_EXTENSIONS_API_DECLARATIVE_DECLARATIVE_API_H__ +#ifndef CHROME_BROWSER_EXTENSIONS_API_DECLARATIVE_DECLARATIVE_API_H_ +#define CHROME_BROWSER_EXTENSIONS_API_DECLARATIVE_DECLARATIVE_API_H_ #include "base/compiler_specific.h" #include "base/memory/ref_counted.h" @@ -31,34 +31,34 @@ class RulesFunction : public AsyncExtensionFunction { scoped_refptr<RulesRegistry> rules_registry_; }; -class AddRulesFunction : public RulesFunction { +class EventsAddRulesFunction : public RulesFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("events.addRules"); protected: - virtual ~AddRulesFunction() {} + virtual ~EventsAddRulesFunction() {} // RulesFunction: virtual bool RunImplOnCorrectThread() OVERRIDE; }; -class RemoveRulesFunction : public RulesFunction { +class EventsRemoveRulesFunction : public RulesFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("events.removeRules"); protected: - virtual ~RemoveRulesFunction() {} + virtual ~EventsRemoveRulesFunction() {} // RulesFunction: virtual bool RunImplOnCorrectThread() OVERRIDE; }; -class GetRulesFunction : public RulesFunction { +class EventsGetRulesFunction : public RulesFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("events.getRules"); protected: - virtual ~GetRulesFunction() {} + virtual ~EventsGetRulesFunction() {} // RulesFunction: virtual bool RunImplOnCorrectThread() OVERRIDE; @@ -66,4 +66,4 @@ class GetRulesFunction : public RulesFunction { } // namespace extensions -#endif // CHROME_BROWSER_EXTENSIONS_API_DECLARATIVE_DECLARATIVE_API_H__ +#endif // CHROME_BROWSER_EXTENSIONS_API_DECLARATIVE_DECLARATIVE_API_H_ diff --git a/chrome/browser/extensions/api/font_settings/font_settings_api.cc b/chrome/browser/extensions/api/font_settings/font_settings_api.cc index 802c625..7aeec6f 100644 --- a/chrome/browser/extensions/api/font_settings/font_settings_api.cc +++ b/chrome/browser/extensions/api/font_settings/font_settings_api.cc @@ -217,7 +217,7 @@ FontSettingsAPI::FontSettingsAPI(Profile* profile) FontSettingsAPI::~FontSettingsAPI() { } -bool ClearFontFunction::RunImpl() { +bool FontSettingsClearFontFunction::RunImpl() { if (profile_->IsOffTheRecord()) { error_ = kSetFromIncognitoError; return false; @@ -242,7 +242,7 @@ bool ClearFontFunction::RunImpl() { return true; } -bool GetFontFunction::RunImpl() { +bool FontSettingsGetFontFunction::RunImpl() { scoped_ptr<fonts::GetFont::Params> params( fonts::GetFont::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -275,7 +275,7 @@ bool GetFontFunction::RunImpl() { return true; } -bool SetFontFunction::RunImpl() { +bool FontSettingsSetFontFunction::RunImpl() { if (profile_->IsOffTheRecord()) { error_ = kSetFromIncognitoError; return false; @@ -302,18 +302,19 @@ bool SetFontFunction::RunImpl() { return true; } -bool GetFontListFunction::RunImpl() { +bool FontSettingsGetFontListFunction::RunImpl() { content::GetFontListAsync( - Bind(&GetFontListFunction::FontListHasLoaded, this)); + Bind(&FontSettingsGetFontListFunction::FontListHasLoaded, this)); return true; } -void GetFontListFunction::FontListHasLoaded(scoped_ptr<ListValue> list) { +void FontSettingsGetFontListFunction::FontListHasLoaded( + scoped_ptr<ListValue> list) { bool success = CopyFontsToResult(list.get()); SendResponse(success); } -bool GetFontListFunction::CopyFontsToResult(ListValue* fonts) { +bool FontSettingsGetFontListFunction::CopyFontsToResult(ListValue* fonts) { scoped_ptr<ListValue> result(new ListValue()); for (ListValue::iterator it = fonts->begin(); it != fonts->end(); ++it) { ListValue* font_list_value; @@ -401,63 +402,63 @@ bool SetFontPrefExtensionFunction::RunImpl() { return true; } -const char* ClearDefaultFontSizeFunction::GetPrefName() { +const char* FontSettingsClearDefaultFontSizeFunction::GetPrefName() { return prefs::kWebKitDefaultFontSize; } -const char* GetDefaultFontSizeFunction::GetPrefName() { +const char* FontSettingsGetDefaultFontSizeFunction::GetPrefName() { return prefs::kWebKitDefaultFontSize; } -const char* GetDefaultFontSizeFunction::GetKey() { +const char* FontSettingsGetDefaultFontSizeFunction::GetKey() { return kPixelSizeKey; } -const char* SetDefaultFontSizeFunction::GetPrefName() { +const char* FontSettingsSetDefaultFontSizeFunction::GetPrefName() { return prefs::kWebKitDefaultFontSize; } -const char* SetDefaultFontSizeFunction::GetKey() { +const char* FontSettingsSetDefaultFontSizeFunction::GetKey() { return kPixelSizeKey; } -const char* ClearDefaultFixedFontSizeFunction::GetPrefName() { +const char* FontSettingsClearDefaultFixedFontSizeFunction::GetPrefName() { return prefs::kWebKitDefaultFixedFontSize; } -const char* GetDefaultFixedFontSizeFunction::GetPrefName() { +const char* FontSettingsGetDefaultFixedFontSizeFunction::GetPrefName() { return prefs::kWebKitDefaultFixedFontSize; } -const char* GetDefaultFixedFontSizeFunction::GetKey() { +const char* FontSettingsGetDefaultFixedFontSizeFunction::GetKey() { return kPixelSizeKey; } -const char* SetDefaultFixedFontSizeFunction::GetPrefName() { +const char* FontSettingsSetDefaultFixedFontSizeFunction::GetPrefName() { return prefs::kWebKitDefaultFixedFontSize; } -const char* SetDefaultFixedFontSizeFunction::GetKey() { +const char* FontSettingsSetDefaultFixedFontSizeFunction::GetKey() { return kPixelSizeKey; } -const char* ClearMinimumFontSizeFunction::GetPrefName() { +const char* FontSettingsClearMinimumFontSizeFunction::GetPrefName() { return prefs::kWebKitMinimumFontSize; } -const char* GetMinimumFontSizeFunction::GetPrefName() { +const char* FontSettingsGetMinimumFontSizeFunction::GetPrefName() { return prefs::kWebKitMinimumFontSize; } -const char* GetMinimumFontSizeFunction::GetKey() { +const char* FontSettingsGetMinimumFontSizeFunction::GetKey() { return kPixelSizeKey; } -const char* SetMinimumFontSizeFunction::GetPrefName() { +const char* FontSettingsSetMinimumFontSizeFunction::GetPrefName() { return prefs::kWebKitMinimumFontSize; } -const char* SetMinimumFontSizeFunction::GetKey() { +const char* FontSettingsSetMinimumFontSizeFunction::GetKey() { return kPixelSizeKey; } diff --git a/chrome/browser/extensions/api/font_settings/font_settings_api.h b/chrome/browser/extensions/api/font_settings/font_settings_api.h index e4d2cb0..3920ca8 100644 --- a/chrome/browser/extensions/api/font_settings/font_settings_api.h +++ b/chrome/browser/extensions/api/font_settings/font_settings_api.h @@ -5,8 +5,8 @@ // Defines the classes to realize the Font Settings Extension API as specified // in the extension API JSON. -#ifndef CHROME_BROWSER_EXTENSIONS_API_FONT_SETTINGS_FONT_SETTINGS_API_H__ -#define CHROME_BROWSER_EXTENSIONS_API_FONT_SETTINGS_FONT_SETTINGS_API_H__ +#ifndef CHROME_BROWSER_EXTENSIONS_API_FONT_SETTINGS_FONT_SETTINGS_API_H_ +#define CHROME_BROWSER_EXTENSIONS_API_FONT_SETTINGS_FONT_SETTINGS_API_H_ #include <string> @@ -80,50 +80,50 @@ class FontSettingsAPI : public ProfileKeyedService { }; // fontSettings.clearFont API function. -class ClearFontFunction : public SyncExtensionFunction { +class FontSettingsClearFontFunction : public SyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.clearFont") protected: // RefCounted types have non-public destructors, as with all extension // functions in this file. - virtual ~ClearFontFunction() {} + virtual ~FontSettingsClearFontFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; // fontSettings.getFont API function. -class GetFontFunction : public SyncExtensionFunction { +class FontSettingsGetFontFunction : public SyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.getFont") protected: - virtual ~GetFontFunction() {} + virtual ~FontSettingsGetFontFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; // fontSettings.setFont API function. -class SetFontFunction : public SyncExtensionFunction { +class FontSettingsSetFontFunction : public SyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.setFont") protected: - virtual ~SetFontFunction() {} + virtual ~FontSettingsSetFontFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; // fontSettings.getFontList API function. -class GetFontListFunction : public AsyncExtensionFunction { +class FontSettingsGetFontListFunction : public AsyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.getFontList") protected: - virtual ~GetFontListFunction() {} + virtual ~FontSettingsGetFontListFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; @@ -183,106 +183,114 @@ class SetFontPrefExtensionFunction : public SyncExtensionFunction { // The following are get/set/clear API functions that act on a browser font // pref. -class ClearDefaultFontSizeFunction : public ClearFontPrefExtensionFunction { +class FontSettingsClearDefaultFontSizeFunction + : public ClearFontPrefExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.clearDefaultFontSize") protected: - virtual ~ClearDefaultFontSizeFunction() {} + virtual ~FontSettingsClearDefaultFontSizeFunction() {} // ClearFontPrefExtensionFunction: virtual const char* GetPrefName() OVERRIDE; }; -class GetDefaultFontSizeFunction : public GetFontPrefExtensionFunction { +class FontSettingsGetDefaultFontSizeFunction + : public GetFontPrefExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.getDefaultFontSize") protected: - virtual ~GetDefaultFontSizeFunction() {} + virtual ~FontSettingsGetDefaultFontSizeFunction() {} // GetFontPrefExtensionFunction: virtual const char* GetPrefName() OVERRIDE; virtual const char* GetKey() OVERRIDE; }; -class SetDefaultFontSizeFunction : public SetFontPrefExtensionFunction { +class FontSettingsSetDefaultFontSizeFunction + : public SetFontPrefExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.setDefaultFontSize") protected: - virtual ~SetDefaultFontSizeFunction() {} + virtual ~FontSettingsSetDefaultFontSizeFunction() {} // SetFontPrefExtensionFunction: virtual const char* GetPrefName() OVERRIDE; virtual const char* GetKey() OVERRIDE; }; -class ClearDefaultFixedFontSizeFunction +class FontSettingsClearDefaultFixedFontSizeFunction : public ClearFontPrefExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.clearDefaultFixedFontSize") protected: - virtual ~ClearDefaultFixedFontSizeFunction() {} + virtual ~FontSettingsClearDefaultFixedFontSizeFunction() {} // ClearFontPrefExtensionFunction: virtual const char* GetPrefName() OVERRIDE; }; -class GetDefaultFixedFontSizeFunction : public GetFontPrefExtensionFunction { +class FontSettingsGetDefaultFixedFontSizeFunction + : public GetFontPrefExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.getDefaultFixedFontSize") protected: - virtual ~GetDefaultFixedFontSizeFunction() {} + virtual ~FontSettingsGetDefaultFixedFontSizeFunction() {} // GetFontPrefExtensionFunction: virtual const char* GetPrefName() OVERRIDE; virtual const char* GetKey() OVERRIDE; }; -class SetDefaultFixedFontSizeFunction : public SetFontPrefExtensionFunction { +class FontSettingsSetDefaultFixedFontSizeFunction + : public SetFontPrefExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.setDefaultFixedFontSize") protected: - virtual ~SetDefaultFixedFontSizeFunction() {} + virtual ~FontSettingsSetDefaultFixedFontSizeFunction() {} // SetFontPrefExtensionFunction: virtual const char* GetPrefName() OVERRIDE; virtual const char* GetKey() OVERRIDE; }; -class ClearMinimumFontSizeFunction : public ClearFontPrefExtensionFunction { +class FontSettingsClearMinimumFontSizeFunction + : public ClearFontPrefExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.clearMinimumFontSize") protected: - virtual ~ClearMinimumFontSizeFunction() {} + virtual ~FontSettingsClearMinimumFontSizeFunction() {} // ClearFontPrefExtensionFunction: virtual const char* GetPrefName() OVERRIDE; }; -class GetMinimumFontSizeFunction : public GetFontPrefExtensionFunction { +class FontSettingsGetMinimumFontSizeFunction + : public GetFontPrefExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.getMinimumFontSize") protected: - virtual ~GetMinimumFontSizeFunction() {} + virtual ~FontSettingsGetMinimumFontSizeFunction() {} // GetFontPrefExtensionFunction: virtual const char* GetPrefName() OVERRIDE; virtual const char* GetKey() OVERRIDE; }; -class SetMinimumFontSizeFunction : public SetFontPrefExtensionFunction { +class FontSettingsSetMinimumFontSizeFunction + : public SetFontPrefExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("fontSettings.setMinimumFontSize") protected: - virtual ~SetMinimumFontSizeFunction() {} + virtual ~FontSettingsSetMinimumFontSizeFunction() {} // SetFontPrefExtensionFunction: virtual const char* GetPrefName() OVERRIDE; @@ -291,4 +299,4 @@ class SetMinimumFontSizeFunction : public SetFontPrefExtensionFunction { } // namespace extensions -#endif // CHROME_BROWSER_EXTENSIONS_API_FONT_SETTINGS_FONT_SETTINGS_API_H__ +#endif // CHROME_BROWSER_EXTENSIONS_API_FONT_SETTINGS_FONT_SETTINGS_API_H_ diff --git a/chrome/browser/extensions/api/history/history_api.cc b/chrome/browser/extensions/api/history/history_api.cc index 00af52c..06b5fcc 100644 --- a/chrome/browser/extensions/api/history/history_api.cc +++ b/chrome/browser/extensions/api/history/history_api.cc @@ -268,7 +268,7 @@ void HistoryFunctionWithCallback::SendResponseToCallback() { Release(); // Balanced in RunImpl(). } -bool GetMostVisitedHistoryFunction::RunAsyncImpl() { +bool HistoryGetMostVisitedFunction::RunAsyncImpl() { scoped_ptr<GetMostVisited::Params> params = GetMostVisited::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -288,12 +288,12 @@ bool GetMostVisitedHistoryFunction::RunAsyncImpl() { HistoryService* hs = HistoryServiceFactory::GetForProfile(profile(), Profile::EXPLICIT_ACCESS); hs->QueryFilteredURLs(max_results, filter, false, &cancelable_consumer_, - base::Bind(&GetMostVisitedHistoryFunction::QueryComplete, + base::Bind(&HistoryGetMostVisitedFunction::QueryComplete, base::Unretained(this))); return true; } -void GetMostVisitedHistoryFunction::QueryComplete( +void HistoryGetMostVisitedFunction::QueryComplete( CancelableRequestProvider::Handle handle, const history::FilteredURLList& data) { std::vector<linked_ptr<MostVisitedItem> > results; @@ -308,7 +308,7 @@ void GetMostVisitedHistoryFunction::QueryComplete( SendAsyncResponse(); } -bool GetVisitsHistoryFunction::RunAsyncImpl() { +bool HistoryGetVisitsFunction::RunAsyncImpl() { scoped_ptr<GetVisits::Params> params(GetVisits::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -322,13 +322,13 @@ bool GetVisitsHistoryFunction::RunAsyncImpl() { hs->QueryURL(url, true, // Retrieve full history of a URL. &cancelable_consumer_, - base::Bind(&GetVisitsHistoryFunction::QueryComplete, + base::Bind(&HistoryGetVisitsFunction::QueryComplete, base::Unretained(this))); return true; } -void GetVisitsHistoryFunction::QueryComplete( +void HistoryGetVisitsFunction::QueryComplete( HistoryService::Handle request_service, bool success, const history::URLRow* url_row, @@ -347,7 +347,7 @@ void GetVisitsHistoryFunction::QueryComplete( SendAsyncResponse(); } -bool SearchHistoryFunction::RunAsyncImpl() { +bool HistorySearchFunction::RunAsyncImpl() { scoped_ptr<Search::Params> params(Search::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -368,13 +368,13 @@ bool SearchHistoryFunction::RunAsyncImpl() { HistoryServiceFactory::GetForProfile(profile(), Profile::EXPLICIT_ACCESS); hs->QueryHistory(search_text, options, &cancelable_consumer_, - base::Bind(&SearchHistoryFunction::SearchComplete, + base::Bind(&HistorySearchFunction::SearchComplete, base::Unretained(this))); return true; } -void SearchHistoryFunction::SearchComplete( +void HistorySearchFunction::SearchComplete( HistoryService::Handle request_handle, history::QueryResults* results) { HistoryItemList history_item_vec; @@ -391,7 +391,7 @@ void SearchHistoryFunction::SearchComplete( SendAsyncResponse(); } -bool AddUrlHistoryFunction::RunImpl() { +bool HistoryAddUrlFunction::RunImpl() { scoped_ptr<AddUrl::Params> params(AddUrl::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -408,7 +408,7 @@ bool AddUrlHistoryFunction::RunImpl() { return true; } -bool DeleteUrlHistoryFunction::RunImpl() { +bool HistoryDeleteUrlFunction::RunImpl() { scoped_ptr<DeleteUrl::Params> params(DeleteUrl::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -425,7 +425,7 @@ bool DeleteUrlHistoryFunction::RunImpl() { return true; } -bool DeleteRangeHistoryFunction::RunAsyncImpl() { +bool HistoryDeleteRangeFunction::RunAsyncImpl() { scoped_ptr<DeleteRange::Params> params(DeleteRange::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -440,18 +440,18 @@ bool DeleteRangeHistoryFunction::RunAsyncImpl() { restrict_urls, start_time, end_time, - base::Bind(&DeleteRangeHistoryFunction::DeleteComplete, + base::Bind(&HistoryDeleteRangeFunction::DeleteComplete, base::Unretained(this)), &task_tracker_); return true; } -void DeleteRangeHistoryFunction::DeleteComplete() { +void HistoryDeleteRangeFunction::DeleteComplete() { SendAsyncResponse(); } -bool DeleteAllHistoryFunction::RunAsyncImpl() { +bool HistoryDeleteAllFunction::RunAsyncImpl() { std::set<GURL> restrict_urls; HistoryService* hs = HistoryServiceFactory::GetForProfile(profile(), @@ -460,14 +460,14 @@ bool DeleteAllHistoryFunction::RunAsyncImpl() { restrict_urls, base::Time::UnixEpoch(), // From the beginning of the epoch. base::Time::Now(), // To the current time. - base::Bind(&DeleteAllHistoryFunction::DeleteComplete, + base::Bind(&HistoryDeleteAllFunction::DeleteComplete, base::Unretained(this)), &task_tracker_); return true; } -void DeleteAllHistoryFunction::DeleteComplete() { +void HistoryDeleteAllFunction::DeleteComplete() { SendAsyncResponse(); } diff --git a/chrome/browser/extensions/api/history/history_api.h b/chrome/browser/extensions/api/history/history_api.h index 83860eb..9700b18 100644 --- a/chrome/browser/extensions/api/history/history_api.h +++ b/chrome/browser/extensions/api/history/history_api.h @@ -112,12 +112,12 @@ class HistoryFunctionWithCallback : public HistoryFunction { void SendResponseToCallback(); }; -class GetMostVisitedHistoryFunction : public HistoryFunctionWithCallback { +class HistoryGetMostVisitedFunction : public HistoryFunctionWithCallback { public: DECLARE_EXTENSION_FUNCTION_NAME("experimental.history.getMostVisited"); protected: - virtual ~GetMostVisitedHistoryFunction() {} + virtual ~HistoryGetMostVisitedFunction() {} // HistoryFunctionWithCallback: virtual bool RunAsyncImpl() OVERRIDE; @@ -127,12 +127,12 @@ class GetMostVisitedHistoryFunction : public HistoryFunctionWithCallback { const history::FilteredURLList& data); }; -class GetVisitsHistoryFunction : public HistoryFunctionWithCallback { +class HistoryGetVisitsFunction : public HistoryFunctionWithCallback { public: DECLARE_EXTENSION_FUNCTION_NAME("history.getVisits"); protected: - virtual ~GetVisitsHistoryFunction() {} + virtual ~HistoryGetVisitsFunction() {} // HistoryFunctionWithCallback: virtual bool RunAsyncImpl() OVERRIDE; @@ -144,12 +144,12 @@ class GetVisitsHistoryFunction : public HistoryFunctionWithCallback { history::VisitVector* visits); }; -class SearchHistoryFunction : public HistoryFunctionWithCallback { +class HistorySearchFunction : public HistoryFunctionWithCallback { public: DECLARE_EXTENSION_FUNCTION_NAME("history.search"); protected: - virtual ~SearchHistoryFunction() {} + virtual ~HistorySearchFunction() {} // HistoryFunctionWithCallback: virtual bool RunAsyncImpl() OVERRIDE; @@ -159,23 +159,23 @@ class SearchHistoryFunction : public HistoryFunctionWithCallback { history::QueryResults* results); }; -class AddUrlHistoryFunction : public HistoryFunction { +class HistoryAddUrlFunction : public HistoryFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("history.addUrl"); protected: - virtual ~AddUrlHistoryFunction() {} + virtual ~HistoryAddUrlFunction() {} // HistoryFunctionWithCallback: virtual bool RunImpl() OVERRIDE; }; -class DeleteAllHistoryFunction : public HistoryFunctionWithCallback { +class HistoryDeleteAllFunction : public HistoryFunctionWithCallback { public: DECLARE_EXTENSION_FUNCTION_NAME("history.deleteAll"); protected: - virtual ~DeleteAllHistoryFunction() {} + virtual ~HistoryDeleteAllFunction() {} // HistoryFunctionWithCallback: virtual bool RunAsyncImpl() OVERRIDE; @@ -185,23 +185,23 @@ class DeleteAllHistoryFunction : public HistoryFunctionWithCallback { }; -class DeleteUrlHistoryFunction : public HistoryFunction { +class HistoryDeleteUrlFunction : public HistoryFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("history.deleteUrl"); protected: - virtual ~DeleteUrlHistoryFunction() {} + virtual ~HistoryDeleteUrlFunction() {} // HistoryFunctionWithCallback: virtual bool RunImpl() OVERRIDE; }; -class DeleteRangeHistoryFunction : public HistoryFunctionWithCallback { +class HistoryDeleteRangeFunction : public HistoryFunctionWithCallback { public: DECLARE_EXTENSION_FUNCTION_NAME("history.deleteRange"); protected: - virtual ~DeleteRangeHistoryFunction() {} + virtual ~HistoryDeleteRangeFunction() {} // HistoryFunctionWithCallback: virtual bool RunAsyncImpl() OVERRIDE; diff --git a/chrome/browser/extensions/api/i18n/i18n_api.cc b/chrome/browser/extensions/api/i18n/i18n_api.cc index 51897da..ad2ef32 100644 --- a/chrome/browser/extensions/api/i18n/i18n_api.cc +++ b/chrome/browser/extensions/api/i18n/i18n_api.cc @@ -12,15 +12,15 @@ #include "base/string_split.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/common/pref_names.h" #include "chrome/common/extensions/api/i18n.h" +#include "chrome/common/pref_names.h" namespace GetAcceptLanguages = extensions::api::i18n::GetAcceptLanguages; // Errors. static const char kEmptyAcceptLanguagesError[] = "accept-languages is empty."; -bool GetAcceptLanguagesFunction::RunImpl() { +bool I18nGetAcceptLanguagesFunction::RunImpl() { std::string accept_languages = profile()->GetPrefs()->GetString(prefs::kAcceptLanguages); // Currently, there are 2 ways to set browser's accept-languages: through UI diff --git a/chrome/browser/extensions/api/i18n/i18n_api.h b/chrome/browser/extensions/api/i18n/i18n_api.h index d69bd9b..1975f17 100644 --- a/chrome/browser/extensions/api/i18n/i18n_api.h +++ b/chrome/browser/extensions/api/i18n/i18n_api.h @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_EXTENSIONS_API_I18N_I18N_API_H__ -#define CHROME_BROWSER_EXTENSIONS_API_I18N_I18N_API_H__ +#ifndef CHROME_BROWSER_EXTENSIONS_API_I18N_I18N_API_H_ +#define CHROME_BROWSER_EXTENSIONS_API_I18N_I18N_API_H_ #include "chrome/browser/extensions/extension_function.h" -class GetAcceptLanguagesFunction : public SyncExtensionFunction { - virtual ~GetAcceptLanguagesFunction() {} +class I18nGetAcceptLanguagesFunction : public SyncExtensionFunction { + virtual ~I18nGetAcceptLanguagesFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("i18n.getAcceptLanguages") }; -#endif // CHROME_BROWSER_EXTENSIONS_API_I18N_I18N_API_H__ +#endif // CHROME_BROWSER_EXTENSIONS_API_I18N_I18N_API_H_ diff --git a/chrome/browser/extensions/api/management/management_api.cc b/chrome/browser/extensions/api/management/management_api.cc index 140517a..04914f0 100644 --- a/chrome/browser/extensions/api/management/management_api.cc +++ b/chrome/browser/extensions/api/management/management_api.cc @@ -219,7 +219,7 @@ ExtensionService* AsyncManagementFunction::service() { return profile()->GetExtensionService(); } -bool GetAllExtensionsFunction::RunImpl() { +bool ManagementGetAllFunction::RunImpl() { ExtensionInfoList extensions; ExtensionSystem* system = ExtensionSystem::Get(profile()); @@ -231,7 +231,7 @@ bool GetAllExtensionsFunction::RunImpl() { return true; } -bool GetExtensionByIdFunction::RunImpl() { +bool ManagementGetFunction::RunImpl() { scoped_ptr<management::Get::Params> params( management::Get::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -250,7 +250,7 @@ bool GetExtensionByIdFunction::RunImpl() { return true; } -bool GetPermissionWarningsByIdFunction::RunImpl() { +bool ManagementGetPermissionWarningsByIdFunction::RunImpl() { scoped_ptr<management::GetPermissionWarningsById::Params> params( management::GetPermissionWarningsById::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -269,12 +269,13 @@ bool GetPermissionWarningsByIdFunction::RunImpl() { namespace { -// This class helps GetPermissionWarningsByManifestFunction manage +// This class helps ManagementGetPermissionWarningsByManifestFunction manage // sending manifest JSON strings to the utility process for parsing. class SafeManifestJSONParser : public UtilityProcessHostClient { public: - SafeManifestJSONParser(GetPermissionWarningsByManifestFunction* client, - const std::string& manifest) + SafeManifestJSONParser( + ManagementGetPermissionWarningsByManifestFunction* client, + const std::string& manifest) : client_(client), manifest_(manifest) {} @@ -345,7 +346,7 @@ class SafeManifestJSONParser : public UtilityProcessHostClient { ~SafeManifestJSONParser() {} // The client who we'll report results back to. - GetPermissionWarningsByManifestFunction* client_; + ManagementGetPermissionWarningsByManifestFunction* client_; // Data to parse. std::string manifest_; @@ -358,7 +359,7 @@ class SafeManifestJSONParser : public UtilityProcessHostClient { } // namespace -bool GetPermissionWarningsByManifestFunction::RunImpl() { +bool ManagementGetPermissionWarningsByManifestFunction::RunImpl() { scoped_ptr<management::GetPermissionWarningsByManifest::Params> params( management::GetPermissionWarningsByManifest::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -374,7 +375,7 @@ bool GetPermissionWarningsByManifestFunction::RunImpl() { return true; } -void GetPermissionWarningsByManifestFunction::OnParseSuccess( +void ManagementGetPermissionWarningsByManifestFunction::OnParseSuccess( DictionaryValue* parsed_manifest) { CHECK(parsed_manifest); @@ -395,7 +396,7 @@ void GetPermissionWarningsByManifestFunction::OnParseSuccess( Release(); } -void GetPermissionWarningsByManifestFunction::OnParseFailure( +void ManagementGetPermissionWarningsByManifestFunction::OnParseFailure( const std::string& error) { error_ = error; SendResponse(false); @@ -404,7 +405,7 @@ void GetPermissionWarningsByManifestFunction::OnParseFailure( Release(); } -bool LaunchAppFunction::RunImpl() { +bool ManagementLaunchAppFunction::RunImpl() { scoped_ptr<management::LaunchApp::Params> params( management::LaunchApp::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -436,13 +437,13 @@ bool LaunchAppFunction::RunImpl() { return true; } -SetEnabledFunction::SetEnabledFunction() { +ManagementSetEnabledFunction::ManagementSetEnabledFunction() { } -SetEnabledFunction::~SetEnabledFunction() { +ManagementSetEnabledFunction::~ManagementSetEnabledFunction() { } -bool SetEnabledFunction::RunImpl() { +bool ManagementSetEnabledFunction::RunImpl() { scoped_ptr<management::SetEnabled::Params> params( management::SetEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -487,30 +488,30 @@ bool SetEnabledFunction::RunImpl() { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, - base::Bind(&SetEnabledFunction::SendResponse, this, true)); + base::Bind(&ManagementSetEnabledFunction::SendResponse, this, true)); return true; } -void SetEnabledFunction::InstallUIProceed() { +void ManagementSetEnabledFunction::InstallUIProceed() { service()->EnableExtension(extension_id_); SendResponse(true); Release(); } -void SetEnabledFunction::InstallUIAbort(bool user_initiated) { +void ManagementSetEnabledFunction::InstallUIAbort(bool user_initiated) { error_ = keys::kUserDidNotReEnableError; SendResponse(false); Release(); } -UninstallFunction::UninstallFunction() { +ManagementUninstallFunction::ManagementUninstallFunction() { } -UninstallFunction::~UninstallFunction() { +ManagementUninstallFunction::~ManagementUninstallFunction() { } -bool UninstallFunction::RunImpl() { +bool ManagementUninstallFunction::RunImpl() { scoped_ptr<management::Uninstall::Params> params( management::Uninstall::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -552,11 +553,11 @@ bool UninstallFunction::RunImpl() { } // static -void UninstallFunction::SetAutoConfirmForTest(bool should_proceed) { +void ManagementUninstallFunction::SetAutoConfirmForTest(bool should_proceed) { auto_confirm_for_test = should_proceed ? PROCEED : ABORT; } -void UninstallFunction::Finish(bool should_uninstall) { +void ManagementUninstallFunction::Finish(bool should_uninstall) { if (should_uninstall) { bool success = service()->UninstallExtension( extension_id_, @@ -573,12 +574,12 @@ void UninstallFunction::Finish(bool should_uninstall) { } -void UninstallFunction::ExtensionUninstallAccepted() { +void ManagementUninstallFunction::ExtensionUninstallAccepted() { Finish(true); Release(); } -void UninstallFunction::ExtensionUninstallCanceled() { +void ManagementUninstallFunction::ExtensionUninstallCanceled() { Finish(false); Release(); } diff --git a/chrome/browser/extensions/api/management/management_api.h b/chrome/browser/extensions/api/management/management_api.h index 1bb39ee..07553c8 100644 --- a/chrome/browser/extensions/api/management/management_api.h +++ b/chrome/browser/extensions/api/management/management_api.h @@ -34,40 +34,41 @@ class AsyncManagementFunction : public AsyncExtensionFunction { ExtensionService* service(); }; -class GetAllExtensionsFunction : public ManagementFunction { +class ManagementGetAllFunction : public ManagementFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("management.getAll"); protected: - virtual ~GetAllExtensionsFunction() {} + virtual ~ManagementGetAllFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class GetExtensionByIdFunction : public ManagementFunction { +class ManagementGetFunction : public ManagementFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("management.get"); protected: - virtual ~GetExtensionByIdFunction() {} + virtual ~ManagementGetFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class GetPermissionWarningsByIdFunction : public ManagementFunction { +class ManagementGetPermissionWarningsByIdFunction : public ManagementFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("management.getPermissionWarningsById"); protected: - virtual ~GetPermissionWarningsByIdFunction() {} + virtual ~ManagementGetPermissionWarningsByIdFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class GetPermissionWarningsByManifestFunction : public AsyncExtensionFunction { +class ManagementGetPermissionWarningsByManifestFunction + : public AsyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME( "management.getPermissionWarningsByManifest"); @@ -77,32 +78,32 @@ class GetPermissionWarningsByManifestFunction : public AsyncExtensionFunction { void OnParseFailure(const std::string& error); protected: - virtual ~GetPermissionWarningsByManifestFunction() {} + virtual ~ManagementGetPermissionWarningsByManifestFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class LaunchAppFunction : public ManagementFunction { +class ManagementLaunchAppFunction : public ManagementFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("management.launchApp"); protected: - virtual ~LaunchAppFunction() {} + virtual ~ManagementLaunchAppFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; -class SetEnabledFunction : public AsyncManagementFunction, +class ManagementSetEnabledFunction : public AsyncManagementFunction, public ExtensionInstallPrompt::Delegate { public: DECLARE_EXTENSION_FUNCTION_NAME("management.setEnabled"); - SetEnabledFunction(); + ManagementSetEnabledFunction(); protected: - virtual ~SetEnabledFunction(); + virtual ~ManagementSetEnabledFunction(); // ExtensionFunction: virtual bool RunImpl() OVERRIDE; @@ -118,12 +119,12 @@ class SetEnabledFunction : public AsyncManagementFunction, scoped_ptr<ExtensionInstallPrompt> install_prompt_; }; -class UninstallFunction : public AsyncManagementFunction, +class ManagementUninstallFunction : public AsyncManagementFunction, public ExtensionUninstallDialog::Delegate { public: DECLARE_EXTENSION_FUNCTION_NAME("management.uninstall"); - UninstallFunction(); + ManagementUninstallFunction(); static void SetAutoConfirmForTest(bool should_proceed); // ExtensionUninstallDialog::Delegate implementation. @@ -131,7 +132,7 @@ class UninstallFunction : public AsyncManagementFunction, virtual void ExtensionUninstallCanceled() OVERRIDE; private: - virtual ~UninstallFunction(); + virtual ~ManagementUninstallFunction(); virtual bool RunImpl() OVERRIDE; diff --git a/chrome/browser/extensions/api/management/management_api_browsertest.cc b/chrome/browser/extensions/api/management/management_api_browsertest.cc index 5ca8f4c6..3250a3b 100644 --- a/chrome/browser/extensions/api/management/management_api_browsertest.cc +++ b/chrome/browser/extensions/api/management/management_api_browsertest.cc @@ -106,8 +106,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, const std::string id = extension->id(); // Uninstall, then cancel via the confirm dialog. - scoped_refptr<UninstallFunction> uninstall_function(new UninstallFunction()); - UninstallFunction::SetAutoConfirmForTest(false); + scoped_refptr<ManagementUninstallFunction> uninstall_function( + new ManagementUninstallFunction()); + ManagementUninstallFunction::SetAutoConfirmForTest(false); EXPECT_TRUE(MatchPattern( util::RunFunctionAndReturnError( @@ -121,8 +122,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, EXPECT_TRUE(service->GetExtensionById(id, false) != NULL); // Uninstall, then accept via the confirm dialog. - uninstall_function = new UninstallFunction(); - UninstallFunction::SetAutoConfirmForTest(true); + uninstall_function = new ManagementUninstallFunction(); + ManagementUninstallFunction::SetAutoConfirmForTest(true); util::RunFunctionAndReturnSingleResult( uninstall_function, @@ -144,8 +145,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, ASSERT_TRUE(listener.WaitUntilSatisfied()); // The management API should list this extension. - scoped_refptr<GetAllExtensionsFunction> function = - new GetAllExtensionsFunction(); + scoped_refptr<ManagementGetAllFunction> function = + new ManagementGetAllFunction(); scoped_ptr<base::Value> result(util::RunFunctionAndReturnSingleResult( function.get(), "[]", browser())); base::ListValue* list; @@ -155,7 +156,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, // And it should continue to do so even after it crashes. ASSERT_TRUE(CrashEnabledExtension(extension->id())); - function = new GetAllExtensionsFunction(); + function = new ManagementGetAllFunction(); result.reset(util::RunFunctionAndReturnSingleResult( function.get(), "[]", browser())); ASSERT_TRUE(result->GetAsList(&list)); @@ -200,7 +201,8 @@ class ExtensionManagementApiEscalationTest : void SetEnabled(bool enabled, bool user_gesture, const std::string& expected_error) { - scoped_refptr<SetEnabledFunction> function(new SetEnabledFunction); + scoped_refptr<ManagementSetEnabledFunction> function( + new ManagementSetEnabledFunction); const char* enabled_string = enabled ? "true" : "false"; if (user_gesture) function->set_user_gesture(true); @@ -227,8 +229,8 @@ const char ExtensionManagementApiEscalationTest::kId[] = IN_PROC_BROWSER_TEST_F(ExtensionManagementApiEscalationTest, DisabledReason) { - scoped_refptr<GetExtensionByIdFunction> function = - new GetExtensionByIdFunction(); + scoped_refptr<ManagementGetFunction> function = + new ManagementGetFunction(); scoped_ptr<base::Value> result(util::RunFunctionAndReturnSingleResult( function.get(), base::StringPrintf("[\"%s\"]", kId), diff --git a/chrome/browser/extensions/api/permissions/permissions_api.cc b/chrome/browser/extensions/api/permissions/permissions_api.cc index c395b9d..ba71c9c 100644 --- a/chrome/browser/extensions/api/permissions/permissions_api.cc +++ b/chrome/browser/extensions/api/permissions/permissions_api.cc @@ -52,7 +52,7 @@ bool ignore_user_gesture_for_tests = false; } // namespace -bool ContainsPermissionsFunction::RunImpl() { +bool PermissionsContainsFunction::RunImpl() { scoped_ptr<Contains::Params> params(Contains::Params::Create(*args_)); scoped_refptr<PermissionSet> permissions = @@ -65,14 +65,14 @@ bool ContainsPermissionsFunction::RunImpl() { return true; } -bool GetAllPermissionsFunction::RunImpl() { +bool PermissionsGetAllFunction::RunImpl() { scoped_ptr<Permissions> permissions = helpers::PackPermissionSet(GetExtension()->GetActivePermissions()); results_ = GetAll::Results::Create(*permissions); return true; } -bool RemovePermissionsFunction::RunImpl() { +bool PermissionsRemoveFunction::RunImpl() { scoped_ptr<Remove::Params> params(Remove::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -110,19 +110,19 @@ bool RemovePermissionsFunction::RunImpl() { } // static -void RequestPermissionsFunction::SetAutoConfirmForTests(bool should_proceed) { +void PermissionsRequestFunction::SetAutoConfirmForTests(bool should_proceed) { auto_confirm_for_tests = should_proceed ? PROCEED : ABORT; } // static -void RequestPermissionsFunction::SetIgnoreUserGestureForTests( +void PermissionsRequestFunction::SetIgnoreUserGestureForTests( bool ignore) { ignore_user_gesture_for_tests = ignore; } -RequestPermissionsFunction::RequestPermissionsFunction() {} +PermissionsRequestFunction::PermissionsRequestFunction() {} -void RequestPermissionsFunction::InstallUIProceed() { +void PermissionsRequestFunction::InstallUIProceed() { PermissionsUpdater perms_updater(profile()); perms_updater.AddPermissions(GetExtension(), requested_permissions_.get()); @@ -132,16 +132,16 @@ void RequestPermissionsFunction::InstallUIProceed() { Release(); // Balanced in RunImpl(). } -void RequestPermissionsFunction::InstallUIAbort(bool user_initiated) { +void PermissionsRequestFunction::InstallUIAbort(bool user_initiated) { results_ = Request::Results::Create(false); SendResponse(true); Release(); // Balanced in RunImpl(). } -RequestPermissionsFunction::~RequestPermissionsFunction() {} +PermissionsRequestFunction::~PermissionsRequestFunction() {} -bool RequestPermissionsFunction::RunImpl() { +bool PermissionsRequestFunction::RunImpl() { if (!user_gesture() && !ignore_user_gesture_for_tests) { error_ = kUserGestureRequiredError; return false; diff --git a/chrome/browser/extensions/api/permissions/permissions_api.h b/chrome/browser/extensions/api/permissions/permissions_api.h index 9801ea1..21281e2 100644 --- a/chrome/browser/extensions/api/permissions/permissions_api.h +++ b/chrome/browser/extensions/api/permissions/permissions_api.h @@ -15,48 +15,48 @@ class ExtensionService; // chrome.permissions.contains -class ContainsPermissionsFunction : public SyncExtensionFunction { +class PermissionsContainsFunction : public SyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("permissions.contains") protected: - virtual ~ContainsPermissionsFunction() {} + virtual ~PermissionsContainsFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; // chrome.permissions.getAll -class GetAllPermissionsFunction : public SyncExtensionFunction { +class PermissionsGetAllFunction : public SyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("permissions.getAll") protected: - virtual ~GetAllPermissionsFunction() {} + virtual ~PermissionsGetAllFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; // chrome.permissions.remove -class RemovePermissionsFunction : public SyncExtensionFunction { +class PermissionsRemoveFunction : public SyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("permissions.remove") protected: - virtual ~RemovePermissionsFunction() {} + virtual ~PermissionsRemoveFunction() {} // ExtensionFunction: virtual bool RunImpl() OVERRIDE; }; // chrome.permissions.request -class RequestPermissionsFunction : public AsyncExtensionFunction, +class PermissionsRequestFunction : public AsyncExtensionFunction, public ExtensionInstallPrompt::Delegate { public: DECLARE_EXTENSION_FUNCTION_NAME("permissions.request") - RequestPermissionsFunction(); + PermissionsRequestFunction(); // FOR TESTS ONLY to bypass the confirmation UI. static void SetAutoConfirmForTests(bool should_proceed); @@ -67,7 +67,7 @@ class RequestPermissionsFunction : public AsyncExtensionFunction, virtual void InstallUIAbort(bool user_initiated) OVERRIDE; protected: - virtual ~RequestPermissionsFunction(); + virtual ~PermissionsRequestFunction(); // ExtensionFunction: virtual bool RunImpl() OVERRIDE; diff --git a/chrome/browser/extensions/api/permissions/permissions_apitest.cc b/chrome/browser/extensions/api/permissions/permissions_apitest.cc index 4006d9b..a3944b5 100644 --- a/chrome/browser/extensions/api/permissions/permissions_apitest.cc +++ b/chrome/browser/extensions/api/permissions/permissions_apitest.cc @@ -85,7 +85,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGranted) { prefs->AddGrantedPermissions("kjmkgkdkpedkejedfhmfcenooemhbpbo", granted_permissions); - RequestPermissionsFunction::SetIgnoreUserGestureForTests(true); + PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_; @@ -95,8 +95,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGranted) { IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsAutoConfirm) { // Rather than setting the granted permissions, set the UI autoconfirm flag // and run the same tests. - RequestPermissionsFunction::SetAutoConfirmForTests(true); - RequestPermissionsFunction::SetIgnoreUserGestureForTests(true); + PermissionsRequestFunction::SetAutoConfirmForTests(true); + PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_; @@ -107,15 +107,15 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsAutoConfirm) { IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ComplexOptionalPermissions) { // Rather than setting the granted permissions, set the UI autoconfirm flag // and run the same tests. - RequestPermissionsFunction::SetAutoConfirmForTests(true); - RequestPermissionsFunction::SetIgnoreUserGestureForTests(true); + PermissionsRequestFunction::SetAutoConfirmForTests(true); + PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); EXPECT_TRUE(RunExtensionTest("permissions/complex_optional")) << message_; } // Test that denying the optional permissions confirmation dialog works. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsDeny) { - RequestPermissionsFunction::SetAutoConfirmForTests(false); - RequestPermissionsFunction::SetIgnoreUserGestureForTests(true); + PermissionsRequestFunction::SetAutoConfirmForTests(false); + PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); EXPECT_TRUE(RunExtensionTest("permissions/optional_deny")) << message_; @@ -124,7 +124,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsDeny) { // Tests that the permissions.request function must be called from within a // user gesture. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGesture) { - RequestPermissionsFunction::SetIgnoreUserGestureForTests(false); + PermissionsRequestFunction::SetIgnoreUserGestureForTests(false); host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); EXPECT_TRUE(RunExtensionTest("permissions/optional_gesture")) << message_; diff --git a/chrome/browser/extensions/api/processes/processes_api.cc b/chrome/browser/extensions/api/processes/processes_api.cc index 3042051..eb20dac 100644 --- a/chrome/browser/extensions/api/processes/processes_api.cc +++ b/chrome/browser/extensions/api/processes/processes_api.cc @@ -12,7 +12,6 @@ #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" - #include "chrome/browser/extensions/api/processes/processes_api_constants.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/event_router.h" diff --git a/chrome/browser/extensions/api/record/record_api.cc b/chrome/browser/extensions/api/record/record_api.cc index ff60cb3..a16b755 100644 --- a/chrome/browser/extensions/api/record/record_api.cc +++ b/chrome/browser/extensions/api/record/record_api.cc @@ -152,16 +152,16 @@ const ProcessStrategy &RunPageCyclerFunction::GetProcessStrategy() { return *process_strategy_; } -// CaptureURLsFunction ------------------------------------------------ +// RecordCaptureURLsFunction ------------------------------------------------ -CaptureURLsFunction::CaptureURLsFunction() +RecordCaptureURLsFunction::RecordCaptureURLsFunction() : RunPageCyclerFunction(new ProductionProcessStrategy()) {} -CaptureURLsFunction::CaptureURLsFunction(ProcessStrategy* strategy) +RecordCaptureURLsFunction::RecordCaptureURLsFunction(ProcessStrategy* strategy) : RunPageCyclerFunction(strategy) {} // Fetch data for possible optional switch for an extension to load. -bool CaptureURLsFunction::ParseJSParameters() { +bool RecordCaptureURLsFunction::ParseJSParameters() { scoped_ptr<record::CaptureURLs::Params> params( record::CaptureURLs::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -174,34 +174,34 @@ bool CaptureURLsFunction::ParseJSParameters() { return true; } -// CaptureURLsFunction adds "record-mode" to sub-browser call, and returns +// RecordCaptureURLsFunction adds "record-mode" to sub-browser call, and returns // just the (possibly empty) error list. -void CaptureURLsFunction::AddSwitches(CommandLine* line) { +void RecordCaptureURLsFunction::AddSwitches(CommandLine* line) { if (!line->HasSwitch(switches::kRecordMode)) line->AppendSwitch(switches::kRecordMode); } -void CaptureURLsFunction::Finish() { +void RecordCaptureURLsFunction::Finish() { results_ = record::CaptureURLs::Results::Create(errors_); SendResponse(true); } -// ReplayURLsFunction ------------------------------------------------ +// RecordReplayURLsFunction ------------------------------------------------ -ReplayURLsFunction::ReplayURLsFunction() +RecordReplayURLsFunction::RecordReplayURLsFunction() : RunPageCyclerFunction(new ProductionProcessStrategy()), run_time_ms_(0.0) { } -ReplayURLsFunction::ReplayURLsFunction(ProcessStrategy* strategy) +RecordReplayURLsFunction::RecordReplayURLsFunction(ProcessStrategy* strategy) : RunPageCyclerFunction(strategy), run_time_ms_(0.0) { } -ReplayURLsFunction::~ReplayURLsFunction() {} +RecordReplayURLsFunction::~RecordReplayURLsFunction() {} // Fetch data for possible optional switches for a repeat count and an // extension to load. -bool ReplayURLsFunction::ParseJSParameters() { +bool RecordReplayURLsFunction::ParseJSParameters() { scoped_ptr<record::ReplayURLs::Params> params( record::ReplayURLs::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -228,7 +228,7 @@ bool ReplayURLsFunction::ParseJSParameters() { // plus temp file into which to place stats. (Can't do this in // ParseJSParameters because file creation can't go on the UI thread.) // Plus, initialize time to create run time statistic. -void ReplayURLsFunction::AddSwitches(CommandLine* line) { +void RecordReplayURLsFunction::AddSwitches(CommandLine* line) { file_util::CreateTemporaryFile(&stats_file_path_); if (!extension_path_.empty()) @@ -240,13 +240,13 @@ void ReplayURLsFunction::AddSwitches(CommandLine* line) { } // Read stats file, and get run time. -void ReplayURLsFunction::ReadReplyFiles() { +void RecordReplayURLsFunction::ReadReplyFiles() { file_util::ReadFileToString(stats_file_path_, &stats_); run_time_ms_ = (base::Time::NowFromSystemTime() - timer_).InMillisecondsF(); } -void ReplayURLsFunction::Finish() { +void RecordReplayURLsFunction::Finish() { record::ReplayURLsResult result; result.run_time = run_time_ms_; diff --git a/chrome/browser/extensions/api/record/record_api.h b/chrome/browser/extensions/api/record/record_api.h index 4f5559a..69974ac 100644 --- a/chrome/browser/extensions/api/record/record_api.h +++ b/chrome/browser/extensions/api/record/record_api.h @@ -5,10 +5,10 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_RECORD_RECORD_API_H_ #define CHROME_BROWSER_EXTENSIONS_API_RECORD_RECORD_API_H_ -#include "chrome/browser/extensions/extension_function.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/time.h" +#include "chrome/browser/extensions/extension_function.h" namespace { @@ -105,15 +105,15 @@ class RunPageCyclerFunction : public AsyncExtensionFunction { scoped_ptr<ProcessStrategy> process_strategy_; }; -class CaptureURLsFunction : public RunPageCyclerFunction { +class RecordCaptureURLsFunction : public RunPageCyclerFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("experimental.record.captureURLs"); - CaptureURLsFunction(); - explicit CaptureURLsFunction(ProcessStrategy* strategy); + RecordCaptureURLsFunction(); + explicit RecordCaptureURLsFunction(ProcessStrategy* strategy); private: - virtual ~CaptureURLsFunction() {} + virtual ~RecordCaptureURLsFunction() {} // Read the ReplayDetails parameter if it exists. virtual bool ParseJSParameters() OVERRIDE; @@ -125,15 +125,15 @@ class CaptureURLsFunction : public RunPageCyclerFunction { virtual void Finish() OVERRIDE; }; -class ReplayURLsFunction : public RunPageCyclerFunction { +class RecordReplayURLsFunction : public RunPageCyclerFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("experimental.record.replayURLs"); - ReplayURLsFunction(); - explicit ReplayURLsFunction(ProcessStrategy* strategy); + RecordReplayURLsFunction(); + explicit RecordReplayURLsFunction(ProcessStrategy* strategy); private: - virtual ~ReplayURLsFunction(); + virtual ~RecordReplayURLsFunction(); // Read the ReplayDetails parameter if it exists. virtual bool ParseJSParameters() OVERRIDE; diff --git a/chrome/browser/extensions/api/record/record_api_test.cc b/chrome/browser/extensions/api/record/record_api_test.cc index c81dbe1..50de96a 100644 --- a/chrome/browser/extensions/api/record/record_api_test.cc +++ b/chrome/browser/extensions/api/record/record_api_test.cc @@ -217,13 +217,14 @@ class RecordApiTest : public InProcessBrowserTest { // Run a capture, using standard URL test list and the specified // user data dir. Return via |out_list| the list of error URLs, // if any, resulting from the capture. And return directly the - // CaptureURLsFunction that was used, so that its state may be + // RecordCaptureURLsFunction that was used, so that its state may be // queried. - scoped_refptr<CaptureURLsFunction> RunCapture(const FilePath& user_data_dir, + scoped_refptr<RecordCaptureURLsFunction> RunCapture( + const FilePath& user_data_dir, scoped_ptr<base::ListValue>* out_list) { - scoped_refptr<CaptureURLsFunction> capture_function( - new CaptureURLsFunction(new TestProcessStrategy(&temp_files_))); + scoped_refptr<RecordCaptureURLsFunction> capture_function( + new RecordCaptureURLsFunction(new TestProcessStrategy(&temp_files_))); std::string escaped_user_data_dir; ReplaceChars(user_data_dir.AsUTF8Unsafe(), "\\", "\\\\", @@ -277,7 +278,7 @@ IN_PROC_BROWSER_TEST_F(RecordApiTest, DISABLED_CheckCapture) { scoped_ptr<base::ListValue> result; EXPECT_TRUE(user_data_dir.CreateUniqueTempDir()); - scoped_refptr<CaptureURLsFunction> capture_URLs_function = + scoped_refptr<RecordCaptureURLsFunction> capture_URLs_function = RunCapture(user_data_dir.path(), &result); // Check that user-data-dir switch has been properly overridden. @@ -314,7 +315,8 @@ IN_PROC_BROWSER_TEST_F(RecordApiTest, MAYBE_CheckPlayback) { ReplaceChars(user_data_dir.path().AsUTF8Unsafe(), "\\", "\\\\", &escaped_user_data_dir); - scoped_refptr<ReplayURLsFunction> playback_function(new ReplayURLsFunction( + scoped_refptr<RecordReplayURLsFunction> playback_function( + new RecordReplayURLsFunction( new TestProcessStrategy(&temp_files_))); scoped_ptr<base::DictionaryValue> result(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult(playback_function, diff --git a/chrome/browser/extensions/api/tabs/execute_code_in_tab_function.cc b/chrome/browser/extensions/api/tabs/execute_code_in_tab_function.cc deleted file mode 100644 index 29a57d9..0000000 --- a/chrome/browser/extensions/api/tabs/execute_code_in_tab_function.cc +++ /dev/null @@ -1,277 +0,0 @@ -// Copyright (c) 2012 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/extensions/api/tabs/execute_code_in_tab_function.h" - -#include "base/bind.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "chrome/browser/extensions/api/tabs/tabs.h" -#include "chrome/browser/extensions/api/tabs/tabs_constants.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/extension_tab_util.h" -#include "chrome/browser/extensions/file_reader.h" -#include "chrome/browser/extensions/script_executor.h" -#include "chrome/browser/extensions/tab_helper.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/extensions/api/tabs.h" -#include "chrome/common/extensions/extension.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/extensions/extension_file_util.h" -#include "chrome/common/extensions/extension_l10n_util.h" -#include "chrome/common/extensions/extension_manifest_constants.h" -#include "chrome/common/extensions/extension_messages.h" -#include "chrome/common/extensions/message_bundle.h" -#include "content/public/browser/render_view_host.h" -#include "content/public/browser/web_contents.h" -#include "extensions/common/error_utils.h" - -using content::BrowserThread; -using extensions::api::tabs::InjectDetails; -using extensions::ErrorUtils; -using extensions::ScriptExecutor; -using extensions::UserScript; - -namespace keys = extensions::tabs_constants; - -ExecuteCodeInTabFunction::ExecuteCodeInTabFunction() - : execute_tab_id_(-1) { -} - -ExecuteCodeInTabFunction::~ExecuteCodeInTabFunction() {} - -bool ExecuteCodeInTabFunction::HasPermission() { - if (Init() && - extension_->HasAPIPermissionForTab(execute_tab_id_, - extensions::APIPermission::kTab)) { - return true; - } - return ExtensionFunction::HasPermission(); -} - -bool ExecuteCodeInTabFunction::RunImpl() { - EXTENSION_FUNCTION_VALIDATE(Init()); - - if (!details_->code.get() && !details_->file.get()) { - error_ = keys::kNoCodeOrFileToExecuteError; - return false; - } - if (details_->code.get() && details_->file.get()) { - error_ = keys::kMoreThanOneValuesError; - return false; - } - - content::WebContents* contents = NULL; - - // If |tab_id| is specified, look for the tab. Otherwise default to selected - // tab in the current window. - CHECK_GE(execute_tab_id_, 0); - if (!ExtensionTabUtil::GetTabById(execute_tab_id_, profile(), - include_incognito(), - NULL, NULL, &contents, NULL)) { - return false; - } - - // NOTE: This can give the wrong answer due to race conditions, but it is OK, - // we check again in the renderer. - CHECK(contents); - if (!GetExtension()->CanExecuteScriptOnPage(contents->GetURL(), - contents->GetURL(), - execute_tab_id_, - NULL, - &error_)) { - return false; - } - - if (details_->code.get()) - return Execute(*details_->code); - - CHECK(details_->file.get()); - resource_ = GetExtension()->GetResource(*details_->file); - - if (resource_.extension_root().empty() || resource_.relative_path().empty()) { - error_ = keys::kNoCodeOrFileToExecuteError; - return false; - } - - scoped_refptr<FileReader> file_reader(new FileReader( - resource_, base::Bind(&ExecuteCodeInTabFunction::DidLoadFile, this))); - file_reader->Start(); - - return true; -} - -void ExecuteCodeInTabFunction::OnExecuteCodeFinished(const std::string& error, - int32 on_page_id, - const GURL& on_url, - const ListValue& result) { - if (!error.empty()) - SetError(error); - - SendResponse(error.empty()); -} - -void TabsExecuteScriptFunction::OnExecuteCodeFinished(const std::string& error, - int32 on_page_id, - const GURL& on_url, - const ListValue& result) { - if (error.empty()) - SetResult(result.DeepCopy()); - ExecuteCodeInTabFunction::OnExecuteCodeFinished(error, on_page_id, on_url, - result); -} - -bool ExecuteCodeInTabFunction::Init() { - if (details_.get()) - return true; - - // |tab_id| is optional so it's ok if it's not there. - int tab_id = -1; - args_->GetInteger(0, &tab_id); - - // |details| are not optional. - DictionaryValue* details_value = NULL; - if (!args_->GetDictionary(1, &details_value)) - return false; - scoped_ptr<InjectDetails> details(new InjectDetails()); - if (!InjectDetails::Populate(*details_value, details.get())) - return false; - - // If the tab ID is -1 then it needs to be converted to the currently active - // tab's ID. - if (tab_id == -1) { - Browser* browser = GetCurrentBrowser(); - if (!browser) - return false; - content::WebContents* web_contents = NULL; - if (!ExtensionTabUtil::GetDefaultTab(browser, &web_contents, &tab_id)) - return false; - } - - execute_tab_id_ = tab_id; - details_ = details.Pass(); - return true; -} - -void ExecuteCodeInTabFunction::DidLoadFile(bool success, - const std::string& data) { - std::string function_name = name(); - const extensions::Extension* extension = GetExtension(); - - // Check if the file is CSS and needs localization. - if (success && - function_name == TabsInsertCSSFunction::function_name() && - extension != NULL && - data.find( - extensions::MessageBundle::kMessageBegin) != std::string::npos) { - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - base::Bind(&ExecuteCodeInTabFunction::LocalizeCSS, this, - data, - extension->id(), - extension->path(), - extension->default_locale())); - } else { - DidLoadAndLocalizeFile(success, data); - } -} - -void ExecuteCodeInTabFunction::LocalizeCSS( - const std::string& data, - const std::string& extension_id, - const FilePath& extension_path, - const std::string& extension_default_locale) { - scoped_ptr<SubstitutionMap> localization_messages( - extension_file_util::LoadMessageBundleSubstitutionMap( - extension_path, extension_id, extension_default_locale)); - - // We need to do message replacement on the data, so it has to be mutable. - std::string css_data = data; - std::string error; - extensions::MessageBundle::ReplaceMessagesWithExternalDictionary( - *localization_messages, &css_data, &error); - - // Call back DidLoadAndLocalizeFile on the UI thread. The success parameter - // is always true, because if loading had failed, we wouldn't have had - // anything to localize. - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::Bind(&ExecuteCodeInTabFunction::DidLoadAndLocalizeFile, this, - true, css_data)); -} - -void ExecuteCodeInTabFunction::DidLoadAndLocalizeFile(bool success, - const std::string& data) { - if (success) { - if (!Execute(data)) - SendResponse(false); - } else { -#if defined(OS_POSIX) - // TODO(viettrungluu): bug: there's no particular reason the path should be - // UTF-8, in which case this may fail. - error_ = ErrorUtils::FormatErrorMessage(keys::kLoadFileError, - resource_.relative_path().value()); -#elif defined(OS_WIN) - error_ = ErrorUtils::FormatErrorMessage(keys::kLoadFileError, - WideToUTF8(resource_.relative_path().value())); -#endif // OS_WIN - SendResponse(false); - } -} - -bool ExecuteCodeInTabFunction::Execute(const std::string& code_string) { - content::WebContents* contents = NULL; - Browser* browser = NULL; - - bool success = ExtensionTabUtil::GetTabById( - execute_tab_id_, profile(), include_incognito(), &browser, NULL, - &contents, NULL) && contents && browser; - - if (!success) - return false; - - const extensions::Extension* extension = GetExtension(); - if (!extension) - return false; - - ScriptExecutor::ScriptType script_type = ScriptExecutor::JAVASCRIPT; - std::string function_name = name(); - if (function_name == TabsInsertCSSFunction::function_name()) { - script_type = ScriptExecutor::CSS; - } else if (function_name != TabsExecuteScriptFunction::function_name()) { - NOTREACHED(); - } - - ScriptExecutor::FrameScope frame_scope = - details_->all_frames.get() && *details_->all_frames ? - ScriptExecutor::ALL_FRAMES : - ScriptExecutor::TOP_FRAME; - - UserScript::RunLocation run_at = UserScript::UNDEFINED; - switch (details_->run_at) { - case InjectDetails::RUN_AT_NONE: - case InjectDetails::RUN_AT_DOCUMENT_IDLE: - run_at = UserScript::DOCUMENT_IDLE; - break; - case InjectDetails::RUN_AT_DOCUMENT_START: - run_at = UserScript::DOCUMENT_START; - break; - case InjectDetails::RUN_AT_DOCUMENT_END: - run_at = UserScript::DOCUMENT_END; - break; - } - CHECK_NE(UserScript::UNDEFINED, run_at); - - extensions::TabHelper::FromWebContents(contents)-> - script_executor()->ExecuteScript( - extension->id(), - script_type, - code_string, - frame_scope, - run_at, - ScriptExecutor::ISOLATED_WORLD, - base::Bind(&ExecuteCodeInTabFunction::OnExecuteCodeFinished, this)); - return true; -} diff --git a/chrome/browser/extensions/api/tabs/execute_code_in_tab_function.h b/chrome/browser/extensions/api/tabs/execute_code_in_tab_function.h deleted file mode 100644 index 7ce5ec1..0000000 --- a/chrome/browser/extensions/api/tabs/execute_code_in_tab_function.h +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_TABS_EXECUTE_CODE_IN_TAB_FUNCTION_H__ -#define CHROME_BROWSER_EXTENSIONS_API_TABS_EXECUTE_CODE_IN_TAB_FUNCTION_H__ - -#include <string> - -#include "chrome/browser/extensions/extension_function.h" -#include "chrome/common/extensions/extension_resource.h" -#include "chrome/common/extensions/user_script.h" - -namespace extensions { -namespace api { -namespace tabs { -struct InjectDetails; -} // namespace tabs -} // namespace api -} // namespace extensions - -// Implement API call tabs.executeScript and tabs.insertCSS. -class ExecuteCodeInTabFunction : public AsyncExtensionFunction { - public: - ExecuteCodeInTabFunction(); - - protected: - virtual ~ExecuteCodeInTabFunction(); - - // ExtensionFunction: - virtual bool HasPermission() OVERRIDE; - virtual bool RunImpl() OVERRIDE; - - // Message handler. - virtual void OnExecuteCodeFinished(const std::string& error, - int32 on_page_id, - const GURL& on_url, - const ListValue& script_result); - - private: - // Initialize the |execute_tab_id_| and |details_| if they haven't already - // been. Returns whether initialization was successful. - bool Init(); - - // Called when contents from the file whose path is specified in JSON - // arguments has been loaded. - void DidLoadFile(bool success, const std::string& data); - - // Runs on FILE thread. Loads message bundles for the extension and - // localizes the CSS data. Calls back DidLoadAndLocalizeFile on the UI thread. - void LocalizeCSS( - const std::string& data, - const std::string& extension_id, - const FilePath& extension_path, - const std::string& extension_default_locale); - - // Called when contents from the loaded file have been localized. - void DidLoadAndLocalizeFile(bool success, const std::string& data); - - // Run in UI thread. Code string contains the code to be executed. Returns - // true on success. If true is returned, this does an AddRef. - bool Execute(const std::string& code_string); - - // Id of tab which executes code. - int execute_tab_id_; - - // The injection details. - scoped_ptr<extensions::api::tabs::InjectDetails> details_; - - // Contains extension resource built from path of file which is - // specified in JSON arguments. - ExtensionResource resource_; -}; - -class TabsExecuteScriptFunction : public ExecuteCodeInTabFunction { - private: - virtual ~TabsExecuteScriptFunction() {} - - virtual void OnExecuteCodeFinished(const std::string& error, - int32 on_page_id, - const GURL& on_url, - const ListValue& script_result) OVERRIDE; - - DECLARE_EXTENSION_FUNCTION_NAME("tabs.executeScript") -}; - -class TabsInsertCSSFunction : public ExecuteCodeInTabFunction { - private: - virtual ~TabsInsertCSSFunction() {} - - DECLARE_EXTENSION_FUNCTION_NAME("tabs.insertCSS") -}; - -#endif // CHROME_BROWSER_EXTENSIONS_API_TABS_EXECUTE_CODE_IN_TAB_FUNCTION_H__ diff --git a/chrome/browser/extensions/api/tabs/tabs.cc b/chrome/browser/extensions/api/tabs/tabs_api.cc index 342b630..441f422 100644 --- a/chrome/browser/extensions/api/tabs/tabs.cc +++ b/chrome/browser/extensions/api/tabs/tabs_api.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/extensions/api/tabs/tabs.h" +#include "chrome/browser/extensions/api/tabs/tabs_api.h" #include <algorithm> #include <limits> @@ -26,6 +26,7 @@ #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/extensions/file_reader.h" #include "chrome/browser/extensions/script_executor.h" #include "chrome/browser/extensions/tab_helper.h" #include "chrome/browser/extensions/window_controller.h" @@ -50,10 +51,15 @@ #include "chrome/browser/web_applications/web_app.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" +#include "chrome/common/extensions/api/tabs.h" #include "chrome/common/extensions/api/windows.h" #include "chrome/common/extensions/extension.h" +#include "chrome/common/extensions/extension_constants.h" +#include "chrome/common/extensions/extension_file_util.h" +#include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_manifest_constants.h" #include "chrome/common/extensions/extension_messages.h" +#include "chrome/common/extensions/message_bundle.h" #include "chrome/common/extensions/user_script.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" @@ -87,6 +93,7 @@ namespace GetLastFocused = extensions::api::windows::GetLastFocused; namespace errors = extension_manifest_errors; namespace keys = extensions::tabs_constants; +using content::BrowserThread; using content::NavigationController; using content::NavigationEntry; using content::OpenURLParams; @@ -95,10 +102,12 @@ using content::RenderViewHost; using content::WebContents; using extensions::ErrorUtils; using extensions::ScriptExecutor; +using extensions::UserScript; using extensions::WindowController; using extensions::WindowControllerList; +using extensions::api::tabs::InjectDetails; -const int CaptureVisibleTabFunction::kDefaultQuality = 90; +const int TabsCaptureVisibleTabFunction::kDefaultQuality = 90; namespace { @@ -249,7 +258,7 @@ Browser* CreateBrowserWindow(const Browser::CreateParams& params, // Windows --------------------------------------------------------------------- -bool GetWindowFunction::RunImpl() { +bool WindowsGetFunction::RunImpl() { scoped_ptr<Get::Params> params(Get::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -268,7 +277,7 @@ bool GetWindowFunction::RunImpl() { return true; } -bool GetCurrentWindowFunction::RunImpl() { +bool WindowsGetCurrentFunction::RunImpl() { scoped_ptr<GetCurrent::Params> params(GetCurrent::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -289,7 +298,7 @@ bool GetCurrentWindowFunction::RunImpl() { return true; } -bool GetLastFocusedWindowFunction::RunImpl() { +bool WindowsGetLastFocusedFunction::RunImpl() { scoped_ptr<GetLastFocused::Params> params( GetLastFocused::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -316,7 +325,7 @@ bool GetLastFocusedWindowFunction::RunImpl() { return true; } -bool GetAllWindowsFunction::RunImpl() { +bool WindowsGetAllFunction::RunImpl() { scoped_ptr<GetAll::Params> params(GetAll::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -341,7 +350,7 @@ bool GetAllWindowsFunction::RunImpl() { return true; } -bool CreateWindowFunction::ShouldOpenIncognitoWindow( +bool WindowsCreateFunction::ShouldOpenIncognitoWindow( const base::DictionaryValue* args, std::vector<GURL>* urls, bool* is_error) { @@ -391,7 +400,7 @@ bool CreateWindowFunction::ShouldOpenIncognitoWindow( return incognito; } -bool CreateWindowFunction::RunImpl() { +bool WindowsCreateFunction::RunImpl() { DictionaryValue* args = NULL; std::vector<GURL> urls; WebContents* contents = NULL; @@ -660,7 +669,7 @@ bool CreateWindowFunction::RunImpl() { return true; } -bool UpdateWindowFunction::RunImpl() { +bool WindowsUpdateFunction::RunImpl() { int window_id = extension_misc::kUnknownWindowId; EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &window_id)); DictionaryValue* update_props; @@ -804,7 +813,7 @@ bool UpdateWindowFunction::RunImpl() { return true; } -bool RemoveWindowFunction::RunImpl() { +bool WindowsRemoveFunction::RunImpl() { int window_id = -1; EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &window_id)); @@ -831,7 +840,7 @@ bool RemoveWindowFunction::RunImpl() { // Tabs ------------------------------------------------------------------------ -bool GetSelectedTabFunction::RunImpl() { +bool TabsGetSelectedFunction::RunImpl() { // windowId defaults to "current" window. int window_id = extension_misc::kCurrentWindowId; @@ -855,7 +864,7 @@ bool GetSelectedTabFunction::RunImpl() { return true; } -bool GetAllTabsInWindowFunction::RunImpl() { +bool TabsGetAllInWindowFunction::RunImpl() { // windowId defaults to "current" window. int window_id = extension_misc::kCurrentWindowId; if (HasOptionalArgument(0)) @@ -870,7 +879,7 @@ bool GetAllTabsInWindowFunction::RunImpl() { return true; } -bool QueryTabsFunction::RunImpl() { +bool TabsQueryFunction::RunImpl() { DictionaryValue* query = NULL; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &query)); @@ -983,7 +992,7 @@ bool QueryTabsFunction::RunImpl() { return true; } -bool CreateTabFunction::RunImpl() { +bool TabsCreateFunction::RunImpl() { DictionaryValue* args = NULL; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &args)); @@ -1117,7 +1126,7 @@ bool CreateTabFunction::RunImpl() { return true; } -bool DuplicateTabFunction::RunImpl() { +bool TabsDuplicateFunction::RunImpl() { int tab_id = -1; EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id)); @@ -1143,7 +1152,7 @@ bool DuplicateTabFunction::RunImpl() { return true; } -bool GetTabFunction::RunImpl() { +bool TabsGetFunction::RunImpl() { int tab_id = -1; EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id)); @@ -1161,7 +1170,7 @@ bool GetTabFunction::RunImpl() { return true; } -bool GetCurrentTabFunction::RunImpl() { +bool TabsGetCurrentFunction::RunImpl() { DCHECK(dispatcher()); WebContents* contents = dispatcher()->delegate()->GetAssociatedWebContents(); @@ -1171,7 +1180,7 @@ bool GetCurrentTabFunction::RunImpl() { return true; } -bool HighlightTabsFunction::RunImpl() { +bool TabsHighlightFunction::RunImpl() { DictionaryValue* info = NULL; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &info)); @@ -1228,10 +1237,10 @@ bool HighlightTabsFunction::RunImpl() { return true; } -UpdateTabFunction::UpdateTabFunction() : web_contents_(NULL) { +TabsUpdateFunction::TabsUpdateFunction() : web_contents_(NULL) { } -bool UpdateTabFunction::RunImpl() { +bool TabsUpdateFunction::RunImpl() { DictionaryValue* update_props = NULL; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &update_props)); @@ -1335,7 +1344,7 @@ bool UpdateTabFunction::RunImpl() { return true; } -bool UpdateTabFunction::UpdateURLIfPresent(DictionaryValue* update_props, +bool TabsUpdateFunction::UpdateURLIfPresent(DictionaryValue* update_props, int tab_id, bool* is_async) { if (!update_props->HasKey(keys::kUrlKey)) @@ -1379,7 +1388,7 @@ bool UpdateTabFunction::UpdateURLIfPresent(DictionaryValue* update_props, ScriptExecutor::TOP_FRAME, extensions::UserScript::DOCUMENT_IDLE, ScriptExecutor::MAIN_WORLD, - base::Bind(&UpdateTabFunction::OnExecuteCodeFinished, this)); + base::Bind(&TabsUpdateFunction::OnExecuteCodeFinished, this)); *is_async = true; return true; @@ -1396,14 +1405,14 @@ bool UpdateTabFunction::UpdateURLIfPresent(DictionaryValue* update_props, return true; } -void UpdateTabFunction::PopulateResult() { +void TabsUpdateFunction::PopulateResult() { if (!has_callback()) return; SetResult(ExtensionTabUtil::CreateTabValue(web_contents_, GetExtension())); } -void UpdateTabFunction::OnExecuteCodeFinished(const std::string& error, +void TabsUpdateFunction::OnExecuteCodeFinished(const std::string& error, int32 on_page_id, const GURL& url, const ListValue& script_result) { @@ -1414,7 +1423,7 @@ void UpdateTabFunction::OnExecuteCodeFinished(const std::string& error, SendResponse(error.empty()); } -bool MoveTabsFunction::RunImpl() { +bool TabsMoveFunction::RunImpl() { Value* tab_value = NULL; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &tab_value)); @@ -1535,7 +1544,7 @@ bool MoveTabsFunction::RunImpl() { return true; } -bool ReloadTabFunction::RunImpl() { +bool TabsReloadFunction::RunImpl() { bool bypass_cache = false; if (HasOptionalArgument(1)) { DictionaryValue* reload_props = NULL; @@ -1590,7 +1599,7 @@ bool ReloadTabFunction::RunImpl() { return true; } -bool RemoveTabsFunction::RunImpl() { +bool TabsRemoveFunction::RunImpl() { Value* tab_value = NULL; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &tab_value)); @@ -1620,7 +1629,8 @@ bool RemoveTabsFunction::RunImpl() { return true; } -bool CaptureVisibleTabFunction::GetTabToCapture(WebContents** web_contents) { +bool TabsCaptureVisibleTabFunction::GetTabToCapture( + WebContents** web_contents) { Browser* browser = NULL; // windowId defaults to "current" window. int window_id = extension_misc::kCurrentWindowId; @@ -1640,7 +1650,7 @@ bool CaptureVisibleTabFunction::GetTabToCapture(WebContents** web_contents) { return true; }; -bool CaptureVisibleTabFunction::RunImpl() { +bool TabsCaptureVisibleTabFunction::RunImpl() { PrefServiceBase* service = profile()->GetPrefs(); if (service->GetBoolean(prefs::kDisableScreenshots)) { error_ = keys::kScreenshotsDisabled; @@ -1699,14 +1709,14 @@ bool CaptureVisibleTabFunction::RunImpl() { render_view_host->CopyFromBackingStore( gfx::Rect(), view->GetViewBounds().size(), - base::Bind(&CaptureVisibleTabFunction::CopyFromBackingStoreComplete, + base::Bind(&TabsCaptureVisibleTabFunction::CopyFromBackingStoreComplete, this, base::Owned(temp_bitmap)), temp_bitmap); return true; } -void CaptureVisibleTabFunction::CopyFromBackingStoreComplete( +void TabsCaptureVisibleTabFunction::CopyFromBackingStoreComplete( skia::PlatformBitmap* bitmap, bool succeeded) { if (succeeded) { @@ -1726,14 +1736,14 @@ void CaptureVisibleTabFunction::CopyFromBackingStoreComplete( registrar_.Add(this, chrome::NOTIFICATION_TAB_SNAPSHOT_TAKEN, content::Source<WebContents>(web_contents)); - AddRef(); // Balanced in CaptureVisibleTabFunction::Observe(). + AddRef(); // Balanced in TabsCaptureVisibleTabFunction::Observe(). SnapshotTabHelper::FromWebContents(web_contents)->CaptureSnapshot(); } -// If a backing store was not available in CaptureVisibleTabFunction::RunImpl, -// than the renderer was asked for a snapshot. Listen for a notification -// that the snapshot is available. -void CaptureVisibleTabFunction::Observe( +// If a backing store was not available in +// TabsCaptureVisibleTabFunction::RunImpl, than the renderer was asked for a +// snapshot. Listen for a notification that the snapshot is available. +void TabsCaptureVisibleTabFunction::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { @@ -1751,12 +1761,12 @@ void CaptureVisibleTabFunction::Observe( SendResultFromBitmap(*screen_capture); } - Release(); // Balanced in CaptureVisibleTabFunction::RunImpl(). + Release(); // Balanced in TabsCaptureVisibleTabFunction::RunImpl(). } // Turn a bitmap of the screen into an image, set that image as the result, // and call SendResponse(). -void CaptureVisibleTabFunction::SendResultFromBitmap( +void TabsCaptureVisibleTabFunction::SendResultFromBitmap( const SkBitmap& screen_capture) { std::vector<unsigned char> data; SkAutoLockPixels screen_capture_lock(screen_capture); @@ -1802,13 +1812,13 @@ void CaptureVisibleTabFunction::SendResultFromBitmap( SendResponse(true); } -void CaptureVisibleTabFunction::RegisterUserPrefs( +void TabsCaptureVisibleTabFunction::RegisterUserPrefs( PrefServiceSyncable* service) { service->RegisterBooleanPref(prefs::kDisableScreenshots, false, PrefServiceSyncable::UNSYNCABLE_PREF); } -bool DetectTabLanguageFunction::RunImpl() { +bool TabsDetectLanguageFunction::RunImpl() { int tab_id = 0; Browser* browser = NULL; WebContents* contents = NULL; @@ -1846,7 +1856,7 @@ bool DetectTabLanguageFunction::RunImpl() { // Delay the callback invocation until after the current JS call has // returned. MessageLoop::current()->PostTask(FROM_HERE, base::Bind( - &DetectTabLanguageFunction::GotLanguage, this, + &TabsDetectLanguageFunction::GotLanguage, this, translate_tab_helper->language_state().original_language())); return true; } @@ -1863,7 +1873,7 @@ bool DetectTabLanguageFunction::RunImpl() { return true; } -void DetectTabLanguageFunction::Observe( +void TabsDetectLanguageFunction::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { @@ -1878,9 +1888,249 @@ void DetectTabLanguageFunction::Observe( GotLanguage(language); } -void DetectTabLanguageFunction::GotLanguage(const std::string& language) { +void TabsDetectLanguageFunction::GotLanguage(const std::string& language) { SetResult(Value::CreateStringValue(language.c_str())); SendResponse(true); Release(); // Balanced in Run() } + +ExecuteCodeInTabFunction::ExecuteCodeInTabFunction() + : execute_tab_id_(-1) { +} + +ExecuteCodeInTabFunction::~ExecuteCodeInTabFunction() {} + +bool ExecuteCodeInTabFunction::HasPermission() { + if (Init() && + extension_->HasAPIPermissionForTab(execute_tab_id_, + extensions::APIPermission::kTab)) { + return true; + } + return ExtensionFunction::HasPermission(); +} + +bool ExecuteCodeInTabFunction::RunImpl() { + EXTENSION_FUNCTION_VALIDATE(Init()); + + if (!details_->code.get() && !details_->file.get()) { + error_ = keys::kNoCodeOrFileToExecuteError; + return false; + } + if (details_->code.get() && details_->file.get()) { + error_ = keys::kMoreThanOneValuesError; + return false; + } + + content::WebContents* contents = NULL; + + // If |tab_id| is specified, look for the tab. Otherwise default to selected + // tab in the current window. + CHECK_GE(execute_tab_id_, 0); + if (!ExtensionTabUtil::GetTabById(execute_tab_id_, profile(), + include_incognito(), + NULL, NULL, &contents, NULL)) { + return false; + } + + // NOTE: This can give the wrong answer due to race conditions, but it is OK, + // we check again in the renderer. + CHECK(contents); + if (!GetExtension()->CanExecuteScriptOnPage(contents->GetURL(), + contents->GetURL(), + execute_tab_id_, + NULL, + &error_)) { + return false; + } + + if (details_->code.get()) + return Execute(*details_->code); + + CHECK(details_->file.get()); + resource_ = GetExtension()->GetResource(*details_->file); + + if (resource_.extension_root().empty() || resource_.relative_path().empty()) { + error_ = keys::kNoCodeOrFileToExecuteError; + return false; + } + + scoped_refptr<FileReader> file_reader(new FileReader( + resource_, base::Bind(&ExecuteCodeInTabFunction::DidLoadFile, this))); + file_reader->Start(); + + return true; +} + +void ExecuteCodeInTabFunction::OnExecuteCodeFinished(const std::string& error, + int32 on_page_id, + const GURL& on_url, + const ListValue& result) { + if (!error.empty()) + SetError(error); + + SendResponse(error.empty()); +} + +void TabsExecuteScriptFunction::OnExecuteCodeFinished(const std::string& error, + int32 on_page_id, + const GURL& on_url, + const ListValue& result) { + if (error.empty()) + SetResult(result.DeepCopy()); + ExecuteCodeInTabFunction::OnExecuteCodeFinished(error, on_page_id, on_url, + result); +} + +bool ExecuteCodeInTabFunction::Init() { + if (details_.get()) + return true; + + // |tab_id| is optional so it's ok if it's not there. + int tab_id = -1; + args_->GetInteger(0, &tab_id); + + // |details| are not optional. + DictionaryValue* details_value = NULL; + if (!args_->GetDictionary(1, &details_value)) + return false; + scoped_ptr<InjectDetails> details(new InjectDetails()); + if (!InjectDetails::Populate(*details_value, details.get())) + return false; + + // If the tab ID is -1 then it needs to be converted to the currently active + // tab's ID. + if (tab_id == -1) { + Browser* browser = GetCurrentBrowser(); + if (!browser) + return false; + content::WebContents* web_contents = NULL; + if (!ExtensionTabUtil::GetDefaultTab(browser, &web_contents, &tab_id)) + return false; + } + + execute_tab_id_ = tab_id; + details_ = details.Pass(); + return true; +} + +void ExecuteCodeInTabFunction::DidLoadFile(bool success, + const std::string& data) { + std::string function_name = name(); + const extensions::Extension* extension = GetExtension(); + + // Check if the file is CSS and needs localization. + if (success && + function_name == TabsInsertCSSFunction::function_name() && + extension != NULL && + data.find( + extensions::MessageBundle::kMessageBegin) != std::string::npos) { + BrowserThread::PostTask( + BrowserThread::FILE, FROM_HERE, + base::Bind(&ExecuteCodeInTabFunction::LocalizeCSS, this, + data, + extension->id(), + extension->path(), + extension->default_locale())); + } else { + DidLoadAndLocalizeFile(success, data); + } +} + +void ExecuteCodeInTabFunction::LocalizeCSS( + const std::string& data, + const std::string& extension_id, + const FilePath& extension_path, + const std::string& extension_default_locale) { + scoped_ptr<SubstitutionMap> localization_messages( + extension_file_util::LoadMessageBundleSubstitutionMap( + extension_path, extension_id, extension_default_locale)); + + // We need to do message replacement on the data, so it has to be mutable. + std::string css_data = data; + std::string error; + extensions::MessageBundle::ReplaceMessagesWithExternalDictionary( + *localization_messages, &css_data, &error); + + // Call back DidLoadAndLocalizeFile on the UI thread. The success parameter + // is always true, because if loading had failed, we wouldn't have had + // anything to localize. + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind(&ExecuteCodeInTabFunction::DidLoadAndLocalizeFile, this, + true, css_data)); +} + +void ExecuteCodeInTabFunction::DidLoadAndLocalizeFile(bool success, + const std::string& data) { + if (success) { + if (!Execute(data)) + SendResponse(false); + } else { +#if defined(OS_POSIX) + // TODO(viettrungluu): bug: there's no particular reason the path should be + // UTF-8, in which case this may fail. + error_ = ErrorUtils::FormatErrorMessage(keys::kLoadFileError, + resource_.relative_path().value()); +#elif defined(OS_WIN) + error_ = ErrorUtils::FormatErrorMessage(keys::kLoadFileError, + WideToUTF8(resource_.relative_path().value())); +#endif // OS_WIN + SendResponse(false); + } +} + +bool ExecuteCodeInTabFunction::Execute(const std::string& code_string) { + content::WebContents* contents = NULL; + Browser* browser = NULL; + + bool success = ExtensionTabUtil::GetTabById( + execute_tab_id_, profile(), include_incognito(), &browser, NULL, + &contents, NULL) && contents && browser; + + if (!success) + return false; + + const extensions::Extension* extension = GetExtension(); + if (!extension) + return false; + + ScriptExecutor::ScriptType script_type = ScriptExecutor::JAVASCRIPT; + std::string function_name = name(); + if (function_name == TabsInsertCSSFunction::function_name()) { + script_type = ScriptExecutor::CSS; + } else if (function_name != TabsExecuteScriptFunction::function_name()) { + NOTREACHED(); + } + + ScriptExecutor::FrameScope frame_scope = + details_->all_frames.get() && *details_->all_frames ? + ScriptExecutor::ALL_FRAMES : + ScriptExecutor::TOP_FRAME; + + UserScript::RunLocation run_at = UserScript::UNDEFINED; + switch (details_->run_at) { + case InjectDetails::RUN_AT_NONE: + case InjectDetails::RUN_AT_DOCUMENT_IDLE: + run_at = UserScript::DOCUMENT_IDLE; + break; + case InjectDetails::RUN_AT_DOCUMENT_START: + run_at = UserScript::DOCUMENT_START; + break; + case InjectDetails::RUN_AT_DOCUMENT_END: + run_at = UserScript::DOCUMENT_END; + break; + } + CHECK_NE(UserScript::UNDEFINED, run_at); + + extensions::TabHelper::FromWebContents(contents)-> + script_executor()->ExecuteScript( + extension->id(), + script_type, + code_string, + frame_scope, + run_at, + ScriptExecutor::ISOLATED_WORLD, + base::Bind(&ExecuteCodeInTabFunction::OnExecuteCodeFinished, this)); + return true; +} diff --git a/chrome/browser/extensions/api/tabs/tabs.h b/chrome/browser/extensions/api/tabs/tabs_api.h index 5011c3f..db362cc 100644 --- a/chrome/browser/extensions/api/tabs/tabs.h +++ b/chrome/browser/extensions/api/tabs/tabs_api.h @@ -2,14 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_EXTENSIONS_API_TABS_TABS_H__ -#define CHROME_BROWSER_EXTENSIONS_API_TABS_TABS_H__ +#ifndef CHROME_BROWSER_EXTENSIONS_API_TABS_TABS_API_H_ +#define CHROME_BROWSER_EXTENSIONS_API_TABS_TABS_API_H_ #include <string> #include <vector> #include "base/compiler_specific.h" #include "chrome/browser/extensions/extension_function.h" +#include "chrome/common/extensions/extension_resource.h" +#include "chrome/common/extensions/user_script.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "googleurl/src/gurl.h" @@ -27,33 +29,41 @@ namespace content { class WebContents; } +namespace extensions { +namespace api { +namespace tabs { +struct InjectDetails; +} // namespace tabs +} // namespace api +} // namespace extensions + namespace skia { class PlatformBitmap; } // Windows -class GetWindowFunction : public SyncExtensionFunction { - virtual ~GetWindowFunction() {} +class WindowsGetFunction : public SyncExtensionFunction { + virtual ~WindowsGetFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("windows.get") }; -class GetCurrentWindowFunction : public SyncExtensionFunction { - virtual ~GetCurrentWindowFunction() {} +class WindowsGetCurrentFunction : public SyncExtensionFunction { + virtual ~WindowsGetCurrentFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("windows.getCurrent") }; -class GetLastFocusedWindowFunction : public SyncExtensionFunction { - virtual ~GetLastFocusedWindowFunction() {} +class WindowsGetLastFocusedFunction : public SyncExtensionFunction { + virtual ~WindowsGetLastFocusedFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("windows.getLastFocused") }; -class GetAllWindowsFunction : public SyncExtensionFunction { - virtual ~GetAllWindowsFunction() {} +class WindowsGetAllFunction : public SyncExtensionFunction { + virtual ~WindowsGetAllFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("windows.getAll") }; -class CreateWindowFunction : public SyncExtensionFunction { - virtual ~CreateWindowFunction() {} +class WindowsCreateFunction : public SyncExtensionFunction { + virtual ~WindowsCreateFunction() {} virtual bool RunImpl() OVERRIDE; // Returns whether the window should be created in incognito mode. // |urls| is the list of urls to open. If we are creating an incognito window, @@ -66,64 +76,64 @@ class CreateWindowFunction : public SyncExtensionFunction { bool* is_error); DECLARE_EXTENSION_FUNCTION_NAME("windows.create") }; -class UpdateWindowFunction : public SyncExtensionFunction { - virtual ~UpdateWindowFunction() {} +class WindowsUpdateFunction : public SyncExtensionFunction { + virtual ~WindowsUpdateFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("windows.update") }; -class RemoveWindowFunction : public SyncExtensionFunction { - virtual ~RemoveWindowFunction() {} +class WindowsRemoveFunction : public SyncExtensionFunction { + virtual ~WindowsRemoveFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("windows.remove") }; // Tabs -class GetTabFunction : public SyncExtensionFunction { - virtual ~GetTabFunction() {} +class TabsGetFunction : public SyncExtensionFunction { + virtual ~TabsGetFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.get") }; -class GetCurrentTabFunction : public SyncExtensionFunction { - virtual ~GetCurrentTabFunction() {} +class TabsGetCurrentFunction : public SyncExtensionFunction { + virtual ~TabsGetCurrentFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.getCurrent") }; -class GetSelectedTabFunction : public SyncExtensionFunction { - virtual ~GetSelectedTabFunction() {} +class TabsGetSelectedFunction : public SyncExtensionFunction { + virtual ~TabsGetSelectedFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.getSelected") }; -class GetAllTabsInWindowFunction : public SyncExtensionFunction { - virtual ~GetAllTabsInWindowFunction() {} +class TabsGetAllInWindowFunction : public SyncExtensionFunction { + virtual ~TabsGetAllInWindowFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.getAllInWindow") }; -class QueryTabsFunction : public SyncExtensionFunction { - virtual ~QueryTabsFunction() {} +class TabsQueryFunction : public SyncExtensionFunction { + virtual ~TabsQueryFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.query") }; -class CreateTabFunction : public SyncExtensionFunction { - virtual ~CreateTabFunction() {} +class TabsCreateFunction : public SyncExtensionFunction { + virtual ~TabsCreateFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.create") }; -class DuplicateTabFunction : public SyncExtensionFunction { - virtual ~DuplicateTabFunction() {} +class TabsDuplicateFunction : public SyncExtensionFunction { + virtual ~TabsDuplicateFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.duplicate") }; -class HighlightTabsFunction : public SyncExtensionFunction { - virtual ~HighlightTabsFunction() {} +class TabsHighlightFunction : public SyncExtensionFunction { + virtual ~TabsHighlightFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.highlight") }; -class UpdateTabFunction : public AsyncExtensionFunction { +class TabsUpdateFunction : public AsyncExtensionFunction { public: - UpdateTabFunction(); + TabsUpdateFunction(); protected: - virtual ~UpdateTabFunction() {} + virtual ~TabsUpdateFunction() {} virtual bool UpdateURLIfPresent(base::DictionaryValue* update_props, int tab_id, bool* is_async); @@ -140,25 +150,25 @@ class UpdateTabFunction : public AsyncExtensionFunction { DECLARE_EXTENSION_FUNCTION_NAME("tabs.update") }; -class MoveTabsFunction : public SyncExtensionFunction { - virtual ~MoveTabsFunction() {} +class TabsMoveFunction : public SyncExtensionFunction { + virtual ~TabsMoveFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.move") }; -class ReloadTabFunction : public SyncExtensionFunction { - virtual ~ReloadTabFunction() {} +class TabsReloadFunction : public SyncExtensionFunction { + virtual ~TabsReloadFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.reload") }; -class RemoveTabsFunction : public SyncExtensionFunction { - virtual ~RemoveTabsFunction() {} +class TabsRemoveFunction : public SyncExtensionFunction { + virtual ~TabsRemoveFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("tabs.remove") }; -class DetectTabLanguageFunction : public AsyncExtensionFunction, +class TabsDetectLanguageFunction : public AsyncExtensionFunction, public content::NotificationObserver { private: - virtual ~DetectTabLanguageFunction() {} + virtual ~TabsDetectLanguageFunction() {} virtual bool RunImpl() OVERRIDE; virtual void Observe(int type, @@ -168,7 +178,7 @@ class DetectTabLanguageFunction : public AsyncExtensionFunction, content::NotificationRegistrar registrar_; DECLARE_EXTENSION_FUNCTION_NAME("tabs.detectLanguage") }; -class CaptureVisibleTabFunction : public AsyncExtensionFunction, +class TabsCaptureVisibleTabFunction : public AsyncExtensionFunction, public content::NotificationObserver { public: static void RegisterUserPrefs(PrefServiceSyncable* service); @@ -182,7 +192,7 @@ class CaptureVisibleTabFunction : public AsyncExtensionFunction, // The default quality setting used when encoding jpegs. static const int kDefaultQuality; - virtual ~CaptureVisibleTabFunction() {} + virtual ~TabsCaptureVisibleTabFunction() {} virtual bool RunImpl() OVERRIDE; virtual bool GetTabToCapture(content::WebContents** web_contents); virtual void Observe(int type, @@ -205,4 +215,76 @@ class CaptureVisibleTabFunction : public AsyncExtensionFunction, DECLARE_EXTENSION_FUNCTION_NAME("tabs.captureVisibleTab") }; -#endif // CHROME_BROWSER_EXTENSIONS_API_TABS_TABS_H__ +// Implement API call tabs.executeScript and tabs.insertCSS. +class ExecuteCodeInTabFunction : public AsyncExtensionFunction { + public: + ExecuteCodeInTabFunction(); + + protected: + virtual ~ExecuteCodeInTabFunction(); + + // ExtensionFunction: + virtual bool HasPermission() OVERRIDE; + virtual bool RunImpl() OVERRIDE; + + // Message handler. + virtual void OnExecuteCodeFinished(const std::string& error, + int32 on_page_id, + const GURL& on_url, + const ListValue& script_result); + + private: + // Initialize the |execute_tab_id_| and |details_| if they haven't already + // been. Returns whether initialization was successful. + bool Init(); + + // Called when contents from the file whose path is specified in JSON + // arguments has been loaded. + void DidLoadFile(bool success, const std::string& data); + + // Runs on FILE thread. Loads message bundles for the extension and + // localizes the CSS data. Calls back DidLoadAndLocalizeFile on the UI thread. + void LocalizeCSS( + const std::string& data, + const std::string& extension_id, + const FilePath& extension_path, + const std::string& extension_default_locale); + + // Called when contents from the loaded file have been localized. + void DidLoadAndLocalizeFile(bool success, const std::string& data); + + // Run in UI thread. Code string contains the code to be executed. Returns + // true on success. If true is returned, this does an AddRef. + bool Execute(const std::string& code_string); + + // Id of tab which executes code. + int execute_tab_id_; + + // The injection details. + scoped_ptr<extensions::api::tabs::InjectDetails> details_; + + // Contains extension resource built from path of file which is + // specified in JSON arguments. + ExtensionResource resource_; +}; + +class TabsExecuteScriptFunction : public ExecuteCodeInTabFunction { + private: + virtual ~TabsExecuteScriptFunction() {} + + virtual void OnExecuteCodeFinished(const std::string& error, + int32 on_page_id, + const GURL& on_url, + const ListValue& script_result) OVERRIDE; + + DECLARE_EXTENSION_FUNCTION_NAME("tabs.executeScript") +}; + +class TabsInsertCSSFunction : public ExecuteCodeInTabFunction { + private: + virtual ~TabsInsertCSSFunction() {} + + DECLARE_EXTENSION_FUNCTION_NAME("tabs.insertCSS") +}; + +#endif // CHROME_BROWSER_EXTENSIONS_API_TABS_TABS_API_H_ diff --git a/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc b/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc index c5a0dd5..c18a161 100644 --- a/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc +++ b/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc @@ -2,17 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/extensions/api/tabs/tabs.h" - #include "base/values.h" +#include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" -#include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/ui_test_utils.h" namespace keys = extensions::tabs_constants; @@ -32,8 +31,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, MAYBE_GetLastFocusedWindow) { Browser* new_browser = CreateBrowser(browser()->profile()); int focused_window_id = ExtensionTabUtil::GetWindowId(new_browser); - scoped_refptr<GetLastFocusedWindowFunction> function = - new GetLastFocusedWindowFunction(); + scoped_refptr<WindowsGetLastFocusedFunction> function = + new WindowsGetLastFocusedFunction(); scoped_refptr<extensions::Extension> extension(utils::CreateEmptyExtension()); function->set_extension(extension.get()); scoped_ptr<base::DictionaryValue> result(utils::ToDictionary( @@ -47,7 +46,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, MAYBE_GetLastFocusedWindow) { ListValue* tabs = NULL; EXPECT_FALSE(result.get()->GetList(keys::kTabsKey, &tabs)); - function = new GetLastFocusedWindowFunction(); + function = new WindowsGetLastFocusedFunction(); function->set_extension(extension.get()); result.reset(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult(function.get(), @@ -83,7 +82,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DISABLED_QueryLastFocusedWindowTabs) { int focused_window_id = ExtensionTabUtil::GetWindowId(focused_window); // Get tabs in the 'last focused' window called from non-focused browser. - scoped_refptr<QueryTabsFunction> function = new QueryTabsFunction(); + scoped_refptr<TabsQueryFunction> function = new TabsQueryFunction(); scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult(function.get(), "[{\"lastFocusedWindow\":true}]", @@ -100,7 +99,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DISABLED_QueryLastFocusedWindowTabs) { } // Get tabs NOT in the 'last focused' window called from the focused browser. - function = new QueryTabsFunction(); + function = new TabsQueryFunction(); result.reset(utils::ToList( utils::RunFunctionAndReturnSingleResult(function.get(), "[{\"lastFocusedWindow\":false}]", diff --git a/chrome/browser/extensions/api/tabs/tabs_test.cc b/chrome/browser/extensions/api/tabs/tabs_test.cc index 30f192c..ec96b6a 100644 --- a/chrome/browser/extensions/api/tabs/tabs_test.cc +++ b/chrome/browser/extensions/api/tabs/tabs_test.cc @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/extensions/api/tabs/tabs.h" #include <string> #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" -#include "base/stringprintf.h" #include "base/string_util.h" +#include "base/stringprintf.h" #include "base/values.h" +#include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_tab_util.h" @@ -38,7 +38,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetWindow) { int window_id = ExtensionTabUtil::GetWindowId(browser()); // Invalid window ID error. - scoped_refptr<GetWindowFunction> function = new GetWindowFunction(); + scoped_refptr<WindowsGetFunction> function = new WindowsGetFunction(); scoped_refptr<extensions::Extension> extension(utils::CreateEmptyExtension()); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( @@ -55,7 +55,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetWindow) { else bounds = browser()->window()->GetBounds(); - function = new GetWindowFunction(); + function = new WindowsGetFunction(); function->set_extension(extension.get()); scoped_ptr<base::DictionaryValue> result(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult( @@ -71,7 +71,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetWindow) { EXPECT_EQ(bounds.height(), utils::GetInteger(result.get(), "height")); // With "populate" enabled. - function = new GetWindowFunction(); + function = new WindowsGetFunction(); function->set_extension(extension.get()); result.reset(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult( @@ -96,7 +96,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetWindow) { // Popup. Browser* popup_browser = new Browser( Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile())); - function = new GetWindowFunction(); + function = new WindowsGetFunction(); function->set_extension(extension.get()); result.reset(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult( @@ -109,7 +109,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetWindow) { // Panel. Browser* panel_browser = new Browser( Browser::CreateParams(Browser::TYPE_PANEL, browser()->profile())); - function = new GetWindowFunction(); + function = new WindowsGetFunction(); function->set_extension(extension.get()); result.reset(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult( @@ -124,7 +124,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetWindow) { int incognito_window_id = ExtensionTabUtil::GetWindowId(incognito_browser); // Without "include_incognito". - function = new GetWindowFunction(); + function = new WindowsGetFunction(); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( utils::RunFunctionAndReturnError( @@ -134,7 +134,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetWindow) { keys::kWindowNotFoundError)); // With "include_incognito". - function = new GetWindowFunction(); + function = new WindowsGetFunction(); function->set_extension(extension.get()); result.reset(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult( @@ -151,8 +151,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetCurrentWindow) { int new_id = ExtensionTabUtil::GetWindowId(new_browser); // Get the current window using new_browser. - scoped_refptr<GetCurrentWindowFunction> function = - new GetCurrentWindowFunction(); + scoped_refptr<WindowsGetCurrentFunction> function = + new WindowsGetCurrentFunction(); scoped_refptr<extensions::Extension> extension(utils::CreateEmptyExtension()); function->set_extension(extension.get()); scoped_ptr<base::DictionaryValue> result(utils::ToDictionary( @@ -167,7 +167,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetCurrentWindow) { EXPECT_FALSE(result.get()->GetList(keys::kTabsKey, &tabs)); // Get the current window using the old window and make the tabs populated. - function = new GetCurrentWindowFunction(); + function = new WindowsGetCurrentFunction(); function->set_extension(extension.get()); result.reset(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult(function.get(), @@ -192,7 +192,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindows) { window_ids.insert(ExtensionTabUtil::GetWindowId(new_browser)); } - scoped_refptr<GetAllWindowsFunction> function = new GetAllWindowsFunction(); + scoped_refptr<WindowsGetAllFunction> function = new WindowsGetAllFunction(); scoped_refptr<extensions::Extension> extension(utils::CreateEmptyExtension()); function->set_extension(extension.get()); scoped_ptr<base::ListValue> result(utils::ToList( @@ -215,7 +215,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindows) { EXPECT_EQ(window_ids, result_ids); result_ids.clear(); - function = new GetAllWindowsFunction(); + function = new WindowsGetAllFunction(); function->set_extension(extension.get()); result.reset(utils::ToList( utils::RunFunctionAndReturnSingleResult(function.get(), @@ -240,7 +240,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindows) { IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, UpdateNoPermissions) { // The test empty extension has no permissions, therefore it should not get // tab data in the function result. - scoped_refptr<UpdateTabFunction> update_tab_function(new UpdateTabFunction()); + scoped_refptr<TabsUpdateFunction> update_tab_function( + new TabsUpdateFunction()); scoped_refptr<extensions::Extension> empty_extension( utils::CreateEmptyExtension()); update_tab_function->set_extension(empty_extension.get()); @@ -265,7 +266,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(), IncognitoModePrefs::FORCED); // Run without an explicit "incognito" param. - scoped_refptr<CreateWindowFunction> function(new CreateWindowFunction()); + scoped_refptr<WindowsCreateFunction> function(new WindowsCreateFunction()); scoped_refptr<extensions::Extension> extension(utils::CreateEmptyExtension()); function->set_extension(extension.get()); scoped_ptr<base::DictionaryValue> result(utils::ToDictionary( @@ -284,7 +285,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, // Now try creating a window from incognito window. Browser* incognito_browser = CreateIncognitoBrowser(); // Run without an explicit "incognito" param. - function = new CreateWindowFunction(); + function = new WindowsCreateFunction(); function->set_extension(extension.get()); result.reset(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult( @@ -306,7 +307,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(), IncognitoModePrefs::FORCED); // Run without an explicit "incognito" param. - scoped_refptr<CreateWindowFunction> function = new CreateWindowFunction(); + scoped_refptr<WindowsCreateFunction> function = new WindowsCreateFunction(); scoped_refptr<extensions::Extension> extension(utils::CreateEmptyExtension()); function->set_extension(extension.get()); scoped_ptr<base::DictionaryValue> result(utils::ToDictionary( @@ -324,7 +325,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, // Now try creating a window from incognito window. Browser* incognito_browser = CreateIncognitoBrowser(); // Run without an explicit "incognito" param. - function = new CreateWindowFunction(); + function = new WindowsCreateFunction(); function->set_extension(extension.get()); result.reset(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult(function.get(), @@ -347,7 +348,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, IncognitoModePrefs::FORCED); // Run with an explicit "incognito" param. - scoped_refptr<CreateWindowFunction> function = new CreateWindowFunction(); + scoped_refptr<WindowsCreateFunction> function = new WindowsCreateFunction(); scoped_refptr<extensions::Extension> extension(utils::CreateEmptyExtension()); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( @@ -359,7 +360,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, // Now try opening a normal window from incognito window. Browser* incognito_browser = CreateIncognitoBrowser(); // Run with an explicit "incognito" param. - function = new CreateWindowFunction(); + function = new WindowsCreateFunction(); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( utils::RunFunctionAndReturnError(function.get(), @@ -378,7 +379,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(), IncognitoModePrefs::DISABLED); // Run in normal window. - scoped_refptr<CreateWindowFunction> function = new CreateWindowFunction(); + scoped_refptr<WindowsCreateFunction> function = new WindowsCreateFunction(); scoped_refptr<extensions::Extension> extension(utils::CreateEmptyExtension()); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( @@ -388,7 +389,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, keys::kIncognitoModeIsDisabled)); // Run in incognito window. - function = new CreateWindowFunction(); + function = new WindowsCreateFunction(); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( utils::RunFunctionAndReturnError(function.get(), @@ -407,7 +408,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryCurrentWindowTabs) { int window_id = ExtensionTabUtil::GetWindowId(browser()); // Get tabs in the 'current' window called from non-focused browser. - scoped_refptr<QueryTabsFunction> function = new QueryTabsFunction(); + scoped_refptr<TabsQueryFunction> function = new TabsQueryFunction(); function->set_extension(utils::CreateEmptyExtension().get()); scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult(function.get(), @@ -424,7 +425,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryCurrentWindowTabs) { } // Get tabs NOT in the 'current' window called from non-focused browser. - function = new QueryTabsFunction(); + function = new TabsQueryFunction(); function->set_extension(utils::CreateEmptyExtension().get()); result.reset(utils::ToList( utils::RunFunctionAndReturnSingleResult(function.get(), @@ -450,7 +451,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DontCreateTabInClosingPopupWindow) { int window_id = ExtensionTabUtil::GetWindowId(popup_browser); chrome::CloseWindow(popup_browser); - scoped_refptr<CreateTabFunction> create_tab_function(new CreateTabFunction()); + scoped_refptr<TabsCreateFunction> create_tab_function( + new TabsCreateFunction()); create_tab_function->set_extension(utils::CreateEmptyExtension().get()); // Without a callback the function will not generate a result. create_tab_function->set_has_callback(true); @@ -472,7 +474,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, InvalidUpdateWindowState) { static const char kArgsMinimizedWithFocus[] = "[%u, {\"state\": \"minimized\", \"focused\": true}]"; - scoped_refptr<UpdateWindowFunction> function = new UpdateWindowFunction(); + scoped_refptr<WindowsUpdateFunction> function = new WindowsUpdateFunction(); scoped_refptr<extensions::Extension> extension(utils::CreateEmptyExtension()); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( @@ -484,7 +486,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, InvalidUpdateWindowState) { static const char kArgsMaximizedWithoutFocus[] = "[%u, {\"state\": \"maximized\", \"focused\": false}]"; - function = new UpdateWindowFunction(); + function = new WindowsUpdateFunction(); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( utils::RunFunctionAndReturnError( @@ -495,7 +497,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, InvalidUpdateWindowState) { static const char kArgsMinimizedWithBounds[] = "[%u, {\"state\": \"minimized\", \"width\": 500}]"; - function = new UpdateWindowFunction(); + function = new WindowsUpdateFunction(); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( utils::RunFunctionAndReturnError( @@ -506,7 +508,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, InvalidUpdateWindowState) { static const char kArgsMaximizedWithBounds[] = "[%u, {\"state\": \"maximized\", \"width\": 500}]"; - function = new UpdateWindowFunction(); + function = new WindowsUpdateFunction(); function->set_extension(extension.get()); EXPECT_TRUE(MatchPattern( utils::RunFunctionAndReturnError( @@ -529,8 +531,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DuplicateTab) { TabStripModel* tab_strip; ExtensionTabUtil::GetTabStripModel(web_contents, &tab_strip, &tab_index); - scoped_refptr<DuplicateTabFunction> duplicate_tab_function( - new DuplicateTabFunction()); + scoped_refptr<TabsDuplicateFunction> duplicate_tab_function( + new TabsDuplicateFunction()); scoped_ptr<base::DictionaryValue> test_extension_value( utils::ParseDictionary( "{\"name\": \"Test\", \"version\": \"1.0\", \"permissions\": [\"tabs\"]}" @@ -573,8 +575,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DuplicateTabNoPermission) { TabStripModel* tab_strip; ExtensionTabUtil::GetTabStripModel(web_contents, &tab_strip, &tab_index); - scoped_refptr<DuplicateTabFunction> duplicate_tab_function( - new DuplicateTabFunction()); + scoped_refptr<TabsDuplicateFunction> duplicate_tab_function( + new TabsDuplicateFunction()); scoped_refptr<extensions::Extension> empty_extension( utils::CreateEmptyExtension()); duplicate_tab_function->set_extension(empty_extension.get()); diff --git a/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc b/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc index 841a7fc..713fff5 100644 --- a/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc +++ b/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc @@ -19,12 +19,12 @@ #include "chrome/browser/view_type_utils.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/api/web_navigation.h" -#include "content/public/browser/resource_request_details.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" +#include "content/public/browser/resource_request_details.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "net/base/net_errors.h" @@ -664,7 +664,7 @@ bool WebNavigationTabObserver::IsReferenceFragmentNavigation( url.ReplaceComponents(replacements); } -bool GetFrameFunction::RunImpl() { +bool WebNavigationGetFrameFunction::RunImpl() { scoped_ptr<GetFrame::Params> params(GetFrame::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = params->details.tab_id; @@ -720,7 +720,7 @@ bool GetFrameFunction::RunImpl() { return true; } -bool GetAllFramesFunction::RunImpl() { +bool WebNavigationGetAllFramesFunction::RunImpl() { scoped_ptr<GetAllFrames::Params> params(GetAllFrames::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = params->details.tab_id; diff --git a/chrome/browser/extensions/api/web_navigation/web_navigation_api.h b/chrome/browser/extensions/api/web_navigation/web_navigation_api.h index 58e4308..8270307 100644 --- a/chrome/browser/extensions/api/web_navigation/web_navigation_api.h +++ b/chrome/browser/extensions/api/web_navigation/web_navigation_api.h @@ -201,15 +201,15 @@ class WebNavigationEventRouter : public TabStripModelObserver, }; // API function that returns the state of a given frame. -class GetFrameFunction : public SyncExtensionFunction { - virtual ~GetFrameFunction() {} +class WebNavigationGetFrameFunction : public SyncExtensionFunction { + virtual ~WebNavigationGetFrameFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("webNavigation.getFrame") }; // API function that returns the states of all frames in a given tab. -class GetAllFramesFunction : public SyncExtensionFunction { - virtual ~GetAllFramesFunction() {} +class WebNavigationGetAllFramesFunction : public SyncExtensionFunction { + virtual ~WebNavigationGetAllFramesFunction() {} virtual bool RunImpl() OVERRIDE; DECLARE_EXTENSION_FUNCTION_NAME("webNavigation.getAllFrames") }; diff --git a/chrome/browser/extensions/api/web_request/web_request_api.cc b/chrome/browser/extensions/api/web_request/web_request_api.cc index f907d43..b53ef97 100644 --- a/chrome/browser/extensions/api/web_request/web_request_api.cc +++ b/chrome/browser/extensions/api/web_request/web_request_api.cc @@ -1706,7 +1706,7 @@ void ExtensionWebRequestEventRouter::ClearSignaled(uint64 request_id, iter->second &= ~event_type; } -// Special QuotaLimitHeuristic for WebRequestHandlerBehaviorChanged. +// Special QuotaLimitHeuristic for WebRequestHandlerBehaviorChangedFunction. // // Each call of webRequest.handlerBehaviorChanged() clears the in-memory cache // of WebKit at the time of the next page load (top level navigation event). @@ -1955,7 +1955,7 @@ bool WebRequestEventHandled::RunImpl() { return true; } -void WebRequestHandlerBehaviorChanged::GetQuotaLimitHeuristics( +void WebRequestHandlerBehaviorChangedFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristics* heuristics) const { QuotaLimitHeuristic::Config config = { // See web_request.json for current value. @@ -1969,7 +1969,7 @@ void WebRequestHandlerBehaviorChanged::GetQuotaLimitHeuristics( heuristics->push_back(heuristic); } -void WebRequestHandlerBehaviorChanged::OnQuotaExceeded( +void WebRequestHandlerBehaviorChangedFunction::OnQuotaExceeded( const std::string& violation_error) { // Post warning message. ExtensionWarningSet warnings; @@ -1985,7 +1985,7 @@ void WebRequestHandlerBehaviorChanged::OnQuotaExceeded( Run(); } -bool WebRequestHandlerBehaviorChanged::RunImpl() { +bool WebRequestHandlerBehaviorChangedFunction::RunImpl() { helpers::ClearCacheOnNavigation(); return true; } diff --git a/chrome/browser/extensions/api/web_request/web_request_api.h b/chrome/browser/extensions/api/web_request/web_request_api.h index d0fb338..c7e567a 100644 --- a/chrome/browser/extensions/api/web_request/web_request_api.h +++ b/chrome/browser/extensions/api/web_request/web_request_api.h @@ -433,12 +433,13 @@ class WebRequestEventHandled : public SyncIOThreadExtensionFunction { virtual bool RunImpl() OVERRIDE; }; -class WebRequestHandlerBehaviorChanged : public SyncIOThreadExtensionFunction { +class WebRequestHandlerBehaviorChangedFunction + : public SyncIOThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION_NAME("webRequest.handlerBehaviorChanged"); protected: - virtual ~WebRequestHandlerBehaviorChanged() {} + virtual ~WebRequestHandlerBehaviorChangedFunction() {} // ExtensionFunction: virtual void GetQuotaLimitHeuristics( diff --git a/chrome/browser/extensions/browser_event_router.h b/chrome/browser/extensions/browser_event_router.h index 0ef7a0c..0f40c36 100644 --- a/chrome/browser/extensions/browser_event_router.h +++ b/chrome/browser/extensions/browser_event_router.h @@ -10,7 +10,7 @@ #include "base/basictypes.h" #include "base/compiler_specific.h" -#include "chrome/browser/extensions/api/tabs/tabs.h" +#include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/event_router.h" #include "chrome/browser/extensions/extension_toolbar_model.h" #include "chrome/browser/ui/browser_list_observer.h" diff --git a/chrome/browser/extensions/content_script_apitest.cc b/chrome/browser/extensions/content_script_apitest.cc index b675403..d1a71f3 100644 --- a/chrome/browser/extensions/content_script_apitest.cc +++ b/chrome/browser/extensions/content_script_apitest.cc @@ -163,8 +163,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ContentScriptExtensionAPIs) { } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ContentScriptPermissionsApi) { - RequestPermissionsFunction::SetIgnoreUserGestureForTests(true); - RequestPermissionsFunction::SetAutoConfirmForTests(true); + PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); + PermissionsRequestFunction::SetAutoConfirmForTests(true); host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("content_scripts/permissions")) << message_; diff --git a/chrome/browser/extensions/data_deleter.cc b/chrome/browser/extensions/data_deleter.cc index a164df0..a5c645a 100644 --- a/chrome/browser/extensions/data_deleter.cc +++ b/chrome/browser/extensions/data_deleter.cc @@ -4,8 +4,8 @@ #include "chrome/browser/extensions/data_deleter.h" +#include "chrome/browser/extensions/api/storage/settings_frontend.h" #include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/extension.h" #include "content/public/browser/browser_context.h" diff --git a/chrome/browser/extensions/extension_function_registry.cc b/chrome/browser/extensions/extension_function_registry.cc index 5b63968..7657dc9 100644 --- a/chrome/browser/extensions/extension_function_registry.cc +++ b/chrome/browser/extensions/extension_function_registry.cc @@ -7,44 +7,23 @@ #include "chrome/browser/accessibility/accessibility_extension_api.h" #include "chrome/browser/extensions/api/app/app_api.h" #include "chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h" -#include "chrome/browser/extensions/api/bookmarks/bookmark_api.h" #include "chrome/browser/extensions/api/browsing_data/browsing_data_api.h" -#include "chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h" #include "chrome/browser/extensions/api/commands/commands.h" -#include "chrome/browser/extensions/api/content_settings/content_settings_api.h" -#include "chrome/browser/extensions/api/context_menu/context_menu_api.h" -#include "chrome/browser/extensions/api/cookies/cookies_api.h" -#include "chrome/browser/extensions/api/debugger/debugger_api.h" -#include "chrome/browser/extensions/api/declarative/declarative_api.h" #include "chrome/browser/extensions/api/extension_action/extension_browser_actions_api.h" #include "chrome/browser/extensions/api/extension_action/extension_page_actions_api.h" #include "chrome/browser/extensions/api/extension_action/extension_script_badge_api.h" -#include "chrome/browser/extensions/api/font_settings/font_settings_api.h" -#include "chrome/browser/extensions/api/history/history_api.h" -#include "chrome/browser/extensions/api/identity/identity_api.h" -#include "chrome/browser/extensions/api/i18n/i18n_api.h" #include "chrome/browser/extensions/api/idle/idle_api.h" #include "chrome/browser/extensions/api/managed_mode/managed_mode_api.h" -#include "chrome/browser/extensions/api/management/management_api.h" #include "chrome/browser/extensions/api/metrics/metrics.h" #include "chrome/browser/extensions/api/module/module.h" #include "chrome/browser/extensions/api/omnibox/omnibox_api.h" -#include "chrome/browser/extensions/api/page_capture/page_capture_api.h" -#include "chrome/browser/extensions/api/permissions/permissions_api.h" #include "chrome/browser/extensions/api/preference/preference_api.h" -#include "chrome/browser/extensions/api/record/record_api.h" #include "chrome/browser/extensions/api/runtime/runtime_api.h" -#include "chrome/browser/extensions/api/serial/serial_api.h" -#include "chrome/browser/extensions/api/socket/socket_api.h" -#include "chrome/browser/extensions/api/tabs/execute_code_in_tab_function.h" -#include "chrome/browser/extensions/api/tabs/tabs.h" #include "chrome/browser/extensions/api/test/test_api.h" #include "chrome/browser/extensions/api/top_sites/top_sites_api.h" -#include "chrome/browser/extensions/api/web_navigation/web_navigation_api.h" #include "chrome/browser/extensions/api/web_request/web_request_api.h" #include "chrome/browser/extensions/api/web_socket_proxy_private/web_socket_proxy_private_api.h" #include "chrome/browser/extensions/api/webstore_private/webstore_private_api.h" -#include "chrome/browser/extensions/settings/settings_api.h" #include "chrome/browser/extensions/system/system_api.h" #include "chrome/browser/infobars/infobar_extension_api.h" #include "chrome/browser/rlz/rlz_extension_api.h" @@ -53,18 +32,17 @@ #if defined(TOOLKIT_VIEWS) #include "chrome/browser/extensions/api/input/input.h" -#endif +#endif // defined(TOOLKIT_VIEWS) #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/extensions/echo_private_api.h" -#include "chrome/browser/chromeos/extensions/file_browser_handler_api.h" #include "chrome/browser/chromeos/extensions/info_private_api.h" #include "chrome/browser/chromeos/extensions/input_method_api.h" #include "chrome/browser/chromeos/extensions/media_player_api.h" #include "chrome/browser/chromeos/extensions/power/power_api.h" #include "chrome/browser/chromeos/extensions/wallpaper_private_api.h" #include "chrome/browser/extensions/api/terminal/terminal_private_api.h" -#endif +#endif // defined(OS_CHROMEOS) // static ExtensionFunctionRegistry* ExtensionFunctionRegistry::GetInstance() { @@ -83,33 +61,6 @@ void ExtensionFunctionRegistry::ResetFunctions() { // Register all functions here. - // Windows - RegisterFunction<GetWindowFunction>(); - RegisterFunction<GetCurrentWindowFunction>(); - RegisterFunction<GetLastFocusedWindowFunction>(); - RegisterFunction<GetAllWindowsFunction>(); - RegisterFunction<CreateWindowFunction>(); - RegisterFunction<UpdateWindowFunction>(); - RegisterFunction<RemoveWindowFunction>(); - - // Tabs - RegisterFunction<CaptureVisibleTabFunction>(); - RegisterFunction<CreateTabFunction>(); - RegisterFunction<DetectTabLanguageFunction>(); - RegisterFunction<DuplicateTabFunction>(); - RegisterFunction<GetAllTabsInWindowFunction>(); - RegisterFunction<GetCurrentTabFunction>(); - RegisterFunction<GetSelectedTabFunction>(); - RegisterFunction<GetTabFunction>(); - RegisterFunction<HighlightTabsFunction>(); - RegisterFunction<MoveTabsFunction>(); - RegisterFunction<QueryTabsFunction>(); - RegisterFunction<ReloadTabFunction>(); - RegisterFunction<RemoveTabsFunction>(); - RegisterFunction<TabsExecuteScriptFunction>(); - RegisterFunction<TabsInsertCSSFunction>(); - RegisterFunction<UpdateTabFunction>(); - // Page Actions. RegisterFunction<EnablePageActionsFunction>(); RegisterFunction<DisablePageActionsFunction>(); @@ -154,21 +105,6 @@ void ExtensionFunctionRegistry::ResetFunctions() { RegisterFunction<RemovePasswordsFunction>(); RegisterFunction<RemoveWebSQLFunction>(); - // Bookmarks. - RegisterFunction<extensions::GetBookmarksFunction>(); - RegisterFunction<extensions::GetBookmarkChildrenFunction>(); - RegisterFunction<extensions::GetBookmarkRecentFunction>(); - RegisterFunction<extensions::GetBookmarkTreeFunction>(); - RegisterFunction<extensions::GetBookmarkSubTreeFunction>(); - RegisterFunction<extensions::ImportBookmarksFunction>(); - RegisterFunction<extensions::ExportBookmarksFunction>(); - RegisterFunction<extensions::SearchBookmarksFunction>(); - RegisterFunction<extensions::RemoveBookmarkFunction>(); - RegisterFunction<extensions::RemoveTreeBookmarkFunction>(); - RegisterFunction<extensions::CreateBookmarkFunction>(); - RegisterFunction<extensions::MoveBookmarkFunction>(); - RegisterFunction<extensions::UpdateBookmarkFunction>(); - // Infobars. RegisterFunction<ShowInfoBarFunction>(); @@ -185,22 +121,10 @@ void ExtensionFunctionRegistry::ResetFunctions() { RegisterFunction<extensions::CanEditBookmarkManagerFunction>(); RegisterFunction<extensions::CanOpenNewWindowsBookmarkFunction>(); - // History - RegisterFunction<extensions::AddUrlHistoryFunction>(); - RegisterFunction<extensions::DeleteAllHistoryFunction>(); - RegisterFunction<extensions::DeleteRangeHistoryFunction>(); - RegisterFunction<extensions::DeleteUrlHistoryFunction>(); - RegisterFunction<extensions::GetMostVisitedHistoryFunction>(); - RegisterFunction<extensions::GetVisitsHistoryFunction>(); - RegisterFunction<extensions::SearchHistoryFunction>(); - // Idle RegisterFunction<extensions::IdleQueryStateFunction>(); RegisterFunction<extensions::IdleSetDetectionIntervalFunction>(); - // I18N. - RegisterFunction<GetAcceptLanguagesFunction>(); - // Metrics. RegisterFunction<extensions::MetricsRecordUserActionFunction>(); RegisterFunction<extensions::MetricsRecordValueFunction>(); @@ -220,13 +144,6 @@ void ExtensionFunctionRegistry::ResetFunctions() { RegisterFunction<RlzClearProductStateFunction>(); #endif - // Cookies. - RegisterFunction<extensions::GetCookieFunction>(); - RegisterFunction<extensions::GetAllCookiesFunction>(); - RegisterFunction<extensions::SetCookieFunction>(); - RegisterFunction<extensions::RemoveCookieFunction>(); - RegisterFunction<extensions::GetAllCookieStoresFunction>(); - // Test. RegisterFunction<extensions::TestNotifyPassFunction>(); RegisterFunction<extensions::TestFailFunction>(); @@ -236,10 +153,6 @@ void ExtensionFunctionRegistry::ResetFunctions() { RegisterFunction<extensions::TestSendMessageFunction>(); RegisterFunction<extensions::TestGetConfigFunction>(); - // Record. - RegisterFunction<extensions::CaptureURLsFunction>(); - RegisterFunction<extensions::ReplayURLsFunction>(); - // Accessibility. RegisterFunction<GetFocusedControlFunction>(); RegisterFunction<SetAccessibilityEnabledFunction>(); @@ -248,12 +161,6 @@ void ExtensionFunctionRegistry::ResetFunctions() { // Commands. RegisterFunction<GetAllCommandsFunction>(); - // Context Menus. - RegisterFunction<extensions::CreateContextMenuFunction>(); - RegisterFunction<extensions::UpdateContextMenuFunction>(); - RegisterFunction<extensions::RemoveContextMenuFunction>(); - RegisterFunction<extensions::RemoveAllContextMenusFunction>(); - // Omnibox. RegisterFunction<extensions::OmniboxSendSuggestionsFunction>(); RegisterFunction<extensions::OmniboxSetDefaultSuggestionFunction>(); @@ -282,15 +189,6 @@ void ExtensionFunctionRegistry::ResetFunctions() { RegisterFunction<extensions::GetPolicyFunction>(); RegisterFunction<extensions::SetPolicyFunction>(); - // Management. - RegisterFunction<extensions::GetAllExtensionsFunction>(); - RegisterFunction<extensions::GetExtensionByIdFunction>(); - RegisterFunction<extensions::GetPermissionWarningsByIdFunction>(); - RegisterFunction<extensions::GetPermissionWarningsByManifestFunction>(); - RegisterFunction<extensions::LaunchAppFunction>(); - RegisterFunction<extensions::SetEnabledFunction>(); - RegisterFunction<extensions::UninstallFunction>(); - // Extension module. RegisterFunction<extensions::SetUpdateUrlDataFunction>(); RegisterFunction<extensions::IsAllowedIncognitoAccessFunction>(); @@ -305,14 +203,9 @@ void ExtensionFunctionRegistry::ResetFunctions() { RegisterFunction<extensions::CompleteInstallFunction>(); RegisterFunction<extensions::GetWebGLStatusFunction>(); - // WebNavigation. - RegisterFunction<extensions::GetFrameFunction>(); - RegisterFunction<extensions::GetAllFramesFunction>(); - // WebRequest. RegisterFunction<WebRequestAddEventListener>(); RegisterFunction<WebRequestEventHandled>(); - RegisterFunction<WebRequestHandlerBehaviorChanged>(); // Preferences. RegisterFunction<extensions::GetPreferenceFunction>(); @@ -324,9 +217,6 @@ void ExtensionFunctionRegistry::ResetFunctions() { // Device Customization. RegisterFunction<extensions::GetChromeosInfoFunction>(); - // FileBrowserHandlerInternal. - RegisterFunction<FileHandlerSelectFileFunction>(); - // Mediaplayer RegisterFunction<extensions::PlayMediaplayerFunction>(); RegisterFunction<extensions::GetPlaylistMediaplayerFunction>(); @@ -362,83 +252,17 @@ void ExtensionFunctionRegistry::ResetFunctions() { extensions::WebSocketProxyPrivateGetPassportForTCPFunction>(); RegisterFunction<extensions::WebSocketProxyPrivateGetURLForTCPFunction>(); - // Debugger - RegisterFunction<AttachDebuggerFunction>(); - RegisterFunction<DetachDebuggerFunction>(); - RegisterFunction<SendCommandDebuggerFunction>(); - - // Settings - RegisterFunction<extensions::GetSettingsFunction>(); - RegisterFunction<extensions::SetSettingsFunction>(); - RegisterFunction<extensions::RemoveSettingsFunction>(); - RegisterFunction<extensions::ClearSettingsFunction>(); - RegisterFunction<extensions::GetBytesInUseSettingsFunction>(); - - // Content settings. - RegisterFunction<extensions::GetResourceIdentifiersFunction>(); - RegisterFunction<extensions::ClearContentSettingsFunction>(); - RegisterFunction<extensions::GetContentSettingFunction>(); - RegisterFunction<extensions::SetContentSettingFunction>(); - - // Font settings. - RegisterFunction<extensions::GetFontListFunction>(); - RegisterFunction<extensions::ClearFontFunction>(); - RegisterFunction<extensions::GetFontFunction>(); - RegisterFunction<extensions::SetFontFunction>(); - RegisterFunction<extensions::ClearDefaultFontSizeFunction>(); - RegisterFunction<extensions::GetDefaultFontSizeFunction>(); - RegisterFunction<extensions::SetDefaultFontSizeFunction>(); - RegisterFunction<extensions::ClearDefaultFixedFontSizeFunction>(); - RegisterFunction<extensions::GetDefaultFixedFontSizeFunction>(); - RegisterFunction<extensions::SetDefaultFixedFontSizeFunction>(); - RegisterFunction<extensions::ClearMinimumFontSizeFunction>(); - RegisterFunction<extensions::GetMinimumFontSizeFunction>(); - RegisterFunction<extensions::SetMinimumFontSizeFunction>(); - - // CloudPrint settings. - RegisterFunction<extensions::CloudPrintSetupConnectorFunction>(); - RegisterFunction<extensions::CloudPrintGetHostNameFunction>(); - RegisterFunction<extensions::CloudPrintGetPrintersFunction>(); - // Experimental App API. RegisterFunction<extensions::AppNotifyFunction>(); RegisterFunction<extensions::AppClearAllNotificationsFunction>(); - // Permissions - RegisterFunction<ContainsPermissionsFunction>(); - RegisterFunction<GetAllPermissionsFunction>(); - RegisterFunction<RemovePermissionsFunction>(); - RegisterFunction<RequestPermissionsFunction>(); - - // PageCapture - RegisterFunction<extensions::PageCaptureSaveAsMHTMLFunction>(); - // TopSites RegisterFunction<extensions::GetTopSitesFunction>(); - // Serial - RegisterFunction<extensions::SerialOpenFunction>(); - RegisterFunction<extensions::SerialCloseFunction>(); - RegisterFunction<extensions::SerialReadFunction>(); - RegisterFunction<extensions::SerialWriteFunction>(); - - // Sockets - RegisterFunction<extensions::SocketCreateFunction>(); - RegisterFunction<extensions::SocketDestroyFunction>(); - RegisterFunction<extensions::SocketConnectFunction>(); - RegisterFunction<extensions::SocketDisconnectFunction>(); - RegisterFunction<extensions::SocketReadFunction>(); - RegisterFunction<extensions::SocketWriteFunction>(); - // System RegisterFunction<extensions::GetIncognitoModeAvailabilityFunction>(); RegisterFunction<extensions::GetUpdateStatusFunction>(); - // Net - RegisterFunction<extensions::AddRulesFunction>(); - RegisterFunction<extensions::RemoveRulesFunction>(); - RegisterFunction<extensions::GetRulesFunction>(); - // Runtime RegisterFunction<extensions::RuntimeGetBackgroundPageFunction>(); RegisterFunction<extensions::RuntimeReloadFunction>(); diff --git a/chrome/browser/extensions/extension_service.cc b/chrome/browser/extensions/extension_service.cc index 4917d5f..726959e 100644 --- a/chrome/browser/extensions/extension_service.cc +++ b/chrome/browser/extensions/extension_service.cc @@ -36,6 +36,7 @@ #include "chrome/browser/extensions/api/profile_keyed_api_factory.h" #include "chrome/browser/extensions/api/push_messaging/push_messaging_api.h" #include "chrome/browser/extensions/api/runtime/runtime_api.h" +#include "chrome/browser/extensions/api/storage/settings_frontend.h" #include "chrome/browser/extensions/app_notification_manager.h" #include "chrome/browser/extensions/app_sync_data.h" #include "chrome/browser/extensions/browser_event_router.h" @@ -62,7 +63,6 @@ #include "chrome/browser/extensions/pending_extension_manager.h" #include "chrome/browser/extensions/permissions_updater.h" #include "chrome/browser/extensions/platform_app_launcher.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" #include "chrome/browser/extensions/shell_window_registry.h" #include "chrome/browser/extensions/unpacked_installer.h" #include "chrome/browser/extensions/updater/extension_updater.h" diff --git a/chrome/browser/extensions/platform_app_browsertest.cc b/chrome/browser/extensions/platform_app_browsertest.cc index d2715bd..718d2bd 100644 --- a/chrome/browser/extensions/platform_app_browsertest.cc +++ b/chrome/browser/extensions/platform_app_browsertest.cc @@ -10,8 +10,8 @@ #include "chrome/browser/automation/automation_util.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/extensions/api/permissions/permissions_api.h" -#include "chrome/browser/extensions/app_restore_service_factory.h" #include "chrome/browser/extensions/app_restore_service.h" +#include "chrome/browser/extensions/app_restore_service_factory.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_prefs.h" #include "chrome/browser/extensions/extension_service.h" @@ -761,7 +761,7 @@ IN_PROC_BROWSER_TEST_F(PlatformAppDevToolsBrowserTest, ReOpenedWithURL) { #endif IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, MAYBE_ConstrainedWindowRequest) { - RequestPermissionsFunction::SetIgnoreUserGestureForTests(true); + PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); const Extension* extension = LoadAndLaunchPlatformApp("optional_permission_request"); ASSERT_TRUE(extension) << "Failed to load extension."; diff --git a/chrome/browser/extensions/platform_app_browsertest_util.cc b/chrome/browser/extensions/platform_app_browsertest_util.cc index 4611c0a..f1b78a4 100644 --- a/chrome/browser/extensions/platform_app_browsertest_util.cc +++ b/chrome/browser/extensions/platform_app_browsertest_util.cc @@ -6,7 +6,7 @@ #include "base/command_line.h" #include "base/stringprintf.h" -#include "chrome/browser/extensions/api/tabs/tabs.h" +#include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/shell_window_registry.h" #include "chrome/browser/ui/browser.h" @@ -93,7 +93,7 @@ ShellWindow* PlatformAppBrowserTest::GetFirstShellWindow() { size_t PlatformAppBrowserTest::RunGetWindowsFunctionForExtension( const Extension* extension) { - scoped_refptr<GetAllWindowsFunction> function = new GetAllWindowsFunction(); + scoped_refptr<WindowsGetAllFunction> function = new WindowsGetAllFunction(); function->set_extension(extension); scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult(function.get(), @@ -105,7 +105,7 @@ size_t PlatformAppBrowserTest::RunGetWindowsFunctionForExtension( bool PlatformAppBrowserTest::RunGetWindowFunctionForExtension( int window_id, const Extension* extension) { - scoped_refptr<GetWindowFunction> function = new GetWindowFunction(); + scoped_refptr<WindowsGetFunction> function = new WindowsGetFunction(); function->set_extension(extension); utils::RunFunction( function.get(), diff --git a/chrome/browser/extensions/settings/leveldb_settings_storage_factory.cc b/chrome/browser/extensions/settings/leveldb_settings_storage_factory.cc deleted file mode 100644 index d057529..0000000 --- a/chrome/browser/extensions/settings/leveldb_settings_storage_factory.cc +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/leveldb_settings_storage_factory.h" - -#include "base/logging.h" -#include "chrome/browser/value_store/leveldb_value_store.h" - -namespace extensions { - -ValueStore* LeveldbSettingsStorageFactory::Create( - const FilePath& base_path, - const std::string& extension_id) { - return new LeveldbValueStore(base_path.AppendASCII(extension_id)); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/leveldb_settings_storage_factory.h b/chrome/browser/extensions/settings/leveldb_settings_storage_factory.h deleted file mode 100644 index 8a88f0d..0000000 --- a/chrome/browser/extensions/settings/leveldb_settings_storage_factory.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_LEVELDB_SETTINGS_STORAGE_FACTORY_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_LEVELDB_SETTINGS_STORAGE_FACTORY_H_ - -#include "chrome/browser/extensions/settings/settings_storage_factory.h" - -namespace extensions { - -// Factory for creating LeveldbValueStore instances. -class LeveldbSettingsStorageFactory : public SettingsStorageFactory { - public: - virtual ValueStore* Create(const FilePath& base_path, - const std::string& extension_id) OVERRIDE; - - private: - // SettingsStorageFactory is refcounted. - virtual ~LeveldbSettingsStorageFactory() {} -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_LEVELDB_SETTINGS_STORAGE_FACTORY_H_ diff --git a/chrome/browser/extensions/settings/managed_value_store_cache.cc b/chrome/browser/extensions/settings/managed_value_store_cache.cc deleted file mode 100644 index 62eb094..0000000 --- a/chrome/browser/extensions/settings/managed_value_store_cache.cc +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/managed_value_store_cache.h" - -#include <set> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/file_util.h" -#include "base/logging.h" -#include "base/message_loop_proxy.h" -#include "chrome/browser/extensions/event_names.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/settings/policy_value_store.h" -#include "chrome/browser/extensions/settings/settings_storage_factory.h" -#include "chrome/browser/value_store/value_store_change.h" -#include "chrome/common/extensions/extension.h" -#include "content/public/browser/browser_thread.h" - -using content::BrowserThread; - -namespace extensions { - -ManagedValueStoreCache::ManagedValueStoreCache( - policy::PolicyService* policy_service, - EventRouter* event_router, - const scoped_refptr<SettingsStorageFactory>& factory, - const scoped_refptr<SettingsObserverList>& observers, - const FilePath& profile_path) - : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), - weak_this_on_ui_(weak_factory_.GetWeakPtr()), - policy_service_(policy_service), - event_router_(event_router), - storage_factory_(factory), - observers_(observers), - base_path_(profile_path.AppendASCII( - ExtensionService::kManagedSettingsDirectoryName)) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - // |event_router| can be NULL on unit_tests. - if (event_router_) - event_router_->RegisterObserver(this, event_names::kOnSettingsChanged); - policy_service_->AddObserver(policy::POLICY_DOMAIN_EXTENSIONS, this); -} - -ManagedValueStoreCache::~ManagedValueStoreCache() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(!event_router_); - // Delete the PolicyValueStores on FILE. - store_map_.clear(); -} - -void ManagedValueStoreCache::ShutdownOnUI() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - policy_service_->RemoveObserver(policy::POLICY_DOMAIN_EXTENSIONS, this); - policy_service_ = NULL; - if (event_router_) - event_router_->UnregisterObserver(this); - event_router_ = NULL; - weak_factory_.InvalidateWeakPtrs(); -} - -void ManagedValueStoreCache::RunWithValueStoreForExtension( - const StorageCallback& callback, - scoped_refptr<const Extension> extension) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - PolicyValueStore* store = GetStoreFor(extension->id()); - if (store) { - callback.Run(store); - } else { - // First time that an extension calls storage.managed.get(). Create the - // store and load it with the current policy, and don't send event - // notifications. - CreateStoreFor( - extension->id(), - false, - base::Bind(&ManagedValueStoreCache::RunWithValueStoreForExtension, - base::Unretained(this), - callback, - extension)); - } -} - -void ManagedValueStoreCache::DeleteStorageSoon( - const std::string& extension_id) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - PolicyValueStore* store = GetStoreFor(extension_id); - if (!store) { - // It's possible that the store exists, but hasn't been loaded yet - // (because the extension is unloaded, for example). Open the database to - // clear it if it exists. - // TODO(joaodasilva): move this check to a ValueStore method. - if (file_util::DirectoryExists(base_path_.AppendASCII(extension_id))) { - CreateStoreFor( - extension_id, - false, - base::Bind(&ManagedValueStoreCache::DeleteStorageSoon, - base::Unretained(this), - extension_id)); - } - } else { - store->DeleteStorage(); - store_map_.erase(extension_id); - } -} - -void ManagedValueStoreCache::OnPolicyUpdated(policy::PolicyDomain domain, - const std::string& component_id, - const policy::PolicyMap& previous, - const policy::PolicyMap& current) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - base::Bind(&ManagedValueStoreCache::UpdatePolicyOnFILE, - base::Unretained(this), - std::string(component_id), - base::Passed(current.DeepCopy()))); -} - -void ManagedValueStoreCache::UpdatePolicyOnFILE( - const std::string& extension_id, - scoped_ptr<policy::PolicyMap> current_policy) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - PolicyValueStore* store = GetStoreFor(extension_id); - if (!store) { - // The extension hasn't executed any storage.managed.* calls, and isn't - // listening for onChanged() either. Ignore this notification in that case. - return; - } - // Update the policy on the backing store, and fire notifications if it - // changed. - store->SetCurrentPolicy(*current_policy, true); -} - -void ManagedValueStoreCache::OnListenerAdded( - const EventListenerInfo& details) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - DCHECK_EQ(std::string(event_names::kOnSettingsChanged), details.event_name); - // This is invoked on several occasions: - // - // 1. when an extension first registers to observe storage.onChanged; in this - // case the backend doesn't have any previous data persisted, and it won't - // trigger a notification. - // - // 2. when the browser starts up and all existing extensions re-register for - // the onChanged event. In this case, if the current policy differs from - // the persisted version then a notification will be sent. - // - // 3. a policy update just occurred and sent a notification, and an extension - // with EventPages that is observing onChanged just woke up and registed - // again. In this case the policy update already persisted the current - // policy version, and |store| already exists. - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - base::Bind(&ManagedValueStoreCache::CreateForExtensionOnFILE, - base::Unretained(this), - details.extension_id)); -} - -void ManagedValueStoreCache::CreateForExtensionOnFILE( - const std::string& extension_id) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - PolicyValueStore* store = GetStoreFor(extension_id); - if (!store) - CreateStoreFor(extension_id, true, base::Closure()); -} - -PolicyValueStore* ManagedValueStoreCache::GetStoreFor( - const std::string& extension_id) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - PolicyValueStoreMap::iterator it = store_map_.find(extension_id); - if (it == store_map_.end()) - return NULL; - return it->second.get(); -} - -void ManagedValueStoreCache::CreateStoreFor( - const std::string& extension_id, - bool notify_if_changed, - const base::Closure& continuation) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(!GetStoreFor(extension_id)); - // Creating or loading an existing database requires an immediate update - // with the current policy for the corresponding extension, which must be - // retrieved on UI. - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::Bind(&ManagedValueStoreCache::GetInitialPolicy, - weak_this_on_ui_, - extension_id, - notify_if_changed, - continuation)); -} - -void ManagedValueStoreCache::GetInitialPolicy( - const std::string& extension_id, - bool notify_if_changed, - const base::Closure& continuation) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - const policy::PolicyMap& policy = policy_service_->GetPolicies( - policy::POLICY_DOMAIN_EXTENSIONS, extension_id); - // Now post back to FILE to create the database. - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - base::Bind(&ManagedValueStoreCache::CreateStoreWithInitialPolicy, - base::Unretained(this), - extension_id, - notify_if_changed, - base::Passed(policy.DeepCopy()), - continuation)); -} - -void ManagedValueStoreCache::CreateStoreWithInitialPolicy( - const std::string& extension_id, - bool notify_if_changed, - scoped_ptr<policy::PolicyMap> initial_policy, - const base::Closure& continuation) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - // If a 2nd call to CreateStoreFor() is issued before the 1st gets to execute - // its UI task, then the 2nd will enter this function but the store has - // already been created. Check for that. - PolicyValueStore* store = GetStoreFor(extension_id); - - if (!store) { - // Create it now. - - // If the database doesn't exist yet then this is the initial install, - // and no notifications should be issued in that case. - // TODO(joaodasilva): move this check to a ValueStore method. - if (!file_util::DirectoryExists(base_path_.AppendASCII(extension_id))) - notify_if_changed = false; - - store = new PolicyValueStore( - extension_id, - observers_, - make_scoped_ptr(storage_factory_->Create(base_path_, extension_id))); - store_map_[extension_id] = make_linked_ptr(store); - } - - // Send the latest policy to the store. - store->SetCurrentPolicy(*initial_policy, notify_if_changed); - - // And finally resume from where this process started. - if (!continuation.is_null()) - continuation.Run(); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/managed_value_store_cache.h b/chrome/browser/extensions/settings/managed_value_store_cache.h deleted file mode 100644 index 9a1ea7b..0000000 --- a/chrome/browser/extensions/settings/managed_value_store_cache.h +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_MANAGED_VALUE_STORE_CACHE_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_MANAGED_VALUE_STORE_CACHE_H_ - -#include <map> -#include <string> - -#include "base/basictypes.h" -#include "base/callback_forward.h" -#include "base/compiler_specific.h" -#include "base/file_path.h" -#include "base/memory/linked_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/extensions/event_router.h" -#include "chrome/browser/extensions/settings/settings_observer.h" -#include "chrome/browser/extensions/settings/value_store_cache.h" -#include "chrome/browser/policy/policy_service.h" - -namespace policy { -class PolicyMap; -} - -namespace extensions { - -class PolicyValueStore; -class SettingsStorageFactory; - -// A ValueStoreCache that manages a PolicyValueStore for each extension that -// uses the storage.managed namespace. This class observes policy changes and -// which extensions listen for storage.onChanged(), and sends the appropriate -// updates to the corresponding PolicyValueStore on the FILE thread. -class ManagedValueStoreCache : public ValueStoreCache, - public policy::PolicyService::Observer, - public EventRouter::Observer { - public: - // |policy_service| is used to retrieve policy for extensions, and to observe - // policy updates. - // ||event_router| is used to observe which extensions listen for onChanged. - // |factory| is used to create databases for the PolicyValueStores. - // |observers| is the list of SettingsObservers to notify when a ValueStore - // changes. - // |profile_path| is the path for the profile. The databases are created in - // a directory under this path. - ManagedValueStoreCache(policy::PolicyService* policy_service, - EventRouter* event_router, - const scoped_refptr<SettingsStorageFactory>& factory, - const scoped_refptr<SettingsObserverList>& observers, - const FilePath& profile_path); - virtual ~ManagedValueStoreCache(); - - private: - // Maps an extension ID to its PolicyValueStoreMap. - typedef std::map<std::string, linked_ptr<PolicyValueStore> > - PolicyValueStoreMap; - - // ValueStoreCache implementation: - virtual void ShutdownOnUI() OVERRIDE; - virtual void RunWithValueStoreForExtension( - const StorageCallback& callback, - scoped_refptr<const Extension> extension) OVERRIDE; - virtual void DeleteStorageSoon(const std::string& extension_id) OVERRIDE; - - // PolicyService::Observer implementation: - virtual void OnPolicyUpdated(policy::PolicyDomain domain, - const std::string& component_id, - const policy::PolicyMap& previous, - const policy::PolicyMap& current) OVERRIDE; - - // Posted by OnPolicyUpdated() to update a PolicyValueStore on the FILE - // thread. - void UpdatePolicyOnFILE(const std::string& extension_id, - scoped_ptr<policy::PolicyMap> current_policy); - - // EventRouter::Observer implementation: - virtual void OnListenerAdded(const EventListenerInfo& details) OVERRIDE; - - // Posted by OnListenerAdded() to load or create a PolicyValueStore for the - // given |extension_id|. - void CreateForExtensionOnFILE(const std::string& extension_id); - - // Returns an existing PolicyValueStore for |extension_id|, or NULL. - PolicyValueStore* GetStoreFor(const std::string& extension_id); - - // Creates a new PolicyValueStore for |extension_id|. This may open an - // existing database, or create a new one. This also sends the current policy - // for |extension_id| to the database. When |notify_if_changed| is true, - // a notification is sent with the changes between the current policy and the - // previously stored policy, if there are any. - // - // Since this is used on FILE but must retrieve the current policy, this - // method first posts GetInitialPolicy() to UI and then resumes in - // CreateStoreWithInitialPolicy(). If |continuation| is not null then it - // will be invoked after the store is created. - // - // CreateStoreFor() can be safely invoked from any method on the FILE thread. - // It posts to UI used |weak_this_on_ui_|, so that the task is dropped if - // ShutdownOnUI() has been invoked. Otherwise, GetInitialPolicy() executes - // on UI and can safely post CreateStoreWithInitialPolicy to FILE. - // CreateStoreWithInitialPolicy then guarantees that a store for - // |extension_id| exists or is created, and then executes the |continuation|; - // so when the |continuation| executes, a store for |extension_id| is - // guaranteed to exist. - void CreateStoreFor(const std::string& extension_id, - bool notify_if_changed, - const base::Closure& continuation); - - // Helper for CreateStoreFor, invoked on UI. - void GetInitialPolicy(const std::string& extension_id, - bool notify_if_changed, - const base::Closure& continuation); - - // Helper for CreateStoreFor, invoked on FILE. - void CreateStoreWithInitialPolicy(const std::string& extension_id, - bool notify_if_changed, - scoped_ptr<policy::PolicyMap> policy, - const base::Closure& continuation); - - // Used to create a WeakPtr valid on the UI thread, so that FILE tasks can - // post back to UI. - base::WeakPtrFactory<ManagedValueStoreCache> weak_factory_; - - // A WeakPtr to |this| that is valid on UI. This is used by tasks on the FILE - // thread to post back to UI. - base::WeakPtr<ManagedValueStoreCache> weak_this_on_ui_; - - // The PolicyService that is observed for policy updates. Lives on UI. - policy::PolicyService* policy_service_; - - // The EventRouter is created before the SettingsFrontend (which owns the - // instance of this class), and the SettingsFrontend is also destroyed before - // the EventRouter is. |event_router_| is thus valid for the lifetime of this - // object, until ShutdownOnUI() is invoked. Lives on UI. - EventRouter* event_router_; - - // These live on the FILE thread. - scoped_refptr<SettingsStorageFactory> storage_factory_; - scoped_refptr<SettingsObserverList> observers_; - FilePath base_path_; - - // All the PolicyValueStores live on the FILE thread, and |store_map_| can be - // accessed only on the FILE thread as well. - PolicyValueStoreMap store_map_; - - DISALLOW_COPY_AND_ASSIGN(ManagedValueStoreCache); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_MANAGED_VALUE_STORE_CACHE_H_ diff --git a/chrome/browser/extensions/settings/policy_value_store.cc b/chrome/browser/extensions/settings/policy_value_store.cc deleted file mode 100644 index 88e2de8..0000000 --- a/chrome/browser/extensions/settings/policy_value_store.cc +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/policy_value_store.h" - -#include "base/logging.h" -#include "base/values.h" -#include "chrome/browser/extensions/settings/settings_namespace.h" -#include "chrome/browser/policy/policy_map.h" -#include "chrome/browser/policy/policy_types.h" -#include "chrome/browser/value_store/value_store_change.h" -#include "content/public/browser/browser_thread.h" - -using content::BrowserThread; - -namespace extensions { - -namespace { - -const char kReadOnlyStoreErrorMessage[] = "This is a read-only store."; - -ValueStore::WriteResult WriteResultError() { - return ValueStore::MakeWriteResult(kReadOnlyStoreErrorMessage); -} - -} // namespace - -PolicyValueStore::PolicyValueStore( - const std::string& extension_id, - const scoped_refptr<SettingsObserverList>& observers, - scoped_ptr<ValueStore> delegate) - : extension_id_(extension_id), - observers_(observers), - delegate_(delegate.Pass()) {} - -PolicyValueStore::~PolicyValueStore() {} - -void PolicyValueStore::SetCurrentPolicy(const policy::PolicyMap& policy, - bool notify_if_changed) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - // Convert |policy| to a dictionary value. Only include mandatory policies - // for now. - base::DictionaryValue current_policy; - for (policy::PolicyMap::const_iterator it = policy.begin(); - it != policy.end(); ++it) { - if (it->second.level == policy::POLICY_LEVEL_MANDATORY) { - current_policy.SetWithoutPathExpansion( - it->first, it->second.value->DeepCopy()); - } - } - - // Get the previous policies stored in the database. - // TODO(joaodasilva): it'd be better to have a less expensive way of - // determining which keys are currently stored, or of determining which keys - // must be removed. - base::DictionaryValue previous_policy; - ValueStore::ReadResult read_result = delegate_->Get(); - if (read_result->HasError()) { - LOG(WARNING) << "Failed to read managed settings for extension " - << extension_id_ << ": " << read_result->error(); - // Leave |previous_policy| empty, so that events are generated for every - // policy in |current_policy|. - } else { - read_result->settings()->Swap(&previous_policy); - } - - // Now get two lists of changes: changes after setting the current policies, - // and changes after removing old policies that aren't in |current_policy| - // anymore. - std::vector<std::string> removed_keys; - for (base::DictionaryValue::Iterator it(previous_policy); - it.HasNext(); it.Advance()) { - if (!current_policy.HasKey(it.key())) - removed_keys.push_back(it.key()); - } - - ValueStoreChangeList changes; - - WriteResult result = delegate_->Remove(removed_keys); - if (!result->HasError()) { - changes.insert( - changes.end(), result->changes().begin(), result->changes().end()); - } - - // IGNORE_QUOTA because these settings aren't writable by the extension, and - // are configured by the domain administrator. - ValueStore::WriteOptions options = ValueStore::IGNORE_QUOTA; - result = delegate_->Set(options, current_policy); - if (!result->HasError()) { - changes.insert( - changes.end(), result->changes().begin(), result->changes().end()); - } - - if (!changes.empty() && notify_if_changed) { - observers_->Notify( - &SettingsObserver::OnSettingsChanged, - extension_id_, - settings_namespace::MANAGED, - ValueStoreChange::ToJson(changes)); - } -} - -void PolicyValueStore::DeleteStorage() { - // This is called from our owner, indicating that storage for this extension - // should be removed. - delegate_->Clear(); -} - -size_t PolicyValueStore::GetBytesInUse(const std::string& key) { - // LeveldbValueStore doesn't implement this; and the underlying database - // isn't acccessible to the extension in any case; from the extension's - // perspective this is a read-only store. - return 0; -} - -size_t PolicyValueStore::GetBytesInUse(const std::vector<std::string>& keys) { - // See note above. - return 0; -} - -size_t PolicyValueStore::GetBytesInUse() { - // See note above. - return 0; -} - -ValueStore::ReadResult PolicyValueStore::Get(const std::string& key) { - return delegate_->Get(key); -} - -ValueStore::ReadResult PolicyValueStore::Get( - const std::vector<std::string>& keys) { - return delegate_->Get(keys); -} - -ValueStore::ReadResult PolicyValueStore::Get() { - return delegate_->Get(); -} - -ValueStore::WriteResult PolicyValueStore::Set( - WriteOptions options, const std::string& key, const base::Value& value) { - return WriteResultError(); -} - -ValueStore::WriteResult PolicyValueStore::Set( - WriteOptions options, const base::DictionaryValue& settings) { - return WriteResultError(); -} - -ValueStore::WriteResult PolicyValueStore::Remove(const std::string& key) { - return WriteResultError(); -} - -ValueStore::WriteResult PolicyValueStore::Remove( - const std::vector<std::string>& keys) { - return WriteResultError(); -} - -ValueStore::WriteResult PolicyValueStore::Clear() { - return WriteResultError(); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/policy_value_store.h b/chrome/browser/extensions/settings/policy_value_store.h deleted file mode 100644 index adf5129..0000000 --- a/chrome/browser/extensions/settings/policy_value_store.h +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_POLICY_VALUE_STORE_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_POLICY_VALUE_STORE_H_ - -#include <string> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/extensions/settings/settings_observer.h" -#include "chrome/browser/value_store/value_store.h" - -namespace policy { -class PolicyMap; -} - -namespace extensions { - -// A ValueStore that is backed by another, persistent ValueStore, and stores -// the policies for a specific extension there. This ValueStore is used to -// run the function of the storage.managed namespace; it's read-only for the -// extension. The ManagedValueStoreCache sends updated policy to this store -// and manages its lifetime. -class PolicyValueStore : public ValueStore { - public: - PolicyValueStore(const std::string& extension_id, - const scoped_refptr<SettingsObserverList>& observers, - scoped_ptr<ValueStore> delegate); - virtual ~PolicyValueStore(); - - // Stores |policy| in the persistent database represented by the |delegate_|. - // If |notify_if_changed| and |policy| differs from the previously persisted - // version, then a notification is sent to the |observers_| with a list of the - // changes detected. - void SetCurrentPolicy(const policy::PolicyMap& policy, - bool notify_if_changed); - - // Clears all the stored data and deletes the database. - void DeleteStorage(); - - // ValueStore implementation: - virtual size_t GetBytesInUse(const std::string& key) OVERRIDE; - virtual size_t GetBytesInUse(const std::vector<std::string>& keys) OVERRIDE; - virtual size_t GetBytesInUse() OVERRIDE; - virtual ReadResult Get(const std::string& key) OVERRIDE; - virtual ReadResult Get(const std::vector<std::string>& keys) OVERRIDE; - virtual ReadResult Get() OVERRIDE; - virtual WriteResult Set( - WriteOptions options, - const std::string& key, - const base::Value& value) OVERRIDE; - virtual WriteResult Set( - WriteOptions options, const base::DictionaryValue& values) OVERRIDE; - virtual WriteResult Remove(const std::string& key) OVERRIDE; - virtual WriteResult Remove(const std::vector<std::string>& keys) OVERRIDE; - virtual WriteResult Clear() OVERRIDE; - - // For unit tests. - ValueStore* delegate() { return delegate_.get(); } - - private: - std::string extension_id_; - scoped_refptr<SettingsObserverList> observers_; - scoped_ptr<ValueStore> delegate_; - - DISALLOW_COPY_AND_ASSIGN(PolicyValueStore); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_POLICY_VALUE_STORE_H_ diff --git a/chrome/browser/extensions/settings/policy_value_store_unittest.cc b/chrome/browser/extensions/settings/policy_value_store_unittest.cc deleted file mode 100644 index 0d7fa45..0000000 --- a/chrome/browser/extensions/settings/policy_value_store_unittest.cc +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/policy_value_store.h" - -#include "base/file_path.h" -#include "base/files/scoped_temp_dir.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop.h" -#include "chrome/browser/extensions/settings/settings_observer.h" -#include "chrome/browser/policy/policy_map.h" -#include "chrome/browser/value_store/leveldb_value_store.h" -#include "chrome/browser/value_store/value_store_unittest.h" -#include "content/public/test/test_browser_thread.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; -using testing::Mock; - -namespace extensions { - -namespace { - -const char kTestExtensionId[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - -class MockSettingsObserver : public SettingsObserver { - public: - MOCK_METHOD3(OnSettingsChanged, void( - const std::string& extension_id, - settings_namespace::Namespace settings_namespace, - const std::string& changes_json)); -}; - -// Extends PolicyValueStore by overriding the mutating methods, so that the -// Get() base implementation can be tested with the ValueStoreTest parameterized -// tests. -class MutablePolicyValueStore : public PolicyValueStore { - public: - explicit MutablePolicyValueStore(const FilePath& path) - : PolicyValueStore(kTestExtensionId, - make_scoped_refptr(new SettingsObserverList()), - scoped_ptr<ValueStore>(new LeveldbValueStore(path))) {} - virtual ~MutablePolicyValueStore() {} - - virtual WriteResult Set( - WriteOptions options, - const std::string& key, - const base::Value& value) OVERRIDE { - return delegate()->Set(options, key, value); - } - - virtual WriteResult Set( - WriteOptions options, const base::DictionaryValue& values) OVERRIDE { - return delegate()->Set(options, values); - } - - virtual WriteResult Remove(const std::string& key) OVERRIDE { - return delegate()->Remove(key); - } - - virtual WriteResult Remove(const std::vector<std::string>& keys) OVERRIDE { - return delegate()->Remove(keys); - } - - virtual WriteResult Clear() OVERRIDE { - return delegate()->Clear(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MutablePolicyValueStore); -}; - -ValueStore* Param(const FilePath& file_path) { - return new MutablePolicyValueStore(file_path); -} - -} // namespace - -INSTANTIATE_TEST_CASE_P( - PolicyValueStoreTest, - ValueStoreTest, - testing::Values(&Param)); - -class PolicyValueStoreTest : public testing::Test { - public: - PolicyValueStoreTest() - : file_thread_(content::BrowserThread::FILE, &loop_) {} - virtual ~PolicyValueStoreTest() {} - - virtual void SetUp() OVERRIDE { - ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); - observers_ = new SettingsObserverList(); - observers_->AddObserver(&observer_); - store_.reset(new PolicyValueStore( - kTestExtensionId, - observers_, - scoped_ptr<ValueStore>( - new LeveldbValueStore(scoped_temp_dir_.path())))); - } - - virtual void TearDown() OVERRIDE { - observers_->RemoveObserver(&observer_); - store_.reset(); - } - - protected: - base::ScopedTempDir scoped_temp_dir_; - MessageLoop loop_; - content::TestBrowserThread file_thread_; - scoped_ptr<PolicyValueStore> store_; - MockSettingsObserver observer_; - scoped_refptr<SettingsObserverList> observers_; -}; - -TEST_F(PolicyValueStoreTest, DontProvideRecommendedPolicies) { - policy::PolicyMap policies; - base::FundamentalValue expected(123); - policies.Set("must", policy::POLICY_LEVEL_MANDATORY, - policy::POLICY_SCOPE_USER, expected.DeepCopy()); - policies.Set("may", policy::POLICY_LEVEL_RECOMMENDED, - policy::POLICY_SCOPE_USER, base::Value::CreateIntegerValue(456)); - store_->SetCurrentPolicy(policies, false); - ValueStore::ReadResult result = store_->Get(); - ASSERT_FALSE(result->HasError()); - EXPECT_EQ(1u, result->settings()->size()); - base::Value* value = NULL; - EXPECT_FALSE(result->settings()->Get("may", &value)); - EXPECT_TRUE(result->settings()->Get("must", &value)); - EXPECT_TRUE(base::Value::Equals(&expected, value)); -} - -TEST_F(PolicyValueStoreTest, ReadOnly) { - ValueStore::WriteOptions options = ValueStore::DEFAULTS; - - base::StringValue string_value("value"); - EXPECT_TRUE(store_->Set(options, "key", string_value)->HasError()); - - base::DictionaryValue dict; - dict.SetString("key", "value"); - EXPECT_TRUE(store_->Set(options, dict)->HasError()); - - EXPECT_TRUE(store_->Remove("key")->HasError()); - std::vector<std::string> keys; - keys.push_back("key"); - EXPECT_TRUE(store_->Remove(keys)->HasError()); - EXPECT_TRUE(store_->Clear()->HasError()); -} - -TEST_F(PolicyValueStoreTest, NotifyOnChanges) { - policy::PolicyMap policies; - policies.Set("aaa", policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, - base::Value::CreateStringValue("111")); - EXPECT_CALL(observer_, OnSettingsChanged(_, _, _)).Times(0); - // No notification when setting the initial policy. - store_->SetCurrentPolicy(policies, false); - loop_.RunUntilIdle(); - Mock::VerifyAndClearExpectations(&observer_); - - // And no notifications on changes when not asked for. - policies.Set("aaa", policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, - base::Value::CreateStringValue("222")); - policies.Set("bbb", policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, - base::Value::CreateStringValue("223")); - EXPECT_CALL(observer_, OnSettingsChanged(_, _, _)).Times(0); - store_->SetCurrentPolicy(policies, false); - loop_.RunUntilIdle(); - Mock::VerifyAndClearExpectations(&observer_); - - // Notify when new policies are added. - ValueStoreChangeList changes; - base::StringValue value("333"); - changes.push_back(ValueStoreChange("ccc", NULL, value.DeepCopy())); - policies.Set("ccc", policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, - value.DeepCopy()); - EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, - settings_namespace::MANAGED, - ValueStoreChange::ToJson(changes))); - store_->SetCurrentPolicy(policies, true); - loop_.RunUntilIdle(); - Mock::VerifyAndClearExpectations(&observer_); - - // Notify when policies change. - changes.clear(); - base::StringValue new_value("444"); - changes.push_back( - ValueStoreChange("ccc", value.DeepCopy(), new_value.DeepCopy())); - policies.Set("ccc", policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, - new_value.DeepCopy()); - EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, - settings_namespace::MANAGED, - ValueStoreChange::ToJson(changes))); - store_->SetCurrentPolicy(policies, true); - loop_.RunUntilIdle(); - Mock::VerifyAndClearExpectations(&observer_); - - // Notify when policies are removed. - changes.clear(); - changes.push_back(ValueStoreChange("ccc", new_value.DeepCopy(), NULL)); - policies.Erase("ccc"); - EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, - settings_namespace::MANAGED, - ValueStoreChange::ToJson(changes))); - store_->SetCurrentPolicy(policies, true); - loop_.RunUntilIdle(); - Mock::VerifyAndClearExpectations(&observer_); - - // Don't notify when there aren't changes. - EXPECT_CALL(observer_, OnSettingsChanged(_, _, _)).Times(0); - store_->SetCurrentPolicy(policies, true); - loop_.RunUntilIdle(); - Mock::VerifyAndClearExpectations(&observer_); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/setting_sync_data.cc b/chrome/browser/extensions/settings/setting_sync_data.cc deleted file mode 100644 index 4baf04c..0000000 --- a/chrome/browser/extensions/settings/setting_sync_data.cc +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/setting_sync_data.h" - -#include "base/json/json_reader.h" -#include "base/json/json_writer.h" -#include "sync/api/sync_data.h" -#include "sync/protocol/app_setting_specifics.pb.h" -#include "sync/protocol/extension_setting_specifics.pb.h" -#include "sync/protocol/sync.pb.h" - -namespace extensions { - -SettingSyncData::SettingSyncData( - const syncer::SyncChange& sync_change) { - Init(sync_change.change_type(), sync_change.sync_data()); -} - -SettingSyncData::SettingSyncData( - const syncer::SyncData& sync_data) { - Init(syncer::SyncChange::ACTION_INVALID, sync_data); -} - -void SettingSyncData::Init( - syncer::SyncChange::SyncChangeType change_type, - const syncer::SyncData& sync_data) { - DCHECK(!internal_.get()); - sync_pb::EntitySpecifics specifics = sync_data.GetSpecifics(); - // The data must only be either extension or app specfics. - DCHECK_NE(specifics.has_extension_setting(), - specifics.has_app_setting()); - if (specifics.has_extension_setting()) { - InitFromExtensionSettingSpecifics( - change_type, - specifics.extension_setting()); - } else if (specifics.has_app_setting()) { - InitFromExtensionSettingSpecifics( - change_type, - specifics.app_setting().extension_setting()); - } -} - -void SettingSyncData::InitFromExtensionSettingSpecifics( - syncer::SyncChange::SyncChangeType change_type, - const sync_pb::ExtensionSettingSpecifics& specifics) { - DCHECK(!internal_.get()); - scoped_ptr<Value> value( - base::JSONReader::Read(specifics.value())); - if (!value.get()) { - LOG(WARNING) << "Specifics for " << specifics.extension_id() << "/" << - specifics.key() << " had bad JSON for value: " << specifics.value(); - value.reset(new DictionaryValue()); - } - internal_ = new Internal( - change_type, - specifics.extension_id(), - specifics.key(), - value.Pass()); -} - -SettingSyncData::SettingSyncData( - syncer::SyncChange::SyncChangeType change_type, - const std::string& extension_id, - const std::string& key, - scoped_ptr<Value> value) - : internal_(new Internal(change_type, extension_id, key, value.Pass())) {} - -SettingSyncData::~SettingSyncData() {} - -syncer::SyncChange::SyncChangeType SettingSyncData::change_type() const { - return internal_->change_type_; -} - -const std::string& SettingSyncData::extension_id() const { - return internal_->extension_id_; -} - -const std::string& SettingSyncData::key() const { - return internal_->key_; -} - -const Value& SettingSyncData::value() const { - return *internal_->value_; -} - -SettingSyncData::Internal::Internal( - syncer::SyncChange::SyncChangeType change_type, - const std::string& extension_id, - const std::string& key, - scoped_ptr<Value> value) - : change_type_(change_type), - extension_id_(extension_id), - key_(key), - value_(value.Pass()) { - DCHECK(value_.get()); -} - -SettingSyncData::Internal::~Internal() {} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/setting_sync_data.h b/chrome/browser/extensions/settings/setting_sync_data.h deleted file mode 100644 index fc9d1d4..0000000 --- a/chrome/browser/extensions/settings/setting_sync_data.h +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTING_SYNC_DATA_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTING_SYNC_DATA_H_ - -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/values.h" -#include "sync/api/sync_change.h" - -namespace syncer { -class SyncData; -} - -namespace sync_pb { -class ExtensionSettingSpecifics; -} - -namespace extensions { - -// Container for data interpreted from sync data/changes for an extension or -// app setting. Safe and efficient to copy. -class SettingSyncData { - public: - // Creates from a sync change. - explicit SettingSyncData(const syncer::SyncChange& sync_change); - - // Creates from sync data. |change_type| will be ACTION_INVALID. - explicit SettingSyncData(const syncer::SyncData& sync_data); - - // Creates explicitly. - SettingSyncData( - syncer::SyncChange::SyncChangeType change_type, - const std::string& extension_id, - const std::string& key, - scoped_ptr<Value> value); - - ~SettingSyncData(); - - // Returns the type of the sync change; may be ACTION_INVALID. - syncer::SyncChange::SyncChangeType change_type() const; - - // Returns the extension id the setting is for. - const std::string& extension_id() const; - - // Returns the settings key. - const std::string& key() const; - - // Returns the value of the setting. - const Value& value() const; - - private: - // Ref-counted container for the data. - // TODO(kalman): Use browser_sync::Immutable<Internal>. - class Internal : public base::RefCountedThreadSafe<Internal> { - public: - Internal( - syncer::SyncChange::SyncChangeType change_type, - const std::string& extension_id, - const std::string& key, - scoped_ptr<Value> value); - - syncer::SyncChange::SyncChangeType change_type_; - std::string extension_id_; - std::string key_; - scoped_ptr<Value> value_; - - private: - friend class base::RefCountedThreadSafe<Internal>; - ~Internal(); - }; - - // Initializes internal_ from sync data for an extension or app setting. - void Init(syncer::SyncChange::SyncChangeType change_type, - const syncer::SyncData& sync_data); - - // Initializes internal_ from extension specifics. - void InitFromExtensionSettingSpecifics( - syncer::SyncChange::SyncChangeType change_type, - const sync_pb::ExtensionSettingSpecifics& specifics); - - scoped_refptr<Internal> internal_; -}; - -typedef std::vector<SettingSyncData> SettingSyncDataList; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTING_SYNC_DATA_H_ diff --git a/chrome/browser/extensions/settings/settings_api.cc b/chrome/browser/extensions/settings/settings_api.cc deleted file mode 100644 index 35f4eaf..0000000 --- a/chrome/browser/extensions/settings/settings_api.cc +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/settings_api.h" - -#include <string> -#include <vector> - -#include "base/bind.h" -#include "base/stringprintf.h" -#include "base/values.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/extensions_quota_service.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/extensions/api/storage.h" -#include "content/public/browser/browser_thread.h" - -namespace extensions { - -using content::BrowserThread; - -namespace { -const char kUnsupportedArgumentType[] = "Unsupported argument type"; -const char kInvalidNamespaceErrorMessage[] = - "\"%s\" is not available in this instance of Chrome"; -const char kManagedNamespaceDisabledErrorMessage[] = - "\"managed\" is disabled. Use \"--%s\" to enable it."; -const char kStorageErrorMessage[] = "Storage error"; -} // namespace - -// SettingsFunction - -SettingsFunction::SettingsFunction() - : settings_namespace_(settings_namespace::INVALID) {} - -SettingsFunction::~SettingsFunction() {} - -bool SettingsFunction::ShouldSkipQuotaLimiting() const { - // Only apply quota if this is for sync storage. - std::string settings_namespace_string; - if (!args_->GetString(0, &settings_namespace_string)) { - // This is an error but it will be caught in RunImpl(), there is no - // mechanism to signify an error from this function. - return false; - } - return settings_namespace_string != "sync"; -} - -bool SettingsFunction::RunImpl() { - std::string settings_namespace_string; - EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &settings_namespace_string)); - args_->Remove(0, NULL); - settings_namespace_ = - settings_namespace::FromString(settings_namespace_string); - EXTENSION_FUNCTION_VALIDATE( - settings_namespace_ != settings_namespace::INVALID); - - SettingsFrontend* frontend = - profile()->GetExtensionService()->settings_frontend(); - if (!frontend->IsStorageEnabled(settings_namespace_)) { - error_ = base::StringPrintf(kInvalidNamespaceErrorMessage, - settings_namespace_string.c_str()); - return false; - } - - observers_ = frontend->GetObservers(); - frontend->RunWithStorage( - extension_id(), - settings_namespace_, - base::Bind(&SettingsFunction::AsyncRunWithStorage, this)); - return true; -} - -void SettingsFunction::AsyncRunWithStorage(ValueStore* storage) { - bool success = RunWithStorage(storage); - BrowserThread::PostTask( - BrowserThread::UI, - FROM_HERE, - base::Bind(&SettingsFunction::SendResponse, this, success)); -} - -bool SettingsFunction::UseReadResult(ValueStore::ReadResult result) { - if (result->HasError()) { - error_ = result->error(); - return false; - } - - SetResult(result->settings().release()); - return true; -} - -bool SettingsFunction::UseWriteResult(ValueStore::WriteResult result) { - if (result->HasError()) { - error_ = result->error(); - return false; - } - - if (!result->changes().empty()) { - observers_->Notify( - &SettingsObserver::OnSettingsChanged, - extension_id(), - settings_namespace_, - ValueStoreChange::ToJson(result->changes())); - } - - return true; -} - -// Concrete settings functions - -namespace { - -// Adds all StringValues from a ListValue to a vector of strings. -void AddAllStringValues(const ListValue& from, std::vector<std::string>* to) { - DCHECK(to->empty()); - std::string as_string; - for (ListValue::const_iterator it = from.begin(); it != from.end(); ++it) { - if ((*it)->GetAsString(&as_string)) { - to->push_back(as_string); - } - } -} - -// Gets the keys of a DictionaryValue. -std::vector<std::string> GetKeys(const DictionaryValue& dict) { - std::vector<std::string> keys; - for (DictionaryValue::key_iterator it = dict.begin_keys(); - it != dict.end_keys(); ++it) { - keys.push_back(*it); - } - return keys; -} - -// Creates quota heuristics for settings modification. -void GetModificationQuotaLimitHeuristics(QuotaLimitHeuristics* heuristics) { - QuotaLimitHeuristic::Config longLimitConfig = { - // See storage.json for current value. - api::storage::sync::MAX_WRITE_OPERATIONS_PER_HOUR, - base::TimeDelta::FromHours(1) - }; - heuristics->push_back( - new ExtensionsQuotaService::TimedLimit( - longLimitConfig, - new QuotaLimitHeuristic::SingletonBucketMapper(), - "MAX_WRITE_OPERATIONS_PER_HOUR")); - - // A max of 10 operations per minute, sustained over 10 minutes. - QuotaLimitHeuristic::Config shortLimitConfig = { - // See storage.json for current value. - api::storage::sync::MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE, - base::TimeDelta::FromMinutes(1) - }; - heuristics->push_back( - new ExtensionsQuotaService::SustainedLimit( - base::TimeDelta::FromMinutes(10), - shortLimitConfig, - new QuotaLimitHeuristic::SingletonBucketMapper(), - "MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE")); -}; - -} // namespace - -bool GetSettingsFunction::RunWithStorage(ValueStore* storage) { - Value* input = NULL; - EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &input)); - - switch (input->GetType()) { - case Value::TYPE_NULL: - return UseReadResult(storage->Get()); - - case Value::TYPE_STRING: { - std::string as_string; - input->GetAsString(&as_string); - return UseReadResult(storage->Get(as_string)); - } - - case Value::TYPE_LIST: { - std::vector<std::string> as_string_list; - AddAllStringValues(*static_cast<ListValue*>(input), &as_string_list); - return UseReadResult(storage->Get(as_string_list)); - } - - case Value::TYPE_DICTIONARY: { - DictionaryValue* as_dict = static_cast<DictionaryValue*>(input); - ValueStore::ReadResult result = storage->Get(GetKeys(*as_dict)); - if (result->HasError()) { - return UseReadResult(result.Pass()); - } - - DictionaryValue* with_default_values = as_dict->DeepCopy(); - with_default_values->MergeDictionary(result->settings().get()); - return UseReadResult( - ValueStore::MakeReadResult(with_default_values)); - } - - default: - return UseReadResult( - ValueStore::MakeReadResult(kUnsupportedArgumentType)); - } -} - -bool GetBytesInUseSettingsFunction::RunWithStorage(ValueStore* storage) { - Value* input = NULL; - EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &input)); - - size_t bytes_in_use = 0; - - switch (input->GetType()) { - case Value::TYPE_NULL: - bytes_in_use = storage->GetBytesInUse(); - break; - - case Value::TYPE_STRING: { - std::string as_string; - input->GetAsString(&as_string); - bytes_in_use = storage->GetBytesInUse(as_string); - break; - } - - case Value::TYPE_LIST: { - std::vector<std::string> as_string_list; - AddAllStringValues(*static_cast<ListValue*>(input), &as_string_list); - bytes_in_use = storage->GetBytesInUse(as_string_list); - break; - } - - default: - error_ = kUnsupportedArgumentType; - return false; - } - - SetResult(Value::CreateIntegerValue(bytes_in_use)); - return true; -} - -bool SetSettingsFunction::RunWithStorage(ValueStore* storage) { - DictionaryValue* input = NULL; - EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &input)); - return UseWriteResult(storage->Set(ValueStore::DEFAULTS, *input)); -} - -void SetSettingsFunction::GetQuotaLimitHeuristics( - QuotaLimitHeuristics* heuristics) const { - GetModificationQuotaLimitHeuristics(heuristics); -} - -bool RemoveSettingsFunction::RunWithStorage(ValueStore* storage) { - Value* input = NULL; - EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &input)); - - switch (input->GetType()) { - case Value::TYPE_STRING: { - std::string as_string; - input->GetAsString(&as_string); - return UseWriteResult(storage->Remove(as_string)); - } - - case Value::TYPE_LIST: { - std::vector<std::string> as_string_list; - AddAllStringValues(*static_cast<ListValue*>(input), &as_string_list); - return UseWriteResult(storage->Remove(as_string_list)); - } - - default: - return UseWriteResult( - ValueStore::MakeWriteResult(kUnsupportedArgumentType)); - }; -} - -void RemoveSettingsFunction::GetQuotaLimitHeuristics( - QuotaLimitHeuristics* heuristics) const { - GetModificationQuotaLimitHeuristics(heuristics); -} - -bool ClearSettingsFunction::RunWithStorage(ValueStore* storage) { - return UseWriteResult(storage->Clear()); -} - -void ClearSettingsFunction::GetQuotaLimitHeuristics( - QuotaLimitHeuristics* heuristics) const { - GetModificationQuotaLimitHeuristics(heuristics); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_api.h b/chrome/browser/extensions/settings/settings_api.h deleted file mode 100644 index 38a18d5..0000000 --- a/chrome/browser/extensions/settings/settings_api.h +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_API_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_API_H_ - -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "chrome/browser/extensions/extension_function.h" -#include "chrome/browser/extensions/settings/settings_namespace.h" -#include "chrome/browser/extensions/settings/settings_observer.h" -#include "chrome/browser/value_store/value_store.h" - -namespace extensions { - -// Superclass of all settings functions. -// -// NOTE: these all have "*SettingsFunction" names left over from when the API -// was called the "Settings API" (now "Storage API"). -// TODO(kalman): Rename these functions, and all files under -// chrome/browser/extensions/settings. -class SettingsFunction : public AsyncExtensionFunction { - protected: - SettingsFunction(); - virtual ~SettingsFunction(); - - // ExtensionFunction: - virtual bool ShouldSkipQuotaLimiting() const OVERRIDE; - virtual bool RunImpl() OVERRIDE; - - // Extension settings function implementations should do their work here. - // The SettingsFrontend makes sure this is posted to the appropriate thread. - // Implementations should fill in args themselves, though (like RunImpl) - // may return false to imply failure. - virtual bool RunWithStorage(ValueStore* storage) = 0; - - // Sets error_ or result_ depending on the value of a storage ReadResult, and - // returns whether the result implies success (i.e. !error). - bool UseReadResult(ValueStore::ReadResult result); - - // Sets error_ depending on the value of a storage WriteResult, sends a - // change notification if needed, and returns whether the result implies - // success (i.e. !error). - bool UseWriteResult(ValueStore::WriteResult result); - - private: - // Called via PostTask from RunImpl. Calls RunWithStorage and then - // SendResponse with its success value. - void AsyncRunWithStorage(ValueStore* storage); - - // The settings namespace the call was for. For example, SYNC if the API - // call was chrome.settings.experimental.sync..., LOCAL if .local, etc. - settings_namespace::Namespace settings_namespace_; - - // Observers, cached so that it's only grabbed from the UI thread. - scoped_refptr<SettingsObserverList> observers_; -}; - -class GetSettingsFunction : public SettingsFunction { - public: - DECLARE_EXTENSION_FUNCTION_NAME("storage.get"); - - protected: - virtual ~GetSettingsFunction() {} - - // SettingsFunction: - virtual bool RunWithStorage(ValueStore* storage) OVERRIDE; -}; - -class SetSettingsFunction : public SettingsFunction { - public: - DECLARE_EXTENSION_FUNCTION_NAME("storage.set"); - - protected: - virtual ~SetSettingsFunction() {} - - // SettingsFunction: - virtual bool RunWithStorage(ValueStore* storage) OVERRIDE; - - // ExtensionFunction: - virtual void GetQuotaLimitHeuristics( - QuotaLimitHeuristics* heuristics) const OVERRIDE; -}; - -class RemoveSettingsFunction : public SettingsFunction { - public: - DECLARE_EXTENSION_FUNCTION_NAME("storage.remove"); - - protected: - virtual ~RemoveSettingsFunction() {} - - // SettingsFunction: - virtual bool RunWithStorage(ValueStore* storage) OVERRIDE; - - // ExtensionFunction: - virtual void GetQuotaLimitHeuristics( - QuotaLimitHeuristics* heuristics) const OVERRIDE; -}; - -class ClearSettingsFunction : public SettingsFunction { - public: - DECLARE_EXTENSION_FUNCTION_NAME("storage.clear"); - - protected: - virtual ~ClearSettingsFunction() {} - - // SettingsFunction: - virtual bool RunWithStorage(ValueStore* storage) OVERRIDE; - - // ExtensionFunction: - virtual void GetQuotaLimitHeuristics( - QuotaLimitHeuristics* heuristics) const OVERRIDE; -}; - -class GetBytesInUseSettingsFunction : public SettingsFunction { - public: - DECLARE_EXTENSION_FUNCTION_NAME("storage.getBytesInUse"); - - protected: - virtual ~GetBytesInUseSettingsFunction() {} - - // SettingsFunction: - virtual bool RunWithStorage(ValueStore* storage) OVERRIDE; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_API_H_ diff --git a/chrome/browser/extensions/settings/settings_apitest.cc b/chrome/browser/extensions/settings/settings_apitest.cc deleted file mode 100644 index acfa22d..0000000 --- a/chrome/browser/extensions/settings/settings_apitest.cc +++ /dev/null @@ -1,518 +0,0 @@ -// Copyright (c) 2012 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 "base/bind.h" -#include "base/json/json_writer.h" -#include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/extension_test_message_listener.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" -#include "chrome/browser/extensions/settings/settings_namespace.h" -#include "chrome/browser/extensions/settings/settings_sync_util.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/extensions/value_builder.h" -#include "chrome/test/base/ui_test_utils.h" -#include "sync/api/sync_change.h" -#include "sync/api/sync_change_processor.h" -#include "sync/api/sync_error_factory.h" -#include "sync/api/sync_error_factory_mock.h" -#include "testing/gmock/include/gmock/gmock.h" - -#if defined(ENABLE_CONFIGURATION_POLICY) -#include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/mock_configuration_policy_provider.h" -#include "chrome/browser/policy/policy_bundle.h" -#include "chrome/browser/policy/policy_map.h" -#endif - -namespace extensions { - -using settings_namespace::FromString; -using settings_namespace::LOCAL; -using settings_namespace::MANAGED; -using settings_namespace::Namespace; -using settings_namespace::SYNC; -using settings_namespace::ToString; -using testing::Return; - -namespace { - -// TODO(kalman): test both EXTENSION_SETTINGS and APP_SETTINGS. -const syncer::ModelType kModelType = syncer::EXTENSION_SETTINGS; - -// The managed_storage extension has a key defined in its manifest, so that -// its extension ID is well-known and the policy system can push policies for -// the extension. -const char kManagedStorageExtensionId[] = "kjmkgkdkpedkejedfhmfcenooemhbpbo"; - -class NoopSyncChangeProcessor : public syncer::SyncChangeProcessor { - public: - virtual syncer::SyncError ProcessSyncChanges( - const tracked_objects::Location& from_here, - const syncer::SyncChangeList& change_list) OVERRIDE { - return syncer::SyncError(); - } - - virtual ~NoopSyncChangeProcessor() {}; -}; - -class SyncChangeProcessorDelegate : public syncer::SyncChangeProcessor { - public: - explicit SyncChangeProcessorDelegate(syncer::SyncChangeProcessor* recipient) - : recipient_(recipient) { - DCHECK(recipient_); - } - virtual ~SyncChangeProcessorDelegate() {} - - // syncer::SyncChangeProcessor implementation. - virtual syncer::SyncError ProcessSyncChanges( - const tracked_objects::Location& from_here, - const syncer::SyncChangeList& change_list) OVERRIDE { - return recipient_->ProcessSyncChanges(from_here, change_list); - } - - private: - // The recipient of all sync changes. - syncer::SyncChangeProcessor* recipient_; - - DISALLOW_COPY_AND_ASSIGN(SyncChangeProcessorDelegate); -}; - -} // namespace - -class ExtensionSettingsApiTest : public ExtensionApiTest { - protected: - virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { - ExtensionApiTest::SetUpInProcessBrowserTestFixture(); - -#if defined(ENABLE_CONFIGURATION_POLICY) - EXPECT_CALL(policy_provider_, IsInitializationComplete()) - .WillRepeatedly(Return(true)); - policy::BrowserPolicyConnector::SetPolicyProviderForTesting( - &policy_provider_); -#endif - } - - void ReplyWhenSatisfied( - Namespace settings_namespace, - const std::string& normal_action, - const std::string& incognito_action) { - MaybeLoadAndReplyWhenSatisfied( - settings_namespace, normal_action, incognito_action, NULL, false); - } - - const Extension* LoadAndReplyWhenSatisfied( - Namespace settings_namespace, - const std::string& normal_action, - const std::string& incognito_action, - const std::string& extension_dir) { - return MaybeLoadAndReplyWhenSatisfied( - settings_namespace, - normal_action, - incognito_action, - &extension_dir, - false); - } - - void FinalReplyWhenSatisfied( - Namespace settings_namespace, - const std::string& normal_action, - const std::string& incognito_action) { - MaybeLoadAndReplyWhenSatisfied( - settings_namespace, normal_action, incognito_action, NULL, true); - } - - void InitSync(syncer::SyncChangeProcessor* sync_processor) { - MessageLoop::current()->RunUntilIdle(); - InitSyncWithSyncableService( - sync_processor, - browser()->profile()->GetExtensionService()->settings_frontend()-> - GetBackendForSync(kModelType)); - } - - void SendChanges(const syncer::SyncChangeList& change_list) { - MessageLoop::current()->RunUntilIdle(); - SendChangesToSyncableService( - change_list, - browser()->profile()->GetExtensionService()->settings_frontend()-> - GetBackendForSync(kModelType)); - } - -#if defined(ENABLE_CONFIGURATION_POLICY) - void SetPolicies(const base::DictionaryValue& policies) { - scoped_ptr<policy::PolicyBundle> bundle(new policy::PolicyBundle()); - policy::PolicyMap& policy_map = bundle->Get( - policy::POLICY_DOMAIN_EXTENSIONS, kManagedStorageExtensionId); - policy_map.LoadFrom( - &policies, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER); - policy_provider_.UpdatePolicy(bundle.Pass()); - } -#endif - - private: - const Extension* MaybeLoadAndReplyWhenSatisfied( - Namespace settings_namespace, - const std::string& normal_action, - const std::string& incognito_action, - // May be NULL to imply not loading the extension. - const std::string* extension_dir, - bool is_final_action) { - ExtensionTestMessageListener listener("waiting", true); - ExtensionTestMessageListener listener_incognito("waiting_incognito", true); - - // Only load the extension after the listeners have been set up, to avoid - // initialisation race conditions. - const Extension* extension = NULL; - if (extension_dir) { - extension = LoadExtensionIncognito( - test_data_dir_.AppendASCII("settings").AppendASCII(*extension_dir)); - EXPECT_TRUE(extension); - } - - EXPECT_TRUE(listener.WaitUntilSatisfied()); - EXPECT_TRUE(listener_incognito.WaitUntilSatisfied()); - - listener.Reply( - CreateMessage(settings_namespace, normal_action, is_final_action)); - listener_incognito.Reply( - CreateMessage(settings_namespace, incognito_action, is_final_action)); - return extension; - } - - std::string CreateMessage( - Namespace settings_namespace, - const std::string& action, - bool is_final_action) { - scoped_ptr<DictionaryValue> message(new DictionaryValue()); - message->SetString("namespace", ToString(settings_namespace)); - message->SetString("action", action); - message->SetBoolean("isFinalAction", is_final_action); - std::string message_json; - base::JSONWriter::Write(message.get(), &message_json); - return message_json; - } - - void InitSyncWithSyncableService( - syncer::SyncChangeProcessor* sync_processor, - syncer::SyncableService* settings_service) { - EXPECT_FALSE(settings_service->MergeDataAndStartSyncing( - kModelType, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new SyncChangeProcessorDelegate(sync_processor)), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())).error().IsSet()); - } - - void SendChangesToSyncableService( - const syncer::SyncChangeList& change_list, - syncer::SyncableService* settings_service) { - EXPECT_FALSE( - settings_service->ProcessSyncChanges(FROM_HERE, change_list).IsSet()); - } - - protected: -#if defined(ENABLE_CONFIGURATION_POLICY) - policy::MockConfigurationPolicyProvider policy_provider_; -#endif -}; - -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, SimpleTest) { - ASSERT_TRUE(RunExtensionTest("settings/simple_test")) << message_; -} - -// Structure of this test taken from IncognitoSplitMode. -// Note that only split-mode incognito is tested, because spanning mode -// incognito looks the same as normal mode when the only API activity comes -// from background pages. -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, SplitModeIncognito) { - // We need 2 ResultCatchers because we'll be running the same test in both - // regular and incognito mode. - ResultCatcher catcher, catcher_incognito; - catcher.RestrictToProfile(browser()->profile()); - catcher_incognito.RestrictToProfile( - browser()->profile()->GetOffTheRecordProfile()); - - LoadAndReplyWhenSatisfied(SYNC, - "assertEmpty", "assertEmpty", "split_incognito"); - ReplyWhenSatisfied(SYNC, "noop", "setFoo"); - ReplyWhenSatisfied(SYNC, "assertFoo", "assertFoo"); - ReplyWhenSatisfied(SYNC, "clear", "noop"); - ReplyWhenSatisfied(SYNC, "assertEmpty", "assertEmpty"); - ReplyWhenSatisfied(SYNC, "setFoo", "noop"); - ReplyWhenSatisfied(SYNC, "assertFoo", "assertFoo"); - ReplyWhenSatisfied(SYNC, "noop", "removeFoo"); - FinalReplyWhenSatisfied(SYNC, "assertEmpty", "assertEmpty"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); -} - -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, - OnChangedNotificationsBetweenBackgroundPages) { - // We need 2 ResultCatchers because we'll be running the same test in both - // regular and incognito mode. - ResultCatcher catcher, catcher_incognito; - catcher.RestrictToProfile(browser()->profile()); - catcher_incognito.RestrictToProfile( - browser()->profile()->GetOffTheRecordProfile()); - - LoadAndReplyWhenSatisfied(SYNC, - "assertNoNotifications", "assertNoNotifications", "split_incognito"); - ReplyWhenSatisfied(SYNC, "noop", "setFoo"); - ReplyWhenSatisfied(SYNC, - "assertAddFooNotification", "assertAddFooNotification"); - ReplyWhenSatisfied(SYNC, "clearNotifications", "clearNotifications"); - ReplyWhenSatisfied(SYNC, "removeFoo", "noop"); - FinalReplyWhenSatisfied(SYNC, - "assertDeleteFooNotification", "assertDeleteFooNotification"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); -} - -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, - SyncAndLocalAreasAreSeparate) { - // We need 2 ResultCatchers because we'll be running the same test in both - // regular and incognito mode. - ResultCatcher catcher, catcher_incognito; - catcher.RestrictToProfile(browser()->profile()); - catcher_incognito.RestrictToProfile( - browser()->profile()->GetOffTheRecordProfile()); - - LoadAndReplyWhenSatisfied(SYNC, - "assertNoNotifications", "assertNoNotifications", "split_incognito"); - - ReplyWhenSatisfied(SYNC, "noop", "setFoo"); - ReplyWhenSatisfied(SYNC, "assertFoo", "assertFoo"); - ReplyWhenSatisfied(SYNC, - "assertAddFooNotification", "assertAddFooNotification"); - ReplyWhenSatisfied(LOCAL, "assertEmpty", "assertEmpty"); - ReplyWhenSatisfied(LOCAL, "assertNoNotifications", "assertNoNotifications"); - - ReplyWhenSatisfied(SYNC, "clearNotifications", "clearNotifications"); - - ReplyWhenSatisfied(LOCAL, "setFoo", "noop"); - ReplyWhenSatisfied(LOCAL, "assertFoo", "assertFoo"); - ReplyWhenSatisfied(LOCAL, - "assertAddFooNotification", "assertAddFooNotification"); - ReplyWhenSatisfied(SYNC, "assertFoo", "assertFoo"); - ReplyWhenSatisfied(SYNC, "assertNoNotifications", "assertNoNotifications"); - - ReplyWhenSatisfied(LOCAL, "clearNotifications", "clearNotifications"); - - ReplyWhenSatisfied(LOCAL, "noop", "removeFoo"); - ReplyWhenSatisfied(LOCAL, "assertEmpty", "assertEmpty"); - ReplyWhenSatisfied(LOCAL, - "assertDeleteFooNotification", "assertDeleteFooNotification"); - ReplyWhenSatisfied(SYNC, "assertFoo", "assertFoo"); - ReplyWhenSatisfied(SYNC, "assertNoNotifications", "assertNoNotifications"); - - ReplyWhenSatisfied(LOCAL, "clearNotifications", "clearNotifications"); - - ReplyWhenSatisfied(SYNC, "removeFoo", "noop"); - ReplyWhenSatisfied(SYNC, "assertEmpty", "assertEmpty"); - ReplyWhenSatisfied(SYNC, - "assertDeleteFooNotification", "assertDeleteFooNotification"); - ReplyWhenSatisfied(LOCAL, "assertNoNotifications", "assertNoNotifications"); - FinalReplyWhenSatisfied(LOCAL, "assertEmpty", "assertEmpty"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); -} - -// Disabled, see crbug.com/101110 -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, - DISABLED_OnChangedNotificationsFromSync) { - // We need 2 ResultCatchers because we'll be running the same test in both - // regular and incognito mode. - ResultCatcher catcher, catcher_incognito; - catcher.RestrictToProfile(browser()->profile()); - catcher_incognito.RestrictToProfile( - browser()->profile()->GetOffTheRecordProfile()); - - const Extension* extension = - LoadAndReplyWhenSatisfied(SYNC, - "assertNoNotifications", "assertNoNotifications", "split_incognito"); - const std::string& extension_id = extension->id(); - - NoopSyncChangeProcessor sync_processor; - InitSync(&sync_processor); - - // Set "foo" to "bar" via sync. - syncer::SyncChangeList sync_changes; - StringValue bar("bar"); - sync_changes.push_back(settings_sync_util::CreateAdd( - extension_id, "foo", bar, kModelType)); - SendChanges(sync_changes); - - ReplyWhenSatisfied(SYNC, - "assertAddFooNotification", "assertAddFooNotification"); - ReplyWhenSatisfied(SYNC, "clearNotifications", "clearNotifications"); - - // Remove "foo" via sync. - sync_changes.clear(); - sync_changes.push_back(settings_sync_util::CreateDelete( - extension_id, "foo", kModelType)); - SendChanges(sync_changes); - - FinalReplyWhenSatisfied(SYNC, - "assertDeleteFooNotification", "assertDeleteFooNotification"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); -} - -// Disabled, see crbug.com/101110 -// -// TODO: boring test, already done in the unit tests. What we really should be -// be testing is that the areas don't overlap. -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, - DISABLED_OnChangedNotificationsFromSyncNotSentToLocal) { - // We need 2 ResultCatchers because we'll be running the same test in both - // regular and incognito mode. - ResultCatcher catcher, catcher_incognito; - catcher.RestrictToProfile(browser()->profile()); - catcher_incognito.RestrictToProfile( - browser()->profile()->GetOffTheRecordProfile()); - - const Extension* extension = - LoadAndReplyWhenSatisfied(LOCAL, - "assertNoNotifications", "assertNoNotifications", "split_incognito"); - const std::string& extension_id = extension->id(); - - NoopSyncChangeProcessor sync_processor; - InitSync(&sync_processor); - - // Set "foo" to "bar" via sync. - syncer::SyncChangeList sync_changes; - StringValue bar("bar"); - sync_changes.push_back(settings_sync_util::CreateAdd( - extension_id, "foo", bar, kModelType)); - SendChanges(sync_changes); - - ReplyWhenSatisfied(LOCAL, "assertNoNotifications", "assertNoNotifications"); - - // Remove "foo" via sync. - sync_changes.clear(); - sync_changes.push_back(settings_sync_util::CreateDelete( - extension_id, "foo", kModelType)); - SendChanges(sync_changes); - - FinalReplyWhenSatisfied(LOCAL, - "assertNoNotifications", "assertNoNotifications"); - - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); -} - -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, IsStorageEnabled) { - SettingsFrontend* frontend = - browser()->profile()->GetExtensionService()->settings_frontend(); - EXPECT_TRUE(frontend->IsStorageEnabled(LOCAL)); - EXPECT_TRUE(frontend->IsStorageEnabled(SYNC)); - -#if defined(ENABLE_CONFIGURATION_POLICY) - EXPECT_TRUE(frontend->IsStorageEnabled(MANAGED)); -#else - EXPECT_FALSE(frontend->IsStorageEnabled(MANAGED)); -#endif -} - -#if defined(ENABLE_CONFIGURATION_POLICY) - -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, ManagedStorage) { - // Set policies for the test extension. - scoped_ptr<base::DictionaryValue> policy = extensions::DictionaryBuilder() - .Set("string-policy", "value") - .Set("int-policy", -123) - .Set("double-policy", 456e7) - .SetBoolean("boolean-policy", true) - .Set("list-policy", extensions::ListBuilder() - .Append("one") - .Append("two") - .Append("three")) - .Set("dict-policy", extensions::DictionaryBuilder() - .Set("list", extensions::ListBuilder() - .Append(extensions::DictionaryBuilder() - .Set("one", 1) - .Set("two", 2)) - .Append(extensions::DictionaryBuilder() - .Set("three", 3)))) - .Build(); - SetPolicies(*policy); - // Now run the extension. - ASSERT_TRUE(RunExtensionTest("settings/managed_storage")) << message_; -} - -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, PRE_ManagedStorageEvents) { - ResultCatcher catcher; - - // This test starts without any test extensions installed. - EXPECT_FALSE(GetSingleLoadedExtension()); - message_.clear(); - - // Set policies for the test extension. - scoped_ptr<base::DictionaryValue> policy = extensions::DictionaryBuilder() - .Set("constant-policy", "aaa") - .Set("changes-policy", "bbb") - .Set("deleted-policy", "ccc") - .Build(); - SetPolicies(*policy); - - ExtensionTestMessageListener ready_listener("ready", false); - // Load the extension to install the event listener. - const Extension* extension = LoadExtension( - test_data_dir_.AppendASCII("settings/managed_storage_events")); - ASSERT_TRUE(extension); - // Wait until the extension sends the "ready" message. - ASSERT_TRUE(ready_listener.WaitUntilSatisfied()); - - // Now change the policies and wait until the extension is done. - policy = extensions::DictionaryBuilder() - .Set("constant-policy", "aaa") - .Set("changes-policy", "ddd") - .Set("new-policy", "eee") - .Build(); - SetPolicies(*policy); - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); -} - -// TODO(joaodasilva): This test times out on Vista. http://crbug.com/166261 -#if !defined(OS_WIN) -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, ManagedStorageEvents) { - // This test runs after PRE_ManagedStorageEvents without having deleted the - // profile, so the extension is still around. While the browser restarted the - // policy went back to the empty default, and so the extension should receive - // the corresponding change events. - - ResultCatcher catcher; - - // Verify that the test extension is still installed. - const Extension* extension = GetSingleLoadedExtension(); - ASSERT_TRUE(extension); - EXPECT_EQ(kManagedStorageExtensionId, extension->id()); - - // Running the test again skips the onInstalled callback, and just triggers - // the onChanged notification. - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); -} -#endif // !defined(OS_WIN) - -#endif // defined(ENABLE_CONFIGURATION_POLICY) - -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, ManagedStorageDisabled) { - // Disable the 'managed' namespace. This is redundant when - // ENABLE_CONFIGURATION_POLICY is not defined. - SettingsFrontend* frontend = - browser()->profile()->GetExtensionService()->settings_frontend(); - frontend->DisableStorageForTesting(MANAGED); - EXPECT_FALSE(frontend->IsStorageEnabled(MANAGED)); - // Now run the extension. - ASSERT_TRUE(RunExtensionTest("settings/managed_storage_disabled")) - << message_; -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_backend.cc b/chrome/browser/extensions/settings/settings_backend.cc deleted file mode 100644 index 99ca5e3..0000000 --- a/chrome/browser/extensions/settings/settings_backend.cc +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/settings_backend.h" - -#include "base/file_util.h" -#include "base/logging.h" -#include "chrome/browser/extensions/settings/settings_sync_processor.h" -#include "chrome/browser/extensions/settings/settings_sync_util.h" -#include "chrome/browser/extensions/settings/syncable_settings_storage.h" -#include "content/public/browser/browser_thread.h" -#include "sync/api/sync_error_factory.h" - -using content::BrowserThread; - -namespace extensions { - -SettingsBackend::SettingsBackend( - const scoped_refptr<SettingsStorageFactory>& storage_factory, - const FilePath& base_path, - const SettingsStorageQuotaEnforcer::Limits& quota, - const scoped_refptr<SettingsObserverList>& observers) - : storage_factory_(storage_factory), - base_path_(base_path), - quota_(quota), - observers_(observers), - sync_type_(syncer::UNSPECIFIED) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); -} - -SettingsBackend::~SettingsBackend() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); -} - -ValueStore* SettingsBackend::GetStorage( - const std::string& extension_id) const { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DictionaryValue empty; - return GetOrCreateStorageWithSyncData(extension_id, empty); -} - -SyncableSettingsStorage* SettingsBackend::GetOrCreateStorageWithSyncData( - const std::string& extension_id, const DictionaryValue& sync_data) const { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - - StorageObjMap::iterator maybe_storage = storage_objs_.find(extension_id); - if (maybe_storage != storage_objs_.end()) { - return maybe_storage->second.get(); - } - - ValueStore* storage = storage_factory_->Create(base_path_, extension_id); - CHECK(storage); - - // It's fine to create the quota enforcer underneath the sync layer, since - // sync will only go ahead if each underlying storage operation succeeds. - storage = new SettingsStorageQuotaEnforcer(quota_, storage); - - linked_ptr<SyncableSettingsStorage> syncable_storage( - new SyncableSettingsStorage( - observers_, - extension_id, - storage)); - storage_objs_[extension_id] = syncable_storage; - - if (sync_processor_.get()) { - syncer::SyncError error = - syncable_storage->StartSyncing( - sync_data, - CreateSettingsSyncProcessor(extension_id).Pass()); - if (error.IsSet()) - syncable_storage.get()->StopSyncing(); - } - - return syncable_storage.get(); -} - -void SettingsBackend::DeleteStorage(const std::string& extension_id) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - - // Clear settings when the extension is uninstalled. Leveldb implementations - // will also delete the database from disk when the object is destroyed as a - // result of being removed from |storage_objs_|. - // - // TODO(kalman): always GetStorage here (rather than only clearing if it - // exists) since the storage area may have been unloaded, but we still want - // to clear the data from disk. - // However, this triggers http://crbug.com/111072. - StorageObjMap::iterator maybe_storage = storage_objs_.find(extension_id); - if (maybe_storage == storage_objs_.end()) - return; - maybe_storage->second->Clear(); - storage_objs_.erase(extension_id); -} - -std::set<std::string> SettingsBackend::GetKnownExtensionIDs() const { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - std::set<std::string> result; - - // Storage areas can be in-memory as well as on disk. |storage_objs_| will - // contain all that are in-memory. - for (StorageObjMap::iterator it = storage_objs_.begin(); - it != storage_objs_.end(); ++it) { - result.insert(it->first); - } - - // Leveldb databases are directories inside base_path_. - file_util::FileEnumerator::FindInfo find_info; - file_util::FileEnumerator extension_dirs( - base_path_, false, file_util::FileEnumerator::DIRECTORIES); - while (!extension_dirs.Next().empty()) { - extension_dirs.GetFindInfo(&find_info); - FilePath extension_dir(file_util::FileEnumerator::GetFilename(find_info)); - DCHECK(!extension_dir.IsAbsolute()); - // Extension IDs are created as std::strings so they *should* be ASCII. - std::string maybe_as_ascii(extension_dir.MaybeAsASCII()); - if (!maybe_as_ascii.empty()) { - result.insert(maybe_as_ascii); - } - } - - return result; -} - -static void AddAllSyncData( - const std::string& extension_id, - const DictionaryValue& src, - syncer::ModelType type, - syncer::SyncDataList* dst) { - for (DictionaryValue::Iterator it(src); it.HasNext(); it.Advance()) { - dst->push_back(settings_sync_util::CreateData( - extension_id, it.key(), it.value(), type)); - } -} - -syncer::SyncDataList SettingsBackend::GetAllSyncData( - syncer::ModelType type) const { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - // Ignore the type, it's just for sanity checking; assume that whatever base - // path we're constructed with is correct for the sync type. - DCHECK(type == syncer::EXTENSION_SETTINGS || - type == syncer::APP_SETTINGS); - - // For all extensions, get all their settings. This has the effect - // of bringing in the entire state of extension settings in memory; sad. - syncer::SyncDataList all_sync_data; - std::set<std::string> known_extension_ids(GetKnownExtensionIDs()); - - for (std::set<std::string>::const_iterator it = known_extension_ids.begin(); - it != known_extension_ids.end(); ++it) { - ValueStore::ReadResult maybe_settings = GetStorage(*it)->Get(); - if (maybe_settings->HasError()) { - LOG(WARNING) << "Failed to get settings for " << *it << ": " << - maybe_settings->error(); - continue; - } - AddAllSyncData(*it, *maybe_settings->settings().get(), - type, &all_sync_data); - } - - return all_sync_data; -} - -syncer::SyncMergeResult SettingsBackend::MergeDataAndStartSyncing( - syncer::ModelType type, - const syncer::SyncDataList& initial_sync_data, - scoped_ptr<syncer::SyncChangeProcessor> sync_processor, - scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(type == syncer::EXTENSION_SETTINGS || - type == syncer::APP_SETTINGS); - DCHECK_EQ(sync_type_, syncer::UNSPECIFIED); - DCHECK(!sync_processor_.get()); - DCHECK(sync_processor.get()); - DCHECK(sync_error_factory.get()); - - sync_type_ = type; - sync_processor_ = sync_processor.Pass(); - sync_error_factory_ = sync_error_factory.Pass(); - - // Group the initial sync data by extension id. - std::map<std::string, linked_ptr<DictionaryValue> > grouped_sync_data; - for (syncer::SyncDataList::const_iterator it = initial_sync_data.begin(); - it != initial_sync_data.end(); ++it) { - SettingSyncData data(*it); - linked_ptr<DictionaryValue> sync_data = - grouped_sync_data[data.extension_id()]; - if (!sync_data.get()) { - sync_data = linked_ptr<DictionaryValue>(new DictionaryValue()); - grouped_sync_data[data.extension_id()] = sync_data; - } - DCHECK(!sync_data->HasKey(data.key())) << - "Duplicate settings for " << data.extension_id() << "/" << data.key(); - sync_data->SetWithoutPathExpansion(data.key(), data.value().DeepCopy()); - } - - // Start syncing all existing storage areas. Any storage areas created in - // the future will start being synced as part of the creation process. - for (StorageObjMap::iterator it = storage_objs_.begin(); - it != storage_objs_.end(); ++it) { - std::map<std::string, linked_ptr<DictionaryValue> >::iterator - maybe_sync_data = grouped_sync_data.find(it->first); - syncer::SyncError error; - if (maybe_sync_data != grouped_sync_data.end()) { - error = it->second->StartSyncing( - *maybe_sync_data->second, - CreateSettingsSyncProcessor(it->first).Pass()); - grouped_sync_data.erase(it->first); - } else { - DictionaryValue empty; - error = it->second->StartSyncing( - empty, - CreateSettingsSyncProcessor(it->first).Pass()); - } - if (error.IsSet()) - it->second->StopSyncing(); - } - - // Eagerly create and init the rest of the storage areas that have sync data. - // Under normal circumstances (i.e. not first-time sync) this will be all of - // them. - for (std::map<std::string, linked_ptr<DictionaryValue> >::iterator it = - grouped_sync_data.begin(); it != grouped_sync_data.end(); ++it) { - GetOrCreateStorageWithSyncData(it->first, *it->second); - } - - return syncer::SyncMergeResult(type); -} - -syncer::SyncError SettingsBackend::ProcessSyncChanges( - const tracked_objects::Location& from_here, - const syncer::SyncChangeList& sync_changes) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(sync_processor_.get()); - - // Group changes by extension, to pass all changes in a single method call. - std::map<std::string, SettingSyncDataList> grouped_sync_data; - for (syncer::SyncChangeList::const_iterator it = sync_changes.begin(); - it != sync_changes.end(); ++it) { - SettingSyncData data(*it); - grouped_sync_data[data.extension_id()].push_back(data); - } - - // Create any storage areas that don't exist yet but have sync data. - DictionaryValue empty; - for (std::map<std::string, SettingSyncDataList>::iterator - it = grouped_sync_data.begin(); it != grouped_sync_data.end(); ++it) { - SyncableSettingsStorage* storage = - GetOrCreateStorageWithSyncData(it->first, empty); - syncer::SyncError error = storage->ProcessSyncChanges(it->second); - if (error.IsSet()) - storage->StopSyncing(); - } - - return syncer::SyncError(); -} - -void SettingsBackend::StopSyncing(syncer::ModelType type) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(type == syncer::EXTENSION_SETTINGS || - type == syncer::APP_SETTINGS); - DCHECK(sync_type_ == type || sync_type_ == syncer::UNSPECIFIED); - - for (StorageObjMap::iterator it = storage_objs_.begin(); - it != storage_objs_.end(); ++it) { - // Some storage areas may have already stopped syncing if they had areas - // and syncing was disabled, but StopSyncing is safe to call multiple times. - it->second->StopSyncing(); - } - - sync_type_ = syncer::UNSPECIFIED; - sync_processor_.reset(); - sync_error_factory_.reset(); -} - -scoped_ptr<SettingsSyncProcessor> SettingsBackend::CreateSettingsSyncProcessor( - const std::string& extension_id) const { - CHECK(sync_processor_.get()); - return scoped_ptr<SettingsSyncProcessor>( - new SettingsSyncProcessor(extension_id, - sync_type_, - sync_processor_.get())); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_backend.h b/chrome/browser/extensions/settings/settings_backend.h deleted file mode 100644 index 9560c82..0000000 --- a/chrome/browser/extensions/settings/settings_backend.h +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_BACKEND_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_BACKEND_H_ - -#include <map> -#include <set> -#include <string> - -#include "base/compiler_specific.h" -#include "base/file_path.h" -#include "base/memory/linked_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/extensions/settings/settings_observer.h" -#include "chrome/browser/extensions/settings/settings_storage_factory.h" -#include "chrome/browser/extensions/settings/settings_storage_quota_enforcer.h" -#include "sync/api/syncable_service.h" - -namespace syncer { -class SyncErrorFactory; -} - -namespace extensions { - -class SettingsSyncProcessor; -class SyncableSettingsStorage; - -// Manages ValueStore objects for extensions, including routing -// changes from sync to them. -// Lives entirely on the FILE thread. -class SettingsBackend : public syncer::SyncableService { - public: - // |storage_factory| is use to create leveldb storage areas. - // |base_path| is the base of the extension settings directory, so the - // databases will be at base_path/extension_id. - // |observers| is the list of observers to settings changes. - SettingsBackend( - const scoped_refptr<SettingsStorageFactory>& storage_factory, - const FilePath& base_path, - const SettingsStorageQuotaEnforcer::Limits& quota, - const scoped_refptr<SettingsObserverList>& observers); - - virtual ~SettingsBackend(); - - // Gets a weak reference to the storage area for |extension_id|. - // Must be run on the FILE thread. - ValueStore* GetStorage(const std::string& extension_id) const; - - // Deletes all setting data for an extension. Call on the FILE thread. - void DeleteStorage(const std::string& extension_id); - - // syncer::SyncableService implementation. - virtual syncer::SyncDataList GetAllSyncData( - syncer::ModelType type) const OVERRIDE; - virtual syncer::SyncMergeResult MergeDataAndStartSyncing( - syncer::ModelType type, - const syncer::SyncDataList& initial_sync_data, - scoped_ptr<syncer::SyncChangeProcessor> sync_processor, - scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) OVERRIDE; - virtual syncer::SyncError ProcessSyncChanges( - const tracked_objects::Location& from_here, - const syncer::SyncChangeList& change_list) OVERRIDE; - virtual void StopSyncing(syncer::ModelType type) OVERRIDE; - - private: - // Gets a weak reference to the storage area for a given extension, - // initializing sync with some initial data if sync enabled. - SyncableSettingsStorage* GetOrCreateStorageWithSyncData( - const std::string& extension_id, - const DictionaryValue& sync_data) const; - - // Gets all extension IDs known to extension settings. This may not be all - // installed extensions. - std::set<std::string> GetKnownExtensionIDs() const; - - // Creates a new SettingsSyncProcessor for an extension. - scoped_ptr<SettingsSyncProcessor> CreateSettingsSyncProcessor( - const std::string& extension_id) const; - - // The Factory to use for creating leveldb storage areas. - const scoped_refptr<SettingsStorageFactory> storage_factory_; - - // The base file path to create any leveldb databases at. - const FilePath base_path_; - - // Quota limits (see SettingsStorageQuotaEnforcer). - const SettingsStorageQuotaEnforcer::Limits quota_; - - // The list of observers to settings changes. - const scoped_refptr<SettingsObserverList> observers_; - - // A cache of ValueStore objects that have already been created. - // Ensure that there is only ever one created per extension. - typedef std::map<std::string, linked_ptr<SyncableSettingsStorage> > - StorageObjMap; - mutable StorageObjMap storage_objs_; - - // Current sync model type. Will be UNSPECIFIED if sync hasn't been enabled - // yet, and either SETTINGS or APP_SETTINGS if it has been. - syncer::ModelType sync_type_; - - // Current sync processor, if any. - scoped_ptr<syncer::SyncChangeProcessor> sync_processor_; - - // Current sync error handler if any. - scoped_ptr<syncer::SyncErrorFactory> sync_error_factory_; - - DISALLOW_COPY_AND_ASSIGN(SettingsBackend); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_BACKEND_H_ diff --git a/chrome/browser/extensions/settings/settings_frontend.cc b/chrome/browser/extensions/settings/settings_frontend.cc deleted file mode 100644 index b616edd0..0000000 --- a/chrome/browser/extensions/settings/settings_frontend.cc +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/settings_frontend.h" - -#include <limits> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/file_path.h" -#include "base/json/json_reader.h" -#include "chrome/browser/extensions/event_names.h" -#include "chrome/browser/extensions/event_router.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/extension_system.h" -#include "chrome/browser/extensions/settings/leveldb_settings_storage_factory.h" -#include "chrome/browser/extensions/settings/settings_backend.h" -#include "chrome/browser/extensions/settings/sync_or_local_value_store_cache.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/extensions/api/storage.h" -#include "content/public/browser/browser_thread.h" - -#if defined(ENABLE_CONFIGURATION_POLICY) -#include "chrome/browser/extensions/settings/managed_value_store_cache.h" -#endif - -using content::BrowserThread; - -namespace extensions { - -namespace { - -// Settings change Observer which forwards changes on to the extension -// processes for |profile| and its incognito partner if it exists. -class DefaultObserver : public SettingsObserver { - public: - explicit DefaultObserver(Profile* profile) : profile_(profile) {} - - // SettingsObserver implementation. - virtual void OnSettingsChanged( - const std::string& extension_id, - settings_namespace::Namespace settings_namespace, - const std::string& change_json) OVERRIDE { - // TODO(gdk): This is a temporary hack while the refactoring for - // string-based event payloads is removed. http://crbug.com/136045 - scoped_ptr<ListValue> args(new ListValue()); - args->Append(base::JSONReader::Read(change_json)); - args->Append(Value::CreateStringValue(settings_namespace::ToString( - settings_namespace))); - scoped_ptr<Event> event(new Event( - event_names::kOnSettingsChanged, args.Pass())); - ExtensionSystem::Get(profile_)->event_router()-> - DispatchEventToExtension(extension_id, event.Pass()); - } - - private: - Profile* const profile_; -}; - -SettingsStorageQuotaEnforcer::Limits GetLocalLimits() { - SettingsStorageQuotaEnforcer::Limits limits = { - static_cast<size_t>(api::storage::local::QUOTA_BYTES), - std::numeric_limits<size_t>::max(), - std::numeric_limits<size_t>::max() - }; - return limits; -} - -SettingsStorageQuotaEnforcer::Limits GetSyncLimits() { - SettingsStorageQuotaEnforcer::Limits limits = { - static_cast<size_t>(api::storage::sync::QUOTA_BYTES), - static_cast<size_t>(api::storage::sync::QUOTA_BYTES_PER_ITEM), - static_cast<size_t>(api::storage::sync::MAX_ITEMS) - }; - return limits; -} - -} // namespace - -// static -SettingsFrontend* SettingsFrontend::Create(Profile* profile) { - return new SettingsFrontend(new LeveldbSettingsStorageFactory(), profile); -} - -// static -SettingsFrontend* SettingsFrontend::Create( - const scoped_refptr<SettingsStorageFactory>& storage_factory, - Profile* profile) { - return new SettingsFrontend(storage_factory, profile); -} - -SettingsFrontend::SettingsFrontend( - const scoped_refptr<SettingsStorageFactory>& factory, Profile* profile) - : local_quota_limit_(GetLocalLimits()), - sync_quota_limit_(GetSyncLimits()), - profile_(profile), - observers_(new SettingsObserverList()), - profile_observer_(new DefaultObserver(profile)) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - DCHECK(!profile->IsOffTheRecord()); - - observers_->AddObserver(profile_observer_.get()); - - const FilePath& profile_path = profile->GetPath(); - caches_[settings_namespace::LOCAL] = - new SyncOrLocalValueStoreCache( - settings_namespace::LOCAL, - factory, - local_quota_limit_, - observers_, - profile_path); - caches_[settings_namespace::SYNC] = - new SyncOrLocalValueStoreCache( - settings_namespace::SYNC, - factory, - sync_quota_limit_, - observers_, - profile_path); - -#if defined(ENABLE_CONFIGURATION_POLICY) - caches_[settings_namespace::MANAGED] = - new ManagedValueStoreCache( - profile->GetPolicyService(), - ExtensionSystem::Get(profile)->event_router(), - factory, - observers_, - profile_path); -#endif -} - -SettingsFrontend::~SettingsFrontend() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - observers_->RemoveObserver(profile_observer_.get()); - for (CacheMap::iterator it = caches_.begin(); it != caches_.end(); ++it) { - ValueStoreCache* cache = it->second; - cache->ShutdownOnUI(); - BrowserThread::DeleteSoon(BrowserThread::FILE, FROM_HERE, cache); - } -} - -syncer::SyncableService* SettingsFrontend::GetBackendForSync( - syncer::ModelType type) const { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - CacheMap::const_iterator it = caches_.find(settings_namespace::SYNC); - DCHECK(it != caches_.end()); - const SyncOrLocalValueStoreCache* sync_cache = - static_cast<const SyncOrLocalValueStoreCache*>(it->second); - switch (type) { - case syncer::APP_SETTINGS: - return sync_cache->GetAppBackend(); - case syncer::EXTENSION_SETTINGS: - return sync_cache->GetExtensionBackend(); - default: - NOTREACHED(); - return NULL; - } -} - -bool SettingsFrontend::IsStorageEnabled( - settings_namespace::Namespace settings_namespace) const { - return caches_.find(settings_namespace) != caches_.end(); -} - -void SettingsFrontend::RunWithStorage( - const std::string& extension_id, - settings_namespace::Namespace settings_namespace, - const ValueStoreCache::StorageCallback& callback) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - - ValueStoreCache* cache = caches_[settings_namespace]; - CHECK(cache); - - // The |extension| has already been referenced earlier in the stack, so it - // can't be gone here. - // TODO(kalman): change RunWithStorage() to take a - // scoped_refptr<const Extension> instead. - scoped_refptr<const Extension> extension = - extensions::ExtensionSystem::Get(profile_)->extension_service()-> - GetExtensionById(extension_id, true); - CHECK(extension); - - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - base::Bind(&ValueStoreCache::RunWithValueStoreForExtension, - base::Unretained(cache), callback, extension)); -} - -void SettingsFrontend::DeleteStorageSoon( - const std::string& extension_id) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - for (CacheMap::iterator it = caches_.begin(); it != caches_.end(); ++it) { - ValueStoreCache* cache = it->second; - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - base::Bind(&ValueStoreCache::DeleteStorageSoon, - base::Unretained(cache), - extension_id)); - } -} - -scoped_refptr<SettingsObserverList> SettingsFrontend::GetObservers() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - return observers_; -} - -void SettingsFrontend::DisableStorageForTesting( - settings_namespace::Namespace settings_namespace) { - CacheMap::iterator it = caches_.find(settings_namespace); - if (it != caches_.end()) { - ValueStoreCache* cache = it->second; - cache->ShutdownOnUI(); - BrowserThread::DeleteSoon(BrowserThread::FILE, FROM_HERE, cache); - caches_.erase(it); - } -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_frontend.h b/chrome/browser/extensions/settings/settings_frontend.h deleted file mode 100644 index 1c53d51..0000000 --- a/chrome/browser/extensions/settings/settings_frontend.h +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_FRONTEND_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_FRONTEND_H_ - -#include <map> -#include <string> - -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/extensions/settings/settings_namespace.h" -#include "chrome/browser/extensions/settings/settings_observer.h" -#include "chrome/browser/extensions/settings/settings_storage_factory.h" -#include "chrome/browser/extensions/settings/settings_storage_quota_enforcer.h" -#include "chrome/browser/extensions/settings/value_store_cache.h" -#include "sync/api/syncable_service.h" - -class Profile; - -namespace extensions { - -// The component of extension settings which runs on the UI thread, as opposed -// to SettingsBackend which lives on the FILE thread. -// All public methods, must be called on the UI thread, with the exception of -// GetBackendForSync(), which must be called on the FILE thread. -class SettingsFrontend { - public: - // Creates with the default factory. - static SettingsFrontend* Create(Profile* profile); - - // Creates with a specific factory |storage_factory| (presumably for tests). - static SettingsFrontend* Create( - const scoped_refptr<SettingsStorageFactory>& storage_factory, - Profile* profile); - - virtual ~SettingsFrontend(); - - // Must only be called from the FILE thread. |type| should be either - // APP_SETTINGS or EXTENSION_SETTINGS. - syncer::SyncableService* GetBackendForSync(syncer::ModelType type) const; - - // Returns true if |settings_namespace| is a valid namespace. - bool IsStorageEnabled(settings_namespace::Namespace settings_namespace) const; - - // Runs |callback| with the storage area of the given |settings_namespace| - // for the |extension_id|. - void RunWithStorage( - const std::string& extension_id, - settings_namespace::Namespace settings_namespace, - const ValueStoreCache::StorageCallback& callback); - - // Deletes the settings for the given |extension_id|. - void DeleteStorageSoon(const std::string& extension_id); - - // Gets the thread-safe observer list. - scoped_refptr<SettingsObserverList> GetObservers(); - - void DisableStorageForTesting( - settings_namespace::Namespace settings_namespace); - - private: - typedef std::map<settings_namespace::Namespace, ValueStoreCache*> CacheMap; - - SettingsFrontend( - const scoped_refptr<SettingsStorageFactory>& storage_factory, - Profile* profile); - - // The quota limit configurations for the local and sync areas, taken out of - // the schema in chrome/common/extensions/api/storage.json. - const SettingsStorageQuotaEnforcer::Limits local_quota_limit_; - const SettingsStorageQuotaEnforcer::Limits sync_quota_limit_; - - // The (non-incognito) Profile this Frontend belongs to. - Profile* const profile_; - - // List of observers to settings changes. - scoped_refptr<SettingsObserverList> observers_; - - // Observer for |profile_|. - scoped_ptr<SettingsObserver> profile_observer_; - - // Maps a known namespace to its corresponding ValueStoreCache. The caches - // are owned by this object. - CacheMap caches_; - - DISALLOW_COPY_AND_ASSIGN(SettingsFrontend); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_FRONTEND_H_ diff --git a/chrome/browser/extensions/settings/settings_frontend_unittest.cc b/chrome/browser/extensions/settings/settings_frontend_unittest.cc deleted file mode 100644 index 34e2318..0000000 --- a/chrome/browser/extensions/settings/settings_frontend_unittest.cc +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright (c) 2012 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 "testing/gtest/include/gtest/gtest.h" - -#include "base/bind.h" -#include "base/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop.h" -#include "base/stringprintf.h" -#include "chrome/browser/extensions/settings/leveldb_settings_storage_factory.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" -#include "chrome/browser/extensions/settings/settings_namespace.h" -#include "chrome/browser/extensions/settings/settings_test_util.h" -#include "chrome/browser/value_store/value_store.h" -#include "chrome/common/chrome_notification_types.h" -#include "content/public/test/test_browser_thread.h" - -using content::BrowserThread; - -namespace extensions { - -namespace settings = settings_namespace; -namespace util = settings_test_util; - -namespace { - -// To save typing ValueStore::DEFAULTS everywhere. -const ValueStore::WriteOptions DEFAULTS = ValueStore::DEFAULTS; - -// Creates a kilobyte of data. -scoped_ptr<Value> CreateKilobyte() { - std::string kilobyte_string; - for (int i = 0; i < 1024; ++i) { - kilobyte_string += "a"; - } - return scoped_ptr<Value>(Value::CreateStringValue(kilobyte_string)); -} - -// Creates a megabyte of data. -scoped_ptr<Value> CreateMegabyte() { - ListValue* megabyte = new ListValue(); - for (int i = 0; i < 1000; ++i) { - megabyte->Append(CreateKilobyte().release()); - } - return scoped_ptr<Value>(megabyte); -} - -} - -class ExtensionSettingsFrontendTest : public testing::Test { - public: - ExtensionSettingsFrontendTest() - : storage_factory_(new util::ScopedSettingsStorageFactory()), - ui_thread_(BrowserThread::UI, MessageLoop::current()), - file_thread_(BrowserThread::FILE, MessageLoop::current()) {} - - virtual void SetUp() OVERRIDE { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - profile_.reset(new util::MockProfile(temp_dir_.path())); - ResetFrontend(); - } - - virtual void TearDown() OVERRIDE { - frontend_.reset(); - profile_.reset(); - // Execute any pending deletion tasks. - message_loop_.RunUntilIdle(); - } - - protected: - void ResetFrontend() { - storage_factory_->Reset(new LeveldbSettingsStorageFactory()); - frontend_.reset( - SettingsFrontend::Create(storage_factory_.get(), profile_.get())); - } - - base::ScopedTempDir temp_dir_; - scoped_ptr<util::MockProfile> profile_; - scoped_ptr<SettingsFrontend> frontend_; - scoped_refptr<util::ScopedSettingsStorageFactory> storage_factory_; - - private: - MessageLoop message_loop_; - content::TestBrowserThread ui_thread_; - content::TestBrowserThread file_thread_; -}; - -// Get a semblance of coverage for both extension and app settings by -// alternating in each test. -// TODO(kalman): explicitly test the two interact correctly. - -TEST_F(ExtensionSettingsFrontendTest, SettingsPreservedAcrossReconstruction) { - const std::string id = "ext"; - ExtensionServiceInterface* esi = - extensions::ExtensionSystem::Get(profile_.get())->extension_service(); - static_cast<extensions::settings_test_util::MockExtensionService*>(esi)-> - AddExtensionWithId(id, Extension::TYPE_EXTENSION); - - ValueStore* storage = util::GetStorage(id, frontend_.get()); - - // The correctness of Get/Set/Remove/Clear is tested elsewhere so no need to - // be too rigorous. - { - StringValue bar("bar"); - ValueStore::WriteResult result = storage->Set(DEFAULTS, "foo", bar); - ASSERT_FALSE(result->HasError()); - } - - { - ValueStore::ReadResult result = storage->Get(); - ASSERT_FALSE(result->HasError()); - EXPECT_FALSE(result->settings()->empty()); - } - - ResetFrontend(); - storage = util::GetStorage(id, frontend_.get()); - - { - ValueStore::ReadResult result = storage->Get(); - ASSERT_FALSE(result->HasError()); - EXPECT_FALSE(result->settings()->empty()); - } -} - -TEST_F(ExtensionSettingsFrontendTest, SettingsClearedOnUninstall) { - const std::string id = "ext"; - ExtensionServiceInterface* esi = - extensions::ExtensionSystem::Get(profile_.get())->extension_service(); - static_cast<extensions::settings_test_util::MockExtensionService*>(esi)-> - AddExtensionWithId(id, Extension::TYPE_LEGACY_PACKAGED_APP); - - ValueStore* storage = util::GetStorage(id, frontend_.get()); - - { - StringValue bar("bar"); - ValueStore::WriteResult result = storage->Set(DEFAULTS, "foo", bar); - ASSERT_FALSE(result->HasError()); - } - - // This would be triggered by extension uninstall via a DataDeleter. - frontend_->DeleteStorageSoon(id); - MessageLoop::current()->RunUntilIdle(); - - // The storage area may no longer be valid post-uninstall, so re-request. - storage = util::GetStorage(id, frontend_.get()); - { - ValueStore::ReadResult result = storage->Get(); - ASSERT_FALSE(result->HasError()); - EXPECT_TRUE(result->settings()->empty()); - } -} - -TEST_F(ExtensionSettingsFrontendTest, LeveldbDatabaseDeletedFromDiskOnClear) { - const std::string id = "ext"; - ExtensionServiceInterface* esi = - extensions::ExtensionSystem::Get(profile_.get())->extension_service(); - static_cast<extensions::settings_test_util::MockExtensionService*>(esi)-> - AddExtensionWithId(id, Extension::TYPE_EXTENSION); - - ValueStore* storage = util::GetStorage(id, frontend_.get()); - - { - StringValue bar("bar"); - ValueStore::WriteResult result = storage->Set(DEFAULTS, "foo", bar); - ASSERT_FALSE(result->HasError()); - EXPECT_TRUE(file_util::PathExists(temp_dir_.path())); - } - - // Should need to both clear the database and delete the frontend for the - // leveldb database to be deleted from disk. - { - ValueStore::WriteResult result = storage->Clear(); - ASSERT_FALSE(result->HasError()); - EXPECT_TRUE(file_util::PathExists(temp_dir_.path())); - } - - frontend_.reset(); - MessageLoop::current()->RunUntilIdle(); - // TODO(kalman): Figure out why this fails, despite appearing to work. - // Leaving this commented out rather than disabling the whole test so that the - // deletion code paths are at least exercised. - //EXPECT_FALSE(file_util::PathExists(temp_dir_.path())); -} - -#if defined(OS_WIN) -// Failing on vista dbg. http://crbug.com/111100, http://crbug.com/108724 -#define QuotaLimitsEnforcedCorrectlyForSyncAndLocal \ - DISABLED_QuotaLimitsEnforcedCorrectlyForSyncAndLocal -#endif -TEST_F(ExtensionSettingsFrontendTest, - QuotaLimitsEnforcedCorrectlyForSyncAndLocal) { - const std::string id = "ext"; - ExtensionServiceInterface* esi = - extensions::ExtensionSystem::Get(profile_.get())->extension_service(); - static_cast<extensions::settings_test_util::MockExtensionService*>(esi)-> - AddExtensionWithId(id, Extension::TYPE_EXTENSION); - - ValueStore* sync_storage = - util::GetStorage(id, settings::SYNC, frontend_.get()); - ValueStore* local_storage = - util::GetStorage(id, settings::LOCAL, frontend_.get()); - - // Sync storage should run out after ~100K. - scoped_ptr<Value> kilobyte = CreateKilobyte(); - for (int i = 0; i < 100; ++i) { - sync_storage->Set( - ValueStore::DEFAULTS, base::StringPrintf("%d", i), *kilobyte); - } - - EXPECT_TRUE(sync_storage->Set( - ValueStore::DEFAULTS, "WillError", *kilobyte)->HasError()); - - // Local storage shouldn't run out after ~100K. - for (int i = 0; i < 100; ++i) { - local_storage->Set( - ValueStore::DEFAULTS, base::StringPrintf("%d", i), *kilobyte); - } - - EXPECT_FALSE(local_storage->Set( - ValueStore::DEFAULTS, "WontError", *kilobyte)->HasError()); - - // Local storage should run out after ~5MB. - scoped_ptr<Value> megabyte = CreateMegabyte(); - for (int i = 0; i < 5; ++i) { - local_storage->Set( - ValueStore::DEFAULTS, base::StringPrintf("%d", i), *megabyte); - } - - EXPECT_TRUE(local_storage->Set( - ValueStore::DEFAULTS, "WillError", *megabyte)->HasError()); -} - -// In other tests, we assume that the result of GetStorage is a pointer to the -// a Storage owned by a Frontend object, but for the unlimitedStorage case, this -// might not be true. So, write the tests in a "callback" style. -// We should really rewrite all tests to be asynchronous in this way. - -static void UnlimitedSyncStorageTestCallback(ValueStore* sync_storage) { - // Sync storage should still run out after ~100K; the unlimitedStorage - // permission can't apply to sync. - scoped_ptr<Value> kilobyte = CreateKilobyte(); - for (int i = 0; i < 100; ++i) { - sync_storage->Set( - ValueStore::DEFAULTS, base::StringPrintf("%d", i), *kilobyte); - } - - EXPECT_TRUE(sync_storage->Set( - ValueStore::DEFAULTS, "WillError", *kilobyte)->HasError()); -} - -static void UnlimitedLocalStorageTestCallback(ValueStore* local_storage) { - // Local storage should never run out. - scoped_ptr<Value> megabyte = CreateMegabyte(); - for (int i = 0; i < 7; ++i) { - local_storage->Set( - ValueStore::DEFAULTS, base::StringPrintf("%d", i), *megabyte); - } - - EXPECT_FALSE(local_storage->Set( - ValueStore::DEFAULTS, "WontError", *megabyte)->HasError()); -} - -#if defined(OS_WIN) -// Failing on vista dbg. http://crbug.com/111100, http://crbug.com/108724 -#define UnlimitedStorageForLocalButNotSync DISABLED_UnlimitedStorageForLocalButNotSync -#endif -TEST_F(ExtensionSettingsFrontendTest, - UnlimitedStorageForLocalButNotSync) { - const std::string id = "ext"; - std::set<std::string> permissions; - permissions.insert("unlimitedStorage"); - ExtensionServiceInterface* esi = - extensions::ExtensionSystem::Get(profile_.get())->extension_service(); - static_cast<extensions::settings_test_util::MockExtensionService*>(esi)-> - AddExtensionWithIdAndPermissions(id, Extension::TYPE_EXTENSION, - permissions); - - frontend_->RunWithStorage( - id, settings::SYNC, base::Bind(&UnlimitedSyncStorageTestCallback)); - frontend_->RunWithStorage( - id, settings::LOCAL, base::Bind(&UnlimitedLocalStorageTestCallback)); - - MessageLoop::current()->RunUntilIdle(); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_namespace.cc b/chrome/browser/extensions/settings/settings_namespace.cc deleted file mode 100644 index 82767ca..0000000 --- a/chrome/browser/extensions/settings/settings_namespace.cc +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/settings_namespace.h" - -#include "base/logging.h" - -namespace extensions { - -namespace settings_namespace { - -namespace { -const char kLocalNamespace[] = "local"; -const char kSyncNamespace[] = "sync"; -const char kManagedNamespace[] = "managed"; -} // namespace - -std::string ToString(Namespace settings_namespace) { - switch (settings_namespace) { - case LOCAL: return kLocalNamespace; - case SYNC: return kSyncNamespace; - case MANAGED: return kManagedNamespace; - case INVALID: break; - } - NOTREACHED(); - return std::string(); -} - -Namespace FromString(const std::string& namespace_string) { - if (namespace_string == kLocalNamespace) - return LOCAL; - if (namespace_string == kSyncNamespace) - return SYNC; - if (namespace_string == kManagedNamespace) - return MANAGED; - return INVALID; -} - -} // namespace settings_namespace - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_namespace.h b/chrome/browser/extensions/settings/settings_namespace.h deleted file mode 100644 index c89658b..0000000 --- a/chrome/browser/extensions/settings/settings_namespace.h +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_NAMESPACE_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_NAMESPACE_H_ - -#include <string> - -namespace extensions { - -namespace settings_namespace { - -// The namespaces of the storage areas. -enum Namespace { - LOCAL, // "local" i.e. chrome.storage.local - SYNC, // "sync" i.e. chrome.storage.sync - MANAGED, // "managed" i.e. chrome.storage.managed - INVALID -}; - -// Converts a namespace to its string representation. -// Namespace must not be INVALID. -std::string ToString(Namespace settings_namespace); - -// Converts a string representation of a namespace to its namespace, or INVALID -// if the string doesn't map to one. -Namespace FromString(const std::string& ns_string); - -} // namespace settings_namespace - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_NAMESPACE_H_ diff --git a/chrome/browser/extensions/settings/settings_observer.h b/chrome/browser/extensions/settings/settings_observer.h deleted file mode 100644 index f789b95..0000000 --- a/chrome/browser/extensions/settings/settings_observer.h +++ /dev/null @@ -1,30 +0,0 @@ -// 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_OBSERVER_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_OBSERVER_H_ - -#include "base/observer_list_threadsafe.h" -#include "chrome/browser/extensions/settings/settings_namespace.h" - -namespace extensions { - -// Interface for classes that listen to changes to extension settings. -class SettingsObserver { - public: - // Called when a list of settings have changed for an extension. - virtual void OnSettingsChanged( - const std::string& extension_id, - settings_namespace::Namespace settings_namespace, - const std::string& changes_json) = 0; - - virtual ~SettingsObserver() {} -}; - -typedef ObserverListThreadSafe<SettingsObserver> - SettingsObserverList; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_OBSERVER_H_ diff --git a/chrome/browser/extensions/settings/settings_quota_unittest.cc b/chrome/browser/extensions/settings/settings_quota_unittest.cc deleted file mode 100644 index c8b66c6..0000000 --- a/chrome/browser/extensions/settings/settings_quota_unittest.cc +++ /dev/null @@ -1,595 +0,0 @@ -// Copyright (c) 2012 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 "testing/gtest/include/gtest/gtest.h" - -#include "base/json/json_writer.h" -#include "base/values.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/extensions/settings/settings_backend.h" -#include "chrome/browser/extensions/settings/settings_storage_quota_enforcer.h" -#include "chrome/browser/value_store/testing_value_store.h" - -namespace extensions { - -// To save typing ValueStore::DEFAULTS/IGNORE_QUOTA everywhere. -const ValueStore::WriteOptions DEFAULTS = ValueStore::DEFAULTS; -const ValueStore::WriteOptions IGNORE_QUOTA = - ValueStore::IGNORE_QUOTA; - -class ExtensionSettingsQuotaTest : public testing::Test { - public: - ExtensionSettingsQuotaTest() - : byte_value_1_(Value::CreateIntegerValue(1)), - byte_value_16_(Value::CreateStringValue("sixteen bytes.")), - byte_value_256_(new ListValue()), - delegate_(new TestingValueStore()) { - for (int i = 1; i < 89; ++i) { - byte_value_256_->Append(Value::CreateIntegerValue(i)); - } - ValidateByteValues(); - } - - void ValidateByteValues() { - std::string validate_sizes; - base::JSONWriter::Write(byte_value_1_.get(), &validate_sizes); - ASSERT_EQ(1u, validate_sizes.size()); - base::JSONWriter::Write(byte_value_16_.get(), &validate_sizes); - ASSERT_EQ(16u, validate_sizes.size()); - base::JSONWriter::Write(byte_value_256_.get(), &validate_sizes); - ASSERT_EQ(256u, validate_sizes.size()); - } - - virtual void TearDown() OVERRIDE { - ASSERT_TRUE(storage_.get() != NULL); - } - - protected: - // Creates |storage_|. Must only be called once. - void CreateStorage( - size_t quota_bytes, size_t quota_bytes_per_item, size_t max_items) { - ASSERT_TRUE(storage_.get() == NULL); - SettingsStorageQuotaEnforcer::Limits limits = - { quota_bytes, quota_bytes_per_item, max_items }; - storage_.reset(new SettingsStorageQuotaEnforcer(limits, delegate_)); - } - - // Returns whether the settings in |storage_| and |delegate_| are the same as - // |settings|. - bool SettingsEqual(const DictionaryValue& settings) { - return settings.Equals(storage_->Get()->settings().get()) && - settings.Equals(delegate_->Get()->settings().get()); - } - - // Values with different serialized sizes. - scoped_ptr<Value> byte_value_1_; - scoped_ptr<Value> byte_value_16_; - scoped_ptr<ListValue> byte_value_256_; - - // Quota enforcing storage area being tested. - scoped_ptr<SettingsStorageQuotaEnforcer> storage_; - - // In-memory storage area being delegated to. Always owned by |storage_|. - TestingValueStore* delegate_; -}; - -TEST_F(ExtensionSettingsQuotaTest, ZeroQuotaBytes) { - DictionaryValue empty; - CreateStorage(0, UINT_MAX, UINT_MAX); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Remove("a")->HasError()); - EXPECT_FALSE(storage_->Remove("b")->HasError()); - EXPECT_TRUE(SettingsEqual(empty)); -} - -TEST_F(ExtensionSettingsQuotaTest, KeySizeTakenIntoAccount) { - DictionaryValue empty; - CreateStorage(8u, UINT_MAX, UINT_MAX); - EXPECT_TRUE( - storage_->Set(DEFAULTS, "Really long key", *byte_value_1_)->HasError()); - EXPECT_TRUE(SettingsEqual(empty)); -} - -TEST_F(ExtensionSettingsQuotaTest, SmallByteQuota) { - DictionaryValue settings; - CreateStorage(8u, UINT_MAX, UINT_MAX); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - settings.Set("a", byte_value_1_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "b", *byte_value_16_)->HasError()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_256_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, MediumByteQuota) { - DictionaryValue settings; - CreateStorage(40, UINT_MAX, UINT_MAX); - - DictionaryValue to_set; - to_set.Set("a", byte_value_1_->DeepCopy()); - to_set.Set("b", byte_value_16_->DeepCopy()); - EXPECT_FALSE(storage_->Set(DEFAULTS, to_set)->HasError()); - settings.Set("a", byte_value_1_->DeepCopy()); - settings.Set("b", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Should be able to set value to other under-quota value. - to_set.Set("a", byte_value_16_->DeepCopy()); - EXPECT_FALSE(storage_->Set(DEFAULTS, to_set)->HasError()); - settings.Set("a", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_256_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, ZeroMaxKeys) { - DictionaryValue empty; - CreateStorage(UINT_MAX, UINT_MAX, 0); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Remove("a")->HasError()); - EXPECT_FALSE(storage_->Remove("b")->HasError()); - EXPECT_TRUE(SettingsEqual(empty)); -} - -TEST_F(ExtensionSettingsQuotaTest, SmallMaxKeys) { - DictionaryValue settings; - CreateStorage(UINT_MAX, UINT_MAX, 1); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - settings.Set("a", byte_value_1_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Should be able to set existing key to other value without going over quota. - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_16_)->HasError()); - settings.Set("a", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "b", *byte_value_16_)->HasError()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_256_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, MediumMaxKeys) { - DictionaryValue settings; - CreateStorage(UINT_MAX, UINT_MAX, 2); - - DictionaryValue to_set; - to_set.Set("a", byte_value_1_->DeepCopy()); - to_set.Set("b", byte_value_16_->DeepCopy()); - EXPECT_FALSE(storage_->Set(DEFAULTS, to_set)->HasError()); - settings.Set("a", byte_value_1_->DeepCopy()); - settings.Set("b", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Should be able to set existing keys to other values without going over - // quota. - to_set.Set("a", byte_value_16_->DeepCopy()); - EXPECT_FALSE(storage_->Set(DEFAULTS, to_set)->HasError()); - settings.Set("a", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_256_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, RemovingExistingSettings) { - DictionaryValue settings; - CreateStorage(266, UINT_MAX, 2); - - storage_->Set(DEFAULTS, "b", *byte_value_16_); - settings.Set("b", byte_value_16_->DeepCopy()); - // Not enough quota. - storage_->Set(DEFAULTS, "c", *byte_value_256_); - EXPECT_TRUE(SettingsEqual(settings)); - - // Try again with "b" removed, enough quota. - EXPECT_FALSE(storage_->Remove("b")->HasError()); - settings.Remove("b", NULL); - EXPECT_FALSE(storage_->Set(DEFAULTS, "c", *byte_value_256_)->HasError()); - settings.Set("c", byte_value_256_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Enough byte quota but max keys not high enough. - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - settings.Set("a", byte_value_1_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "b", *byte_value_1_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Back under max keys. - EXPECT_FALSE(storage_->Remove("a")->HasError()); - settings.Remove("a", NULL); - EXPECT_FALSE(storage_->Set(DEFAULTS, "b", *byte_value_1_)->HasError()); - settings.Set("b", byte_value_1_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, RemovingNonexistentSettings) { - DictionaryValue settings; - CreateStorage(36, UINT_MAX, 3); - - // Max out bytes. - DictionaryValue to_set; - to_set.Set("b1", byte_value_16_->DeepCopy()); - to_set.Set("b2", byte_value_16_->DeepCopy()); - storage_->Set(DEFAULTS, to_set); - settings.Set("b1", byte_value_16_->DeepCopy()); - settings.Set("b2", byte_value_16_->DeepCopy()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Remove some settings that don't exist. - std::vector<std::string> to_remove; - to_remove.push_back("a1"); - to_remove.push_back("a2"); - EXPECT_FALSE(storage_->Remove(to_remove)->HasError()); - EXPECT_FALSE(storage_->Remove("b")->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Still no quota. - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Max out key count. - to_set.Clear(); - to_set.Set("b1", byte_value_1_->DeepCopy()); - to_set.Set("b2", byte_value_1_->DeepCopy()); - storage_->Set(DEFAULTS, to_set); - settings.Set("b1", byte_value_1_->DeepCopy()); - settings.Set("b2", byte_value_1_->DeepCopy()); - storage_->Set(DEFAULTS, "b3", *byte_value_1_); - settings.Set("b3", byte_value_1_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Remove some settings that don't exist. - to_remove.clear(); - to_remove.push_back("a1"); - to_remove.push_back("a2"); - EXPECT_FALSE(storage_->Remove(to_remove)->HasError()); - EXPECT_FALSE(storage_->Remove("b")->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Still no quota. - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, Clear) { - DictionaryValue settings; - CreateStorage(40, UINT_MAX, 5); - - // Test running out of byte quota. - { - DictionaryValue to_set; - to_set.Set("a", byte_value_16_->DeepCopy()); - to_set.Set("b", byte_value_16_->DeepCopy()); - EXPECT_FALSE(storage_->Set(DEFAULTS, to_set)->HasError()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_16_)->HasError()); - - EXPECT_FALSE(storage_->Clear()->HasError()); - - // (repeat) - EXPECT_FALSE(storage_->Set(DEFAULTS, to_set)->HasError()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_16_)->HasError()); - } - - // Test reaching max keys. - storage_->Clear(); - { - DictionaryValue to_set; - to_set.Set("a", byte_value_1_->DeepCopy()); - to_set.Set("b", byte_value_1_->DeepCopy()); - to_set.Set("c", byte_value_1_->DeepCopy()); - to_set.Set("d", byte_value_1_->DeepCopy()); - to_set.Set("e", byte_value_1_->DeepCopy()); - EXPECT_FALSE(storage_->Set(DEFAULTS, to_set)->HasError()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "f", *byte_value_1_)->HasError()); - - storage_->Clear(); - - // (repeat) - EXPECT_FALSE(storage_->Set(DEFAULTS, to_set)->HasError()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "f", *byte_value_1_)->HasError()); - } -} - -TEST_F(ExtensionSettingsQuotaTest, ChangingUsedBytesWithSet) { - DictionaryValue settings; - CreateStorage(20, UINT_MAX, UINT_MAX); - - // Change a setting to make it go over quota. - storage_->Set(DEFAULTS, "a", *byte_value_16_); - settings.Set("a", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_256_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Change a setting to reduce usage and room for another setting. - EXPECT_TRUE(storage_->Set(DEFAULTS, "foobar", *byte_value_1_)->HasError()); - storage_->Set(DEFAULTS, "a", *byte_value_1_); - settings.Set("a", byte_value_1_->DeepCopy()); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "foobar", *byte_value_1_)->HasError()); - settings.Set("foobar", byte_value_1_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, SetsOnlyEntirelyCompletedWithByteQuota) { - DictionaryValue settings; - CreateStorage(40, UINT_MAX, UINT_MAX); - - storage_->Set(DEFAULTS, "a", *byte_value_16_); - settings.Set("a", byte_value_16_->DeepCopy()); - - // The entire change is over quota. - DictionaryValue to_set; - to_set.Set("b", byte_value_16_->DeepCopy()); - to_set.Set("c", byte_value_16_->DeepCopy()); - EXPECT_TRUE(storage_->Set(DEFAULTS, to_set)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); - - // The entire change is over quota, but quota reduced in existing key. - to_set.Set("a", byte_value_1_->DeepCopy()); - EXPECT_FALSE(storage_->Set(DEFAULTS, to_set)->HasError()); - settings.Set("a", byte_value_1_->DeepCopy()); - settings.Set("b", byte_value_16_->DeepCopy()); - settings.Set("c", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, SetsOnlyEntireCompletedWithMaxKeys) { - DictionaryValue settings; - CreateStorage(UINT_MAX, UINT_MAX, 2); - - storage_->Set(DEFAULTS, "a", *byte_value_1_); - settings.Set("a", byte_value_1_->DeepCopy()); - - DictionaryValue to_set; - to_set.Set("b", byte_value_16_->DeepCopy()); - to_set.Set("c", byte_value_16_->DeepCopy()); - EXPECT_TRUE(storage_->Set(DEFAULTS, to_set)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, WithInitialDataAndByteQuota) { - DictionaryValue settings; - delegate_->Set(DEFAULTS, "a", *byte_value_256_); - settings.Set("a", byte_value_256_->DeepCopy()); - - CreateStorage(280, UINT_MAX, UINT_MAX); - EXPECT_TRUE(SettingsEqual(settings)); - - // Add some data. - EXPECT_FALSE(storage_->Set(DEFAULTS, "b", *byte_value_16_)->HasError()); - settings.Set("b", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Not enough quota. - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_16_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Reduce usage of original setting so that "c" can fit. - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_16_)->HasError()); - settings.Set("a", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "c", *byte_value_16_)->HasError()); - settings.Set("c", byte_value_16_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Remove to free up some more data. - EXPECT_TRUE(storage_->Set(DEFAULTS, "d", *byte_value_256_)->HasError()); - - std::vector<std::string> to_remove; - to_remove.push_back("a"); - to_remove.push_back("b"); - storage_->Remove(to_remove); - settings.Remove("a", NULL); - settings.Remove("b", NULL); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "d", *byte_value_256_)->HasError()); - settings.Set("d", byte_value_256_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, WithInitialDataAndMaxKeys) { - DictionaryValue settings; - delegate_->Set(DEFAULTS, "a", *byte_value_1_); - settings.Set("a", byte_value_1_->DeepCopy()); - CreateStorage(UINT_MAX, UINT_MAX, 2); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "b", *byte_value_1_)->HasError()); - settings.Set("b", byte_value_1_->DeepCopy()); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_1_)->HasError()); - - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, InitiallyOverByteQuota) { - DictionaryValue settings; - settings.Set("a", byte_value_16_->DeepCopy()); - settings.Set("b", byte_value_16_->DeepCopy()); - settings.Set("c", byte_value_16_->DeepCopy()); - delegate_->Set(DEFAULTS, settings); - - CreateStorage(40, UINT_MAX, UINT_MAX); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "d", *byte_value_16_)->HasError()); - - // Take under quota by reducing size of an existing setting - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - settings.Set("a", byte_value_1_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Should be able set another small setting. - EXPECT_FALSE(storage_->Set(DEFAULTS, "d", *byte_value_1_)->HasError()); - settings.Set("d", byte_value_1_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, InitiallyOverMaxKeys) { - DictionaryValue settings; - settings.Set("a", byte_value_16_->DeepCopy()); - settings.Set("b", byte_value_16_->DeepCopy()); - settings.Set("c", byte_value_16_->DeepCopy()); - delegate_->Set(DEFAULTS, settings); - - CreateStorage(UINT_MAX, UINT_MAX, 2); - EXPECT_TRUE(SettingsEqual(settings)); - - // Can't set either an existing or new setting. - EXPECT_TRUE(storage_->Set(DEFAULTS, "d", *byte_value_16_)->HasError()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Should be able after removing 2. - storage_->Remove("a"); - settings.Remove("a", NULL); - storage_->Remove("b"); - settings.Remove("b", NULL); - EXPECT_TRUE(SettingsEqual(settings)); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "e", *byte_value_1_)->HasError()); - settings.Set("e", byte_value_1_->DeepCopy()); - EXPECT_TRUE(SettingsEqual(settings)); - - // Still can't set any. - EXPECT_TRUE(storage_->Set(DEFAULTS, "d", *byte_value_16_)->HasError()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, ZeroQuotaBytesPerSetting) { - DictionaryValue empty; - CreateStorage(UINT_MAX, 0, UINT_MAX); - - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Remove("a")->HasError()); - EXPECT_FALSE(storage_->Remove("b")->HasError()); - EXPECT_TRUE(SettingsEqual(empty)); -} - -TEST_F(ExtensionSettingsQuotaTest, QuotaBytesPerSetting) { - DictionaryValue settings; - - CreateStorage(UINT_MAX, 20, UINT_MAX); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_16_)->HasError()); - settings.Set("a", byte_value_16_->DeepCopy()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_256_)->HasError()); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "b", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Set(DEFAULTS, "b", *byte_value_16_)->HasError()); - settings.Set("b", byte_value_16_->DeepCopy()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "b", *byte_value_256_)->HasError()); - - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, QuotaBytesPerSettingWithInitialSettings) { - DictionaryValue settings; - - delegate_->Set(DEFAULTS, "a", *byte_value_1_); - delegate_->Set(DEFAULTS, "b", *byte_value_16_); - delegate_->Set(DEFAULTS, "c", *byte_value_256_); - CreateStorage(UINT_MAX, 20, UINT_MAX); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Set(DEFAULTS, "a", *byte_value_16_)->HasError()); - settings.Set("a", byte_value_16_->DeepCopy()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "a", *byte_value_256_)->HasError()); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "b", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Set(DEFAULTS, "b", *byte_value_16_)->HasError()); - settings.Set("b", byte_value_16_->DeepCopy()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "b", *byte_value_256_)->HasError()); - - EXPECT_FALSE(storage_->Set(DEFAULTS, "c", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Set(DEFAULTS, "c", *byte_value_16_)->HasError()); - settings.Set("c", byte_value_16_->DeepCopy()); - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_256_)->HasError()); - - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, - QuotaBytesPerSettingWithInitialSettingsForced) { - // This is a lazy test to make sure IGNORE_QUOTA lets through changes: the - // test above copied, but using IGNORE_QUOTA and asserting nothing is ever - // rejected... - DictionaryValue settings; - - delegate_->Set(DEFAULTS, "a", *byte_value_1_); - delegate_->Set(DEFAULTS, "b", *byte_value_16_); - delegate_->Set(DEFAULTS, "c", *byte_value_256_); - CreateStorage(UINT_MAX, 20, UINT_MAX); - - EXPECT_FALSE(storage_->Set(IGNORE_QUOTA, "a", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Set(IGNORE_QUOTA, "a", *byte_value_16_)->HasError()); - EXPECT_FALSE(storage_->Set(IGNORE_QUOTA, "a", *byte_value_256_)->HasError()); - settings.Set("a", byte_value_256_->DeepCopy()); - - EXPECT_FALSE(storage_->Set(IGNORE_QUOTA, "b", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Set(IGNORE_QUOTA, "b", *byte_value_16_)->HasError()); - EXPECT_FALSE(storage_->Set(IGNORE_QUOTA, "b", *byte_value_256_)->HasError()); - settings.Set("b", byte_value_256_->DeepCopy()); - - EXPECT_FALSE(storage_->Set(IGNORE_QUOTA, "c", *byte_value_1_)->HasError()); - EXPECT_FALSE(storage_->Set(IGNORE_QUOTA, "c", *byte_value_16_)->HasError()); - settings.Set("c", byte_value_16_->DeepCopy()); - - // ... except the last. Make sure it can still fail. - EXPECT_TRUE(storage_->Set(DEFAULTS, "c", *byte_value_256_)->HasError()); - - EXPECT_TRUE(SettingsEqual(settings)); -} - -TEST_F(ExtensionSettingsQuotaTest, GetBytesInUse) { - // Just testing GetBytesInUse, no need for a quota. - CreateStorage(UINT_MAX, UINT_MAX, UINT_MAX); - - std::vector<std::string> ab; - ab.push_back("a"); - ab.push_back("b"); - - EXPECT_EQ(0u, storage_->GetBytesInUse()); - EXPECT_EQ(0u, storage_->GetBytesInUse("a")); - EXPECT_EQ(0u, storage_->GetBytesInUse("b")); - EXPECT_EQ(0u, storage_->GetBytesInUse(ab)); - - storage_->Set(DEFAULTS, "a", *byte_value_1_); - - EXPECT_EQ(2u, storage_->GetBytesInUse()); - EXPECT_EQ(2u, storage_->GetBytesInUse("a")); - EXPECT_EQ(0u, storage_->GetBytesInUse("b")); - EXPECT_EQ(2u, storage_->GetBytesInUse(ab)); - - storage_->Set(DEFAULTS, "b", *byte_value_1_); - - EXPECT_EQ(4u, storage_->GetBytesInUse()); - EXPECT_EQ(2u, storage_->GetBytesInUse("a")); - EXPECT_EQ(2u, storage_->GetBytesInUse("b")); - EXPECT_EQ(4u, storage_->GetBytesInUse(ab)); - - storage_->Set(DEFAULTS, "c", *byte_value_1_); - - EXPECT_EQ(6u, storage_->GetBytesInUse()); - EXPECT_EQ(2u, storage_->GetBytesInUse("a")); - EXPECT_EQ(2u, storage_->GetBytesInUse("b")); - EXPECT_EQ(4u, storage_->GetBytesInUse(ab)); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_storage_factory.h b/chrome/browser/extensions/settings/settings_storage_factory.h deleted file mode 100644 index 844e80d..0000000 --- a/chrome/browser/extensions/settings/settings_storage_factory.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_STORAGE_FACTORY_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_STORAGE_FACTORY_H_ - -#include <string> - -#include "base/file_path.h" -#include "base/memory/ref_counted.h" - -class ValueStore; - -namespace extensions { - -// Factory for creating SettingStorage instances. -// -// Refcouted because it's just too messy to distribute these objects between -// SettingsBackend instances any other way. -class SettingsStorageFactory - : public base::RefCountedThreadSafe<SettingsStorageFactory> { - public: - // Creates a new ValueStore area for an extension under |base_path|. - // Return NULL to indicate failure. Must be called on the FILE thread. - virtual ValueStore* Create(const FilePath& base_path, - const std::string& extension_id) = 0; - - protected: - friend class base::RefCountedThreadSafe<SettingsStorageFactory>; - virtual ~SettingsStorageFactory() {} -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_STORAGE_FACTORY_H_ diff --git a/chrome/browser/extensions/settings/settings_storage_quota_enforcer.cc b/chrome/browser/extensions/settings/settings_storage_quota_enforcer.cc deleted file mode 100644 index a4c81ef..0000000 --- a/chrome/browser/extensions/settings/settings_storage_quota_enforcer.cc +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/settings_storage_quota_enforcer.h" - -#include "base/bind.h" -#include "base/json/json_writer.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop.h" -#include "base/metrics/histogram.h" -#include "chrome/common/extensions/api/extension_api.h" -#include "extensions/common/error_utils.h" - -namespace extensions { - -namespace { - -const char* kQuotaExceededError = "* quota exceeded."; - -// Resources there are a quota for. -enum Resource { - QUOTA_BYTES, - QUOTA_BYTES_PER_ITEM, - MAX_ITEMS -}; - -// Allocates a setting in a record of total and per-setting usage. -void Allocate( - const std::string& key, - const Value& value, - size_t* used_total, - std::map<std::string, size_t>* used_per_setting) { - // Calculate the setting size based on its JSON serialization size. - // TODO(kalman): Does this work with different encodings? - // TODO(kalman): This is duplicating work that the leveldb delegate - // implementation is about to do, and it would be nice to avoid this. - std::string value_as_json; - base::JSONWriter::Write(&value, &value_as_json); - size_t new_size = key.size() + value_as_json.size(); - size_t existing_size = (*used_per_setting)[key]; - - *used_total += (new_size - existing_size); - (*used_per_setting)[key] = new_size; -} - -// Frees the allocation of a setting in a record of total and per-setting usage. -void Free( - size_t* used_total, - std::map<std::string, size_t>* used_per_setting, - const std::string& key) { - *used_total -= (*used_per_setting)[key]; - used_per_setting->erase(key); -} - -// Returns an error result and logs the quota exceeded to UMA. -ValueStore::WriteResult QuotaExceededFor(Resource resource) { - std::string name; - switch (resource) { - case QUOTA_BYTES: - name = "QUOTA_BYTES"; - UMA_HISTOGRAM_COUNTS_100( - "Extensions.SettingsQuotaExceeded.TotalBytes", 1); - break; - case QUOTA_BYTES_PER_ITEM: - name = "QUOTA_BYTES_PER_ITEM"; - UMA_HISTOGRAM_COUNTS_100( - "Extensions.SettingsQuotaExceeded.BytesPerSetting", 1); - break; - case MAX_ITEMS: - name = "MAX_ITEMS"; - UMA_HISTOGRAM_COUNTS_100( - "Extensions.SettingsQuotaExceeded.KeyCount", 1); - break; - default: - NOTREACHED(); - } - return ValueStore::MakeWriteResult( - ErrorUtils::FormatErrorMessage(kQuotaExceededError, name)); -} - -} // namespace - -SettingsStorageQuotaEnforcer::SettingsStorageQuotaEnforcer( - const Limits& limits, ValueStore* delegate) - : limits_(limits), delegate_(delegate), used_total_(0) { - ReadResult maybe_settings = delegate_->Get(); - if (maybe_settings->HasError()) { - LOG(WARNING) << "Failed to get initial settings for quota: " << - maybe_settings->error(); - return; - } - - for (DictionaryValue::Iterator it(*maybe_settings->settings().get()); - it.HasNext(); it.Advance()) { - Allocate( - it.key(), it.value(), &used_total_, &used_per_setting_); - } -} - -SettingsStorageQuotaEnforcer::~SettingsStorageQuotaEnforcer() {} - -size_t SettingsStorageQuotaEnforcer::GetBytesInUse(const std::string& key) { - std::map<std::string, size_t>::iterator maybe_used = - used_per_setting_.find(key); - return maybe_used == used_per_setting_.end() ? 0u : maybe_used->second; -} - -size_t SettingsStorageQuotaEnforcer::GetBytesInUse( - const std::vector<std::string>& keys) { - size_t used = 0; - for (std::vector<std::string>::const_iterator it = keys.begin(); - it != keys.end(); ++it) { - used += GetBytesInUse(*it); - } - return used; -} - -size_t SettingsStorageQuotaEnforcer::GetBytesInUse() { - // All ValueStore implementations rely on GetBytesInUse being - // implemented here. - return used_total_; -} - -ValueStore::ReadResult SettingsStorageQuotaEnforcer::Get( - const std::string& key) { - return delegate_->Get(key); -} - -ValueStore::ReadResult SettingsStorageQuotaEnforcer::Get( - const std::vector<std::string>& keys) { - return delegate_->Get(keys); -} - -ValueStore::ReadResult SettingsStorageQuotaEnforcer::Get() { - return delegate_->Get(); -} - -ValueStore::WriteResult SettingsStorageQuotaEnforcer::Set( - WriteOptions options, const std::string& key, const Value& value) { - size_t new_used_total = used_total_; - std::map<std::string, size_t> new_used_per_setting = used_per_setting_; - Allocate(key, value, &new_used_total, &new_used_per_setting); - - if (!(options & IGNORE_QUOTA)) { - if (new_used_total > limits_.quota_bytes) { - return QuotaExceededFor(QUOTA_BYTES); - } - if (new_used_per_setting[key] > limits_.quota_bytes_per_item) { - return QuotaExceededFor(QUOTA_BYTES_PER_ITEM); - } - if (new_used_per_setting.size() > limits_.max_items) { - return QuotaExceededFor(MAX_ITEMS); - } - } - - WriteResult result = delegate_->Set(options, key, value); - if (result->HasError()) { - return result.Pass(); - } - - used_total_ = new_used_total; - used_per_setting_.swap(new_used_per_setting); - return result.Pass(); -} - -ValueStore::WriteResult SettingsStorageQuotaEnforcer::Set( - WriteOptions options, const DictionaryValue& values) { - size_t new_used_total = used_total_; - std::map<std::string, size_t> new_used_per_setting = used_per_setting_; - for (DictionaryValue::Iterator it(values); it.HasNext(); it.Advance()) { - Allocate(it.key(), it.value(), &new_used_total, &new_used_per_setting); - - if (!(options & IGNORE_QUOTA) && - new_used_per_setting[it.key()] > limits_.quota_bytes_per_item) { - return QuotaExceededFor(QUOTA_BYTES_PER_ITEM); - } - } - - if (!(options & IGNORE_QUOTA)) { - if (new_used_total > limits_.quota_bytes) { - return QuotaExceededFor(QUOTA_BYTES); - } - if (new_used_per_setting.size() > limits_.max_items) { - return QuotaExceededFor(MAX_ITEMS); - } - } - - WriteResult result = delegate_->Set(options, values); - if (result->HasError()) { - return result.Pass(); - } - - used_total_ = new_used_total; - used_per_setting_ = new_used_per_setting; - return result.Pass(); -} - -ValueStore::WriteResult SettingsStorageQuotaEnforcer::Remove( - const std::string& key) { - WriteResult result = delegate_->Remove(key); - if (result->HasError()) { - return result.Pass(); - } - Free(&used_total_, &used_per_setting_, key); - return result.Pass(); -} - -ValueStore::WriteResult SettingsStorageQuotaEnforcer::Remove( - const std::vector<std::string>& keys) { - WriteResult result = delegate_->Remove(keys); - if (result->HasError()) { - return result.Pass(); - } - - for (std::vector<std::string>::const_iterator it = keys.begin(); - it != keys.end(); ++it) { - Free(&used_total_, &used_per_setting_, *it); - } - return result.Pass(); -} - -ValueStore::WriteResult SettingsStorageQuotaEnforcer::Clear() { - WriteResult result = delegate_->Clear(); - if (result->HasError()) { - return result.Pass(); - } - - while (!used_per_setting_.empty()) { - Free(&used_total_, &used_per_setting_, used_per_setting_.begin()->first); - } - return result.Pass(); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_storage_quota_enforcer.h b/chrome/browser/extensions/settings/settings_storage_quota_enforcer.h deleted file mode 100644 index 2b71ff9..0000000 --- a/chrome/browser/extensions/settings/settings_storage_quota_enforcer.h +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_STORAGE_QUOTA_ENFORCER_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_STORAGE_QUOTA_ENFORCER_H_ - -#include "base/compiler_specific.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/value_store/value_store.h" - -namespace extensions { - -// Enforces total quota and a per-setting quota in bytes, and a maximum number -// of setting keys, for a delegate storage area. -class SettingsStorageQuotaEnforcer : public ValueStore { - public: - struct Limits { - // The total quota in bytes. - size_t quota_bytes; - - // The quota for each individual item in bytes. - size_t quota_bytes_per_item; - - // The maximum number of items allowed. - size_t max_items; - }; - - SettingsStorageQuotaEnforcer(const Limits& limits, ValueStore* delegate); - - virtual ~SettingsStorageQuotaEnforcer(); - - // ValueStore implementation. - virtual size_t GetBytesInUse(const std::string& key) OVERRIDE; - virtual size_t GetBytesInUse(const std::vector<std::string>& keys) OVERRIDE; - virtual size_t GetBytesInUse() OVERRIDE; - virtual ReadResult Get(const std::string& key) OVERRIDE; - virtual ReadResult Get(const std::vector<std::string>& keys) OVERRIDE; - virtual ReadResult Get() OVERRIDE; - virtual WriteResult Set( - WriteOptions options, - const std::string& key, - const Value& value) OVERRIDE; - virtual WriteResult Set( - WriteOptions options, const DictionaryValue& values) OVERRIDE; - virtual WriteResult Remove(const std::string& key) OVERRIDE; - virtual WriteResult Remove(const std::vector<std::string>& keys) OVERRIDE; - virtual WriteResult Clear() OVERRIDE; - - private: - // Limits configuration. - const Limits limits_; - - // The delegate storage area. - scoped_ptr<ValueStore> const delegate_; - - // Total bytes in used by |delegate_|. Includes both key lengths and - // JSON-encoded values. - size_t used_total_; - - // Map of item key to its size, including the key itself. - std::map<std::string, size_t> used_per_setting_; - - DISALLOW_COPY_AND_ASSIGN(SettingsStorageQuotaEnforcer); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_STORAGE_QUOTA_ENFORCER_H_ diff --git a/chrome/browser/extensions/settings/settings_sync_processor.cc b/chrome/browser/extensions/settings/settings_sync_processor.cc deleted file mode 100644 index 18c4f07..0000000 --- a/chrome/browser/extensions/settings/settings_sync_processor.cc +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/settings_namespace.h" -#include "chrome/browser/extensions/settings/settings_sync_processor.h" -#include "chrome/browser/extensions/settings/settings_sync_util.h" -#include "content/public/browser/browser_thread.h" -#include "sync/api/sync_change_processor.h" -#include "sync/api/sync_data.h" -#include "sync/protocol/extension_setting_specifics.pb.h" - -using content::BrowserThread; - -namespace extensions { - -SettingsSyncProcessor::SettingsSyncProcessor( - const std::string& extension_id, - syncer::ModelType type, - syncer::SyncChangeProcessor* sync_processor) - : extension_id_(extension_id), - type_(type), - sync_processor_(sync_processor), - initialized_(false) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - CHECK(type == syncer::EXTENSION_SETTINGS || type == syncer::APP_SETTINGS); - CHECK(sync_processor); -} - -SettingsSyncProcessor::~SettingsSyncProcessor() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); -} - -void SettingsSyncProcessor::Init(const DictionaryValue& initial_state) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - CHECK(!initialized_) << "Init called multiple times"; - - for (DictionaryValue::Iterator i(initial_state); i.HasNext(); i.Advance()) - synced_keys_.insert(i.key()); - - initialized_ = true; -} - -syncer::SyncError SettingsSyncProcessor::SendChanges( - const ValueStoreChangeList& changes) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - CHECK(initialized_) << "Init not called"; - - syncer::SyncChangeList sync_changes; - std::set<std::string> added_keys; - std::set<std::string> deleted_keys; - - for (ValueStoreChangeList::const_iterator i = changes.begin(); - i != changes.end(); ++i) { - const std::string& key = i->key(); - const Value* value = i->new_value(); - if (value) { - if (synced_keys_.count(key)) { - // New value, key is synced; send ACTION_UPDATE. - sync_changes.push_back(settings_sync_util::CreateUpdate( - extension_id_, key, *value, type_)); - } else { - // New value, key is not synced; send ACTION_ADD. - sync_changes.push_back(settings_sync_util::CreateAdd( - extension_id_, key, *value, type_)); - added_keys.insert(key); - } - } else { - if (synced_keys_.count(key)) { - // Clearing value, key is synced; send ACTION_DELETE. - sync_changes.push_back(settings_sync_util::CreateDelete( - extension_id_, key, type_)); - deleted_keys.insert(key); - } else { - LOG(WARNING) << "Deleted " << key << " but not in synced_keys_"; - } - } - } - - if (sync_changes.empty()) - return syncer::SyncError(); - - syncer::SyncError error = - sync_processor_->ProcessSyncChanges(FROM_HERE, sync_changes); - if (error.IsSet()) - return error; - - synced_keys_.insert(added_keys.begin(), added_keys.end()); - for (std::set<std::string>::iterator i = deleted_keys.begin(); - i != deleted_keys.end(); ++i) { - synced_keys_.erase(*i); - } - - return syncer::SyncError(); -} - -void SettingsSyncProcessor::NotifyChanges(const ValueStoreChangeList& changes) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - CHECK(initialized_) << "Init not called"; - - for (ValueStoreChangeList::const_iterator i = changes.begin(); - i != changes.end(); ++i) { - if (i->new_value()) - synced_keys_.insert(i->key()); - else - synced_keys_.erase(i->key()); - } -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_sync_processor.h b/chrome/browser/extensions/settings/settings_sync_processor.h deleted file mode 100644 index cd39815..0000000 --- a/chrome/browser/extensions/settings/settings_sync_processor.h +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_SYNC_PROCESSOR_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_SYNC_PROCESSOR_H_ - -#include <set> -#include <string> - -#include "chrome/browser/value_store/value_store_change.h" -#include "sync/api/sync_error.h" - -namespace syncer { -class SyncChangeProcessor; -} // namespace syncer - -namespace extensions { - -// A wrapper for a SyncChangeProcessor that deals specifically with the syncing -// of a single extension's settings. Handles: -// - translating SettingChanges into calls into the Sync API. -// - deciding whether to ADD/REMOVE/SET depending on the current state of -// settings. -// - rate limiting (inherently per-extension, which is what we want). -class SettingsSyncProcessor { - public: - SettingsSyncProcessor(const std::string& extension_id, - syncer::ModelType type, - syncer::SyncChangeProcessor* sync_processor); - ~SettingsSyncProcessor(); - - // Initializes this with the initial state of sync. - void Init(const DictionaryValue& initial_state); - - // Sends |changes| to sync. - syncer::SyncError SendChanges(const ValueStoreChangeList& changes); - - // Informs this that |changes| have been receieved from sync. No action will - // be taken, but this must be notified for internal bookkeeping. - void NotifyChanges(const ValueStoreChangeList& changes); - - syncer::ModelType type() { return type_; } - - private: - // ID of the extension the changes are for. - const std::string extension_id_; - - // Sync model type. Either EXTENSION_SETTING or APP_SETTING. - const syncer::ModelType type_; - - // The sync processor used to send changes to sync. - syncer::SyncChangeProcessor* const sync_processor_; - - // Whether Init() has been called. - bool initialized_; - - // Keys of the settings that are currently being synced. Used to decide what - // kind of action (ADD, UPDATE, REMOVE) to send to sync. - std::set<std::string> synced_keys_; - - DISALLOW_COPY_AND_ASSIGN(SettingsSyncProcessor); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_SYNC_PROCESSOR_H_ diff --git a/chrome/browser/extensions/settings/settings_sync_unittest.cc b/chrome/browser/extensions/settings/settings_sync_unittest.cc deleted file mode 100644 index 1386244..0000000 --- a/chrome/browser/extensions/settings/settings_sync_unittest.cc +++ /dev/null @@ -1,1426 +0,0 @@ -// Copyright (c) 2012 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 "testing/gtest/include/gtest/gtest.h" - -#include "base/bind.h" -#include "base/files/scoped_temp_dir.h" -#include "base/json/json_reader.h" -#include "base/json/json_writer.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop.h" -#include "chrome/browser/extensions/extension_system.h" -#include "chrome/browser/extensions/settings/leveldb_settings_storage_factory.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" -#include "chrome/browser/extensions/settings/settings_storage_factory.h" -#include "chrome/browser/extensions/settings/settings_sync_util.h" -#include "chrome/browser/extensions/settings/settings_test_util.h" -#include "chrome/browser/extensions/settings/syncable_settings_storage.h" -#include "chrome/browser/extensions/test_extension_service.h" -#include "chrome/browser/value_store/testing_value_store.h" -#include "content/public/test/test_browser_thread.h" -#include "sync/api/sync_change_processor.h" -#include "sync/api/sync_error_factory.h" -#include "sync/api/sync_error_factory_mock.h" - -using content::BrowserThread; - -namespace extensions { - -namespace util = settings_test_util; - -namespace { - -// To save typing ValueStore::DEFAULTS everywhere. -const ValueStore::WriteOptions DEFAULTS = ValueStore::DEFAULTS; - -// Gets the pretty-printed JSON for a value. -static std::string GetJson(const Value& value) { - std::string json; - base::JSONWriter::WriteWithOptions(&value, - base::JSONWriter::OPTIONS_PRETTY_PRINT, - &json); - return json; -} - -// Returns whether two Values are equal. -testing::AssertionResult ValuesEq( - const char* _1, const char* _2, - const Value* expected, - const Value* actual) { - if (expected == actual) { - return testing::AssertionSuccess(); - } - if (!expected && actual) { - return testing::AssertionFailure() << - "Expected NULL, actual: " << GetJson(*actual); - } - if (expected && !actual) { - return testing::AssertionFailure() << - "Expected: " << GetJson(*expected) << ", actual NULL"; - } - if (!expected->Equals(actual)) { - return testing::AssertionFailure() << - "Expected: " << GetJson(*expected) << ", actual: " << GetJson(*actual); - } - return testing::AssertionSuccess(); -} - -// Returns whether the result of a storage operation is an expected value. -// Logs when different. -testing::AssertionResult SettingsEq( - const char* _1, const char* _2, - const DictionaryValue& expected, - ValueStore::ReadResult actual) { - if (actual->HasError()) { - return testing::AssertionFailure() << - "Expected: " << GetJson(expected) << - ", actual has error: " << actual->error(); - } - return ValuesEq(_1, _2, &expected, actual->settings().get()); -} - -// SyncChangeProcessor which just records the changes made, accessed after -// being converted to the more useful SettingSyncData via changes(). -class MockSyncChangeProcessor : public syncer::SyncChangeProcessor { - public: - MockSyncChangeProcessor() : fail_all_requests_(false) {} - - // syncer::SyncChangeProcessor implementation. - virtual syncer::SyncError ProcessSyncChanges( - const tracked_objects::Location& from_here, - const syncer::SyncChangeList& change_list) OVERRIDE { - if (fail_all_requests_) { - return syncer::SyncError( - FROM_HERE, - "MockSyncChangeProcessor: configured to fail", - change_list[0].sync_data().GetDataType()); - } - for (syncer::SyncChangeList::const_iterator it = change_list.begin(); - it != change_list.end(); ++it) { - changes_.push_back(SettingSyncData(*it)); - } - return syncer::SyncError(); - } - - // Mock methods. - - const SettingSyncDataList& changes() { return changes_; } - - void ClearChanges() { - changes_.clear(); - } - - void SetFailAllRequests(bool fail_all_requests) { - fail_all_requests_ = fail_all_requests; - } - - // Returns the only change for a given extension setting. If there is not - // exactly 1 change for that key, a test assertion will fail. - SettingSyncData GetOnlyChange( - const std::string& extension_id, const std::string& key) { - SettingSyncDataList matching_changes; - for (SettingSyncDataList::iterator it = changes_.begin(); - it != changes_.end(); ++it) { - if (it->extension_id() == extension_id && it->key() == key) { - matching_changes.push_back(*it); - } - } - if (matching_changes.empty()) { - ADD_FAILURE() << "No matching changes for " << extension_id << "/" << - key << " (out of " << changes_.size() << ")"; - return SettingSyncData( - syncer::SyncChange::ACTION_INVALID, "", "", - scoped_ptr<Value>(new DictionaryValue())); - } - if (matching_changes.size() != 1u) { - ADD_FAILURE() << matching_changes.size() << " matching changes for " << - extension_id << "/" << key << " (out of " << changes_.size() << ")"; - } - return matching_changes[0]; - } - - private: - SettingSyncDataList changes_; - bool fail_all_requests_; -}; - -class SyncChangeProcessorDelegate : public syncer::SyncChangeProcessor { - public: - explicit SyncChangeProcessorDelegate(syncer::SyncChangeProcessor* recipient) - : recipient_(recipient) { - DCHECK(recipient_); - } - virtual ~SyncChangeProcessorDelegate() {} - - // syncer::SyncChangeProcessor implementation. - virtual syncer::SyncError ProcessSyncChanges( - const tracked_objects::Location& from_here, - const syncer::SyncChangeList& change_list) OVERRIDE { - return recipient_->ProcessSyncChanges(from_here, change_list); - } - - private: - // The recipient of all sync changes. - syncer::SyncChangeProcessor* recipient_; - - DISALLOW_COPY_AND_ASSIGN(SyncChangeProcessorDelegate); -}; - -// SettingsStorageFactory which always returns TestingValueStore objects, -// and allows individually created objects to be returned. -class TestingValueStoreFactory : public SettingsStorageFactory { - public: - TestingValueStore* GetExisting(const std::string& extension_id) { - DCHECK(created_.count(extension_id)); - return created_[extension_id]; - } - - // SettingsStorageFactory implementation. - virtual ValueStore* Create(const FilePath& base_path, - const std::string& extension_id) OVERRIDE { - TestingValueStore* new_storage = new TestingValueStore(); - DCHECK(!created_.count(extension_id)); - created_[extension_id] = new_storage; - return new_storage; - } - - private: - // SettingsStorageFactory is refcounted. - virtual ~TestingValueStoreFactory() {} - - // None of these storage areas are owned by this factory, so care must be - // taken when calling GetExisting. - std::map<std::string, TestingValueStore*> created_; -}; - -} // namespace - -class ExtensionSettingsSyncTest : public testing::Test { - public: - ExtensionSettingsSyncTest() - : ui_thread_(BrowserThread::UI, MessageLoop::current()), - file_thread_(BrowserThread::FILE, MessageLoop::current()), - storage_factory_(new util::ScopedSettingsStorageFactory()), - sync_processor_(new MockSyncChangeProcessor), - sync_processor_delegate_(new SyncChangeProcessorDelegate( - sync_processor_.get())) {} - - virtual void SetUp() OVERRIDE { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - profile_.reset(new util::MockProfile(temp_dir_.path())); - storage_factory_->Reset(new LeveldbSettingsStorageFactory()); - frontend_.reset( - SettingsFrontend::Create(storage_factory_.get(), profile_.get())); - } - - virtual void TearDown() OVERRIDE { - frontend_.reset(); - profile_.reset(); - // Execute any pending deletion tasks. - message_loop_.RunUntilIdle(); - } - - protected: - // Adds a record of an extension or app to the extension service, then returns - // its storage area. - ValueStore* AddExtensionAndGetStorage( - const std::string& id, Extension::Type type) { - ExtensionServiceInterface* esi = - extensions::ExtensionSystem::Get(profile_.get())->extension_service(); - static_cast<extensions::settings_test_util::MockExtensionService*>(esi)-> - AddExtensionWithId(id, type); - return util::GetStorage(id, frontend_.get()); - } - - // Gets the syncer::SyncableService for the given sync type. - syncer::SyncableService* GetSyncableService(syncer::ModelType model_type) { - MessageLoop::current()->RunUntilIdle(); - return frontend_->GetBackendForSync(model_type); - } - - // Gets all the sync data from the SyncableService for a sync type as a map - // from extension id to its sync data. - std::map<std::string, SettingSyncDataList> GetAllSyncData( - syncer::ModelType model_type) { - syncer::SyncDataList as_list = - GetSyncableService(model_type)->GetAllSyncData(model_type); - std::map<std::string, SettingSyncDataList> as_map; - for (syncer::SyncDataList::iterator it = as_list.begin(); - it != as_list.end(); ++it) { - SettingSyncData sync_data(*it); - as_map[sync_data.extension_id()].push_back(sync_data); - } - return as_map; - } - - // Need these so that the DCHECKs for running on FILE or UI threads pass. - MessageLoop message_loop_; - content::TestBrowserThread ui_thread_; - content::TestBrowserThread file_thread_; - - base::ScopedTempDir temp_dir_; - scoped_ptr<util::MockProfile> profile_; - scoped_ptr<SettingsFrontend> frontend_; - scoped_refptr<util::ScopedSettingsStorageFactory> storage_factory_; - scoped_ptr<MockSyncChangeProcessor> sync_processor_; - scoped_ptr<SyncChangeProcessorDelegate> sync_processor_delegate_; -}; - -// Get a semblance of coverage for both EXTENSION_SETTINGS and APP_SETTINGS -// sync by roughly alternative which one to test. - -TEST_F(ExtensionSettingsSyncTest, NoDataDoesNotInvokeSync) { - syncer::ModelType model_type = syncer::EXTENSION_SETTINGS; - Extension::Type type = Extension::TYPE_EXTENSION; - - EXPECT_EQ(0u, GetAllSyncData(model_type).size()); - - // Have one extension created before sync is set up, the other created after. - AddExtensionAndGetStorage("s1", type); - EXPECT_EQ(0u, GetAllSyncData(model_type).size()); - - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - AddExtensionAndGetStorage("s2", type); - EXPECT_EQ(0u, GetAllSyncData(model_type).size()); - - GetSyncableService(model_type)->StopSyncing(model_type); - - EXPECT_EQ(0u, sync_processor_->changes().size()); - EXPECT_EQ(0u, GetAllSyncData(model_type).size()); -} - -TEST_F(ExtensionSettingsSyncTest, InSyncDataDoesNotInvokeSync) { - syncer::ModelType model_type = syncer::APP_SETTINGS; - Extension::Type type = Extension::TYPE_LEGACY_PACKAGED_APP; - - StringValue value1("fooValue"); - ListValue value2; - value2.Append(StringValue::CreateStringValue("barValue")); - - ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); - ValueStore* storage2 = AddExtensionAndGetStorage("s2", type); - - storage1->Set(DEFAULTS, "foo", value1); - storage2->Set(DEFAULTS, "bar", value2); - - std::map<std::string, SettingSyncDataList> all_sync_data = - GetAllSyncData(model_type); - EXPECT_EQ(2u, all_sync_data.size()); - EXPECT_EQ(1u, all_sync_data["s1"].size()); - EXPECT_PRED_FORMAT2(ValuesEq, &value1, &all_sync_data["s1"][0].value()); - EXPECT_EQ(1u, all_sync_data["s2"].size()); - EXPECT_PRED_FORMAT2(ValuesEq, &value2, &all_sync_data["s2"][0].value()); - - syncer::SyncDataList sync_data; - sync_data.push_back(settings_sync_util::CreateData( - "s1", "foo", value1, model_type)); - sync_data.push_back(settings_sync_util::CreateData( - "s2", "bar", value2, model_type)); - - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, sync_data, - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - // Already in sync, so no changes. - EXPECT_EQ(0u, sync_processor_->changes().size()); - - // Regression test: not-changing the synced value shouldn't result in a sync - // change, and changing the synced value should result in an update. - storage1->Set(DEFAULTS, "foo", value1); - EXPECT_EQ(0u, sync_processor_->changes().size()); - - storage1->Set(DEFAULTS, "foo", value2); - EXPECT_EQ(1u, sync_processor_->changes().size()); - SettingSyncData change = sync_processor_->GetOnlyChange("s1", "foo"); - EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, change.change_type()); - EXPECT_TRUE(value2.Equals(&change.value())); - - GetSyncableService(model_type)->StopSyncing(model_type); -} - -TEST_F(ExtensionSettingsSyncTest, LocalDataWithNoSyncDataIsPushedToSync) { - syncer::ModelType model_type = syncer::EXTENSION_SETTINGS; - Extension::Type type = Extension::TYPE_EXTENSION; - - StringValue value1("fooValue"); - ListValue value2; - value2.Append(StringValue::CreateStringValue("barValue")); - - ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); - ValueStore* storage2 = AddExtensionAndGetStorage("s2", type); - - storage1->Set(DEFAULTS, "foo", value1); - storage2->Set(DEFAULTS, "bar", value2); - - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - // All settings should have been pushed to sync. - EXPECT_EQ(2u, sync_processor_->changes().size()); - SettingSyncData change = sync_processor_->GetOnlyChange("s1", "foo"); - EXPECT_EQ(syncer::SyncChange::ACTION_ADD, change.change_type()); - EXPECT_TRUE(value1.Equals(&change.value())); - change = sync_processor_->GetOnlyChange("s2", "bar"); - EXPECT_EQ(syncer::SyncChange::ACTION_ADD, change.change_type()); - EXPECT_TRUE(value2.Equals(&change.value())); - - GetSyncableService(model_type)->StopSyncing(model_type); -} - -TEST_F(ExtensionSettingsSyncTest, AnySyncDataOverwritesLocalData) { - syncer::ModelType model_type = syncer::APP_SETTINGS; - Extension::Type type = Extension::TYPE_LEGACY_PACKAGED_APP; - - StringValue value1("fooValue"); - ListValue value2; - value2.Append(StringValue::CreateStringValue("barValue")); - - // Maintain dictionaries mirrored to the expected values of the settings in - // each storage area. - DictionaryValue expected1, expected2; - - // Pre-populate one of the storage areas. - ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); - storage1->Set(DEFAULTS, "overwriteMe", value1); - - syncer::SyncDataList sync_data; - sync_data.push_back(settings_sync_util::CreateData( - "s1", "foo", value1, model_type)); - sync_data.push_back(settings_sync_util::CreateData( - "s2", "bar", value2, model_type)); - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, sync_data, - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - expected1.Set("foo", value1.DeepCopy()); - expected2.Set("bar", value2.DeepCopy()); - - ValueStore* storage2 = AddExtensionAndGetStorage("s2", type); - - // All changes should be local, so no sync changes. - EXPECT_EQ(0u, sync_processor_->changes().size()); - - // Sync settings should have been pushed to local settings. - EXPECT_PRED_FORMAT2(SettingsEq, expected1, storage1->Get()); - EXPECT_PRED_FORMAT2(SettingsEq, expected2, storage2->Get()); - - GetSyncableService(model_type)->StopSyncing(model_type); -} - -TEST_F(ExtensionSettingsSyncTest, ProcessSyncChanges) { - syncer::ModelType model_type = syncer::EXTENSION_SETTINGS; - Extension::Type type = Extension::TYPE_EXTENSION; - - StringValue value1("fooValue"); - ListValue value2; - value2.Append(StringValue::CreateStringValue("barValue")); - - // Maintain dictionaries mirrored to the expected values of the settings in - // each storage area. - DictionaryValue expected1, expected2; - - // Make storage1 initialised from local data, storage2 initialised from sync. - ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); - ValueStore* storage2 = AddExtensionAndGetStorage("s2", type); - - storage1->Set(DEFAULTS, "foo", value1); - expected1.Set("foo", value1.DeepCopy()); - - syncer::SyncDataList sync_data; - sync_data.push_back(settings_sync_util::CreateData( - "s2", "bar", value2, model_type)); - - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, sync_data, - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - expected2.Set("bar", value2.DeepCopy()); - - // Make sync add some settings. - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateAdd( - "s1", "bar", value2, model_type)); - change_list.push_back(settings_sync_util::CreateAdd( - "s2", "foo", value1, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - expected1.Set("bar", value2.DeepCopy()); - expected2.Set("foo", value1.DeepCopy()); - - EXPECT_PRED_FORMAT2(SettingsEq, expected1, storage1->Get()); - EXPECT_PRED_FORMAT2(SettingsEq, expected2, storage2->Get()); - - // Make sync update some settings, storage1 the new setting, storage2 the - // initial setting. - change_list.clear(); - change_list.push_back(settings_sync_util::CreateUpdate( - "s1", "bar", value2, model_type)); - change_list.push_back(settings_sync_util::CreateUpdate( - "s2", "bar", value1, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - expected1.Set("bar", value2.DeepCopy()); - expected2.Set("bar", value1.DeepCopy()); - - EXPECT_PRED_FORMAT2(SettingsEq, expected1, storage1->Get()); - EXPECT_PRED_FORMAT2(SettingsEq, expected2, storage2->Get()); - - // Make sync remove some settings, storage1 the initial setting, storage2 the - // new setting. - change_list.clear(); - change_list.push_back(settings_sync_util::CreateDelete( - "s1", "foo", model_type)); - change_list.push_back(settings_sync_util::CreateDelete( - "s2", "foo", model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - expected1.Remove("foo", NULL); - expected2.Remove("foo", NULL); - - EXPECT_PRED_FORMAT2(SettingsEq, expected1, storage1->Get()); - EXPECT_PRED_FORMAT2(SettingsEq, expected2, storage2->Get()); - - GetSyncableService(model_type)->StopSyncing(model_type); -} - -TEST_F(ExtensionSettingsSyncTest, PushToSync) { - syncer::ModelType model_type = syncer::APP_SETTINGS; - Extension::Type type = Extension::TYPE_LEGACY_PACKAGED_APP; - - StringValue value1("fooValue"); - ListValue value2; - value2.Append(StringValue::CreateStringValue("barValue")); - - // Make storage1/2 initialised from local data, storage3/4 initialised from - // sync. - ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); - ValueStore* storage2 = AddExtensionAndGetStorage("s2", type); - ValueStore* storage3 = AddExtensionAndGetStorage("s3", type); - ValueStore* storage4 = AddExtensionAndGetStorage("s4", type); - - storage1->Set(DEFAULTS, "foo", value1); - storage2->Set(DEFAULTS, "foo", value1); - - syncer::SyncDataList sync_data; - sync_data.push_back(settings_sync_util::CreateData( - "s3", "bar", value2, model_type)); - sync_data.push_back(settings_sync_util::CreateData( - "s4", "bar", value2, model_type)); - - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, sync_data, - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - // Add something locally. - storage1->Set(DEFAULTS, "bar", value2); - storage2->Set(DEFAULTS, "bar", value2); - storage3->Set(DEFAULTS, "foo", value1); - storage4->Set(DEFAULTS, "foo", value1); - - SettingSyncData change = sync_processor_->GetOnlyChange("s1", "bar"); - EXPECT_EQ(syncer::SyncChange::ACTION_ADD, change.change_type()); - EXPECT_TRUE(value2.Equals(&change.value())); - sync_processor_->GetOnlyChange("s2", "bar"); - EXPECT_EQ(syncer::SyncChange::ACTION_ADD, change.change_type()); - EXPECT_TRUE(value2.Equals(&change.value())); - change = sync_processor_->GetOnlyChange("s3", "foo"); - EXPECT_EQ(syncer::SyncChange::ACTION_ADD, change.change_type()); - EXPECT_TRUE(value1.Equals(&change.value())); - change = sync_processor_->GetOnlyChange("s4", "foo"); - EXPECT_EQ(syncer::SyncChange::ACTION_ADD, change.change_type()); - EXPECT_TRUE(value1.Equals(&change.value())); - - // Change something locally, storage1/3 the new setting and storage2/4 the - // initial setting, for all combinations of local vs sync intialisation and - // new vs initial. - sync_processor_->ClearChanges(); - storage1->Set(DEFAULTS, "bar", value1); - storage2->Set(DEFAULTS, "foo", value2); - storage3->Set(DEFAULTS, "bar", value1); - storage4->Set(DEFAULTS, "foo", value2); - - change = sync_processor_->GetOnlyChange("s1", "bar"); - EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, change.change_type()); - EXPECT_TRUE(value1.Equals(&change.value())); - change = sync_processor_->GetOnlyChange("s2", "foo"); - EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, change.change_type()); - EXPECT_TRUE(value2.Equals(&change.value())); - change = sync_processor_->GetOnlyChange("s3", "bar"); - EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, change.change_type()); - EXPECT_TRUE(value1.Equals(&change.value())); - change = sync_processor_->GetOnlyChange("s4", "foo"); - EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, change.change_type()); - EXPECT_TRUE(value2.Equals(&change.value())); - - // Remove something locally, storage1/3 the new setting and storage2/4 the - // initial setting, for all combinations of local vs sync intialisation and - // new vs initial. - sync_processor_->ClearChanges(); - storage1->Remove("foo"); - storage2->Remove("bar"); - storage3->Remove("foo"); - storage4->Remove("bar"); - - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s1", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s2", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s3", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s4", "bar").change_type()); - - // Remove some nonexistent settings. - sync_processor_->ClearChanges(); - storage1->Remove("foo"); - storage2->Remove("bar"); - storage3->Remove("foo"); - storage4->Remove("bar"); - - EXPECT_EQ(0u, sync_processor_->changes().size()); - - // Clear the rest of the settings. Add the removed ones back first so that - // more than one setting is cleared. - storage1->Set(DEFAULTS, "foo", value1); - storage2->Set(DEFAULTS, "bar", value2); - storage3->Set(DEFAULTS, "foo", value1); - storage4->Set(DEFAULTS, "bar", value2); - - sync_processor_->ClearChanges(); - storage1->Clear(); - storage2->Clear(); - storage3->Clear(); - storage4->Clear(); - - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s1", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s1", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s2", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s2", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s3", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s3", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s4", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_DELETE, - sync_processor_->GetOnlyChange("s4", "bar").change_type()); - - GetSyncableService(model_type)->StopSyncing(model_type); -} - -TEST_F(ExtensionSettingsSyncTest, ExtensionAndAppSettingsSyncSeparately) { - StringValue value1("fooValue"); - ListValue value2; - value2.Append(StringValue::CreateStringValue("barValue")); - - // storage1 is an extension, storage2 is an app. - ValueStore* storage1 = AddExtensionAndGetStorage( - "s1", Extension::TYPE_EXTENSION); - ValueStore* storage2 = AddExtensionAndGetStorage( - "s2", Extension::TYPE_LEGACY_PACKAGED_APP); - - storage1->Set(DEFAULTS, "foo", value1); - storage2->Set(DEFAULTS, "bar", value2); - - std::map<std::string, SettingSyncDataList> extension_sync_data = - GetAllSyncData(syncer::EXTENSION_SETTINGS); - EXPECT_EQ(1u, extension_sync_data.size()); - EXPECT_EQ(1u, extension_sync_data["s1"].size()); - EXPECT_PRED_FORMAT2(ValuesEq, &value1, &extension_sync_data["s1"][0].value()); - - std::map<std::string, SettingSyncDataList> app_sync_data = - GetAllSyncData(syncer::APP_SETTINGS); - EXPECT_EQ(1u, app_sync_data.size()); - EXPECT_EQ(1u, app_sync_data["s2"].size()); - EXPECT_PRED_FORMAT2(ValuesEq, &value2, &app_sync_data["s2"][0].value()); - - // Stop each separately, there should be no changes either time. - syncer::SyncDataList sync_data; - sync_data.push_back(settings_sync_util::CreateData( - "s1", "foo", value1, syncer::EXTENSION_SETTINGS)); - - GetSyncableService(syncer::EXTENSION_SETTINGS)->MergeDataAndStartSyncing( - syncer::EXTENSION_SETTINGS, - sync_data, - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - GetSyncableService(syncer::EXTENSION_SETTINGS)-> - StopSyncing(syncer::EXTENSION_SETTINGS); - EXPECT_EQ(0u, sync_processor_->changes().size()); - - sync_data.clear(); - sync_data.push_back(settings_sync_util::CreateData( - "s2", "bar", value2, syncer::APP_SETTINGS)); - - scoped_ptr<SyncChangeProcessorDelegate> app_settings_delegate_( - new SyncChangeProcessorDelegate(sync_processor_.get())); - GetSyncableService(syncer::APP_SETTINGS)->MergeDataAndStartSyncing( - syncer::APP_SETTINGS, - sync_data, - app_settings_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - GetSyncableService(syncer::APP_SETTINGS)-> - StopSyncing(syncer::APP_SETTINGS); - EXPECT_EQ(0u, sync_processor_->changes().size()); -} - -TEST_F(ExtensionSettingsSyncTest, FailingStartSyncingDisablesSync) { - syncer::ModelType model_type = syncer::EXTENSION_SETTINGS; - Extension::Type type = Extension::TYPE_EXTENSION; - - StringValue fooValue("fooValue"); - StringValue barValue("barValue"); - - // There is a bit of a convoluted method to get storage areas that can fail; - // hand out TestingValueStore object then toggle them failing/succeeding - // as necessary. - TestingValueStoreFactory* testing_factory = new TestingValueStoreFactory(); - storage_factory_->Reset(testing_factory); - - ValueStore* good = AddExtensionAndGetStorage("good", type); - ValueStore* bad = AddExtensionAndGetStorage("bad", type); - - // Make bad fail for incoming sync changes. - testing_factory->GetExisting("bad")->SetFailAllRequests(true); - { - syncer::SyncDataList sync_data; - sync_data.push_back(settings_sync_util::CreateData( - "good", "foo", fooValue, model_type)); - sync_data.push_back(settings_sync_util::CreateData( - "bad", "foo", fooValue, model_type)); - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - sync_data, - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())); - } - testing_factory->GetExisting("bad")->SetFailAllRequests(false); - - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // Changes made to good should be sent to sync, changes from bad shouldn't. - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "bar", barValue); - bad->Set(DEFAULTS, "bar", barValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ(1u, sync_processor_->changes().size()); - - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // Changes received from sync should go to good but not bad (even when it's - // not failing). - { - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateUpdate( - "good", "foo", barValue, model_type)); - // (Sending UPDATE here even though it's adding, since that's what the state - // of sync is. In any case, it won't work.) - change_list.push_back(settings_sync_util::CreateUpdate( - "bad", "foo", barValue, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - } - - { - DictionaryValue dict; - dict.Set("foo", barValue.DeepCopy()); - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // Changes made to bad still shouldn't go to sync, even though it didn't fail - // last time. - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "bar", fooValue); - bad->Set(DEFAULTS, "bar", fooValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ(1u, sync_processor_->changes().size()); - - { - DictionaryValue dict; - dict.Set("foo", barValue.DeepCopy()); - dict.Set("bar", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("bar", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // Failing ProcessSyncChanges shouldn't go to the storage. - testing_factory->GetExisting("bad")->SetFailAllRequests(true); - { - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateUpdate( - "good", "foo", fooValue, model_type)); - // (Ditto.) - change_list.push_back(settings_sync_util::CreateUpdate( - "bad", "foo", fooValue, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - } - testing_factory->GetExisting("bad")->SetFailAllRequests(false); - - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - dict.Set("bar", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("bar", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // Restarting sync should make bad start syncing again. - sync_processor_->ClearChanges(); - GetSyncableService(model_type)->StopSyncing(model_type); - sync_processor_delegate_.reset(new SyncChangeProcessorDelegate( - sync_processor_.get())); - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - // Local settings will have been pushed to sync, since it's empty (in this - // test; presumably it wouldn't be live, since we've been getting changes). - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("bad", "bar").change_type()); - EXPECT_EQ(3u, sync_processor_->changes().size()); - - // Live local changes now get pushed, too. - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "bar", barValue); - bad->Set(DEFAULTS, "bar", barValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("bad", "bar").change_type()); - EXPECT_EQ(2u, sync_processor_->changes().size()); - - // And ProcessSyncChanges work, too. - { - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateUpdate( - "good", "bar", fooValue, model_type)); - change_list.push_back(settings_sync_util::CreateUpdate( - "bad", "bar", fooValue, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - } - - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - dict.Set("bar", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("bar", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } -} - -TEST_F(ExtensionSettingsSyncTest, FailingProcessChangesDisablesSync) { - // The test above tests a failing ProcessSyncChanges too, but here test with - // an initially passing MergeDataAndStartSyncing. - syncer::ModelType model_type = syncer::APP_SETTINGS; - Extension::Type type = Extension::TYPE_LEGACY_PACKAGED_APP; - - StringValue fooValue("fooValue"); - StringValue barValue("barValue"); - - TestingValueStoreFactory* testing_factory = new TestingValueStoreFactory(); - storage_factory_->Reset(testing_factory); - - ValueStore* good = AddExtensionAndGetStorage("good", type); - ValueStore* bad = AddExtensionAndGetStorage("bad", type); - - // Unlike before, initially succeeding MergeDataAndStartSyncing. - { - syncer::SyncDataList sync_data; - sync_data.push_back(settings_sync_util::CreateData( - "good", "foo", fooValue, model_type)); - sync_data.push_back(settings_sync_util::CreateData( - "bad", "foo", fooValue, model_type)); - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - sync_data, - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())); - } - - EXPECT_EQ(0u, sync_processor_->changes().size()); - - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // Now fail ProcessSyncChanges for bad. - testing_factory->GetExisting("bad")->SetFailAllRequests(true); - { - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateAdd( - "good", "bar", barValue, model_type)); - change_list.push_back(settings_sync_util::CreateAdd( - "bad", "bar", barValue, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - } - testing_factory->GetExisting("bad")->SetFailAllRequests(false); - - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // No more changes sent to sync for bad. - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "foo", barValue); - bad->Set(DEFAULTS, "foo", barValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ(1u, sync_processor_->changes().size()); - - // No more changes received from sync should go to bad. - { - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateAdd( - "good", "foo", fooValue, model_type)); - change_list.push_back(settings_sync_util::CreateAdd( - "bad", "foo", fooValue, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - } - - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("foo", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } -} - -TEST_F(ExtensionSettingsSyncTest, FailingGetAllSyncDataDoesntStopSync) { - syncer::ModelType model_type = syncer::EXTENSION_SETTINGS; - Extension::Type type = Extension::TYPE_EXTENSION; - - StringValue fooValue("fooValue"); - StringValue barValue("barValue"); - - TestingValueStoreFactory* testing_factory = new TestingValueStoreFactory(); - storage_factory_->Reset(testing_factory); - - ValueStore* good = AddExtensionAndGetStorage("good", type); - ValueStore* bad = AddExtensionAndGetStorage("bad", type); - - good->Set(DEFAULTS, "foo", fooValue); - bad->Set(DEFAULTS, "foo", fooValue); - - // Even though bad will fail to get all sync data, sync data should still - // include that from good. - testing_factory->GetExisting("bad")->SetFailAllRequests(true); - { - syncer::SyncDataList all_sync_data = - GetSyncableService(model_type)->GetAllSyncData(model_type); - EXPECT_EQ(1u, all_sync_data.size()); - EXPECT_EQ("good/foo", all_sync_data[0].GetTag()); - } - testing_factory->GetExisting("bad")->SetFailAllRequests(false); - - // Sync shouldn't be disabled for good (nor bad -- but this is unimportant). - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("bad", "foo").change_type()); - EXPECT_EQ(2u, sync_processor_->changes().size()); - - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "bar", barValue); - bad->Set(DEFAULTS, "bar", barValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("bad", "bar").change_type()); - EXPECT_EQ(2u, sync_processor_->changes().size()); -} - -TEST_F(ExtensionSettingsSyncTest, FailureToReadChangesToPushDisablesSync) { - syncer::ModelType model_type = syncer::APP_SETTINGS; - Extension::Type type = Extension::TYPE_LEGACY_PACKAGED_APP; - - StringValue fooValue("fooValue"); - StringValue barValue("barValue"); - - TestingValueStoreFactory* testing_factory = new TestingValueStoreFactory(); - storage_factory_->Reset(testing_factory); - - ValueStore* good = AddExtensionAndGetStorage("good", type); - ValueStore* bad = AddExtensionAndGetStorage("bad", type); - - good->Set(DEFAULTS, "foo", fooValue); - bad->Set(DEFAULTS, "foo", fooValue); - - // good will successfully push foo:fooValue to sync, but bad will fail to - // get them so won't. - testing_factory->GetExisting("bad")->SetFailAllRequests(true); - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - testing_factory->GetExisting("bad")->SetFailAllRequests(false); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ(1u, sync_processor_->changes().size()); - - // bad should now be disabled for sync. - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "bar", barValue); - bad->Set(DEFAULTS, "bar", barValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ(1u, sync_processor_->changes().size()); - - { - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateUpdate( - "good", "foo", barValue, model_type)); - // (Sending ADD here even though it's updating, since that's what the state - // of sync is. In any case, it won't work.) - change_list.push_back(settings_sync_util::CreateAdd( - "bad", "foo", barValue, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - } - - { - DictionaryValue dict; - dict.Set("foo", barValue.DeepCopy()); - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("foo", fooValue.DeepCopy()); - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // Re-enabling sync without failing should cause the local changes from bad - // to be pushed to sync successfully, as should future changes to bad. - sync_processor_->ClearChanges(); - GetSyncableService(model_type)->StopSyncing(model_type); - sync_processor_delegate_.reset(new SyncChangeProcessorDelegate( - sync_processor_.get())); - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("bad", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("bad", "bar").change_type()); - EXPECT_EQ(4u, sync_processor_->changes().size()); - - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "bar", fooValue); - bad->Set(DEFAULTS, "bar", fooValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ(2u, sync_processor_->changes().size()); -} - -TEST_F(ExtensionSettingsSyncTest, FailureToPushLocalStateDisablesSync) { - syncer::ModelType model_type = syncer::EXTENSION_SETTINGS; - Extension::Type type = Extension::TYPE_EXTENSION; - - StringValue fooValue("fooValue"); - StringValue barValue("barValue"); - - TestingValueStoreFactory* testing_factory = new TestingValueStoreFactory(); - storage_factory_->Reset(testing_factory); - - ValueStore* good = AddExtensionAndGetStorage("good", type); - ValueStore* bad = AddExtensionAndGetStorage("bad", type); - - // Only set bad; setting good will cause it to fail below. - bad->Set(DEFAULTS, "foo", fooValue); - - sync_processor_->SetFailAllRequests(true); - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - sync_processor_->SetFailAllRequests(false); - - // Changes from good will be send to sync, changes from bad won't. - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "foo", barValue); - bad->Set(DEFAULTS, "foo", barValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ(1u, sync_processor_->changes().size()); - - // Changes from sync will be sent to good, not to bad. - { - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateAdd( - "good", "bar", barValue, model_type)); - change_list.push_back(settings_sync_util::CreateAdd( - "bad", "bar", barValue, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - } - - { - DictionaryValue dict; - dict.Set("foo", barValue.DeepCopy()); - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("foo", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // Restarting sync makes everything work again. - sync_processor_->ClearChanges(); - GetSyncableService(model_type)->StopSyncing(model_type); - sync_processor_delegate_.reset(new SyncChangeProcessorDelegate( - sync_processor_.get())); - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("bad", "foo").change_type()); - EXPECT_EQ(3u, sync_processor_->changes().size()); - - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "foo", fooValue); - bad->Set(DEFAULTS, "foo", fooValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ(2u, sync_processor_->changes().size()); -} - -TEST_F(ExtensionSettingsSyncTest, FailureToPushLocalChangeDisablesSync) { - syncer::ModelType model_type = syncer::EXTENSION_SETTINGS; - Extension::Type type = Extension::TYPE_EXTENSION; - - StringValue fooValue("fooValue"); - StringValue barValue("barValue"); - - TestingValueStoreFactory* testing_factory = new TestingValueStoreFactory(); - storage_factory_->Reset(testing_factory); - - ValueStore* good = AddExtensionAndGetStorage("good", type); - ValueStore* bad = AddExtensionAndGetStorage("bad", type); - - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - // bad will fail to send changes. - good->Set(DEFAULTS, "foo", fooValue); - sync_processor_->SetFailAllRequests(true); - bad->Set(DEFAULTS, "foo", fooValue); - sync_processor_->SetFailAllRequests(false); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ(1u, sync_processor_->changes().size()); - - // No further changes should be sent from bad. - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "foo", barValue); - bad->Set(DEFAULTS, "foo", barValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ(1u, sync_processor_->changes().size()); - - // Changes from sync will be sent to good, not to bad. - { - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateAdd( - "good", "bar", barValue, model_type)); - change_list.push_back(settings_sync_util::CreateAdd( - "bad", "bar", barValue, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - } - - { - DictionaryValue dict; - dict.Set("foo", barValue.DeepCopy()); - dict.Set("bar", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, good->Get()); - } - { - DictionaryValue dict; - dict.Set("foo", barValue.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, dict, bad->Get()); - } - - // Restarting sync makes everything work again. - sync_processor_->ClearChanges(); - GetSyncableService(model_type)->StopSyncing(model_type); - sync_processor_delegate_.reset(new SyncChangeProcessorDelegate( - sync_processor_.get())); - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("good", "bar").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_ADD, - sync_processor_->GetOnlyChange("bad", "foo").change_type()); - EXPECT_EQ(3u, sync_processor_->changes().size()); - - sync_processor_->ClearChanges(); - good->Set(DEFAULTS, "foo", fooValue); - bad->Set(DEFAULTS, "foo", fooValue); - - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ( - syncer::SyncChange::ACTION_UPDATE, - sync_processor_->GetOnlyChange("good", "foo").change_type()); - EXPECT_EQ(2u, sync_processor_->changes().size()); -} - -TEST_F(ExtensionSettingsSyncTest, - LargeOutgoingChangeRejectedButIncomingAccepted) { - syncer::ModelType model_type = syncer::APP_SETTINGS; - Extension::Type type = Extension::TYPE_LEGACY_PACKAGED_APP; - - // This value should be larger than the limit in settings_backend.cc. - std::string string_5k; - for (size_t i = 0; i < 5000; ++i) { - string_5k.append("a"); - } - StringValue large_value(string_5k); - - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - syncer::SyncDataList(), - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock())); - - // Large local change rejected and doesn't get sent out. - ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); - EXPECT_TRUE(storage1->Set(DEFAULTS, "large_value", large_value)->HasError()); - EXPECT_EQ(0u, sync_processor_->changes().size()); - - // Large incoming change should still get accepted. - ValueStore* storage2 = AddExtensionAndGetStorage("s2", type); - { - syncer::SyncChangeList change_list; - change_list.push_back(settings_sync_util::CreateAdd( - "s1", "large_value", large_value, model_type)); - change_list.push_back(settings_sync_util::CreateAdd( - "s2", "large_value", large_value, model_type)); - GetSyncableService(model_type)->ProcessSyncChanges(FROM_HERE, change_list); - } - { - DictionaryValue expected; - expected.Set("large_value", large_value.DeepCopy()); - EXPECT_PRED_FORMAT2(SettingsEq, expected, storage1->Get()); - EXPECT_PRED_FORMAT2(SettingsEq, expected, storage2->Get()); - } - - GetSyncableService(model_type)->StopSyncing(model_type); -} - -TEST_F(ExtensionSettingsSyncTest, Dots) { - syncer::ModelType model_type = syncer::EXTENSION_SETTINGS; - Extension::Type type = Extension::TYPE_EXTENSION; - - ValueStore* storage = AddExtensionAndGetStorage("ext", type); - - { - syncer::SyncDataList sync_data_list; - scoped_ptr<Value> string_value(Value::CreateStringValue("value")); - sync_data_list.push_back(settings_sync_util::CreateData( - "ext", "key.with.dot", *string_value, model_type)); - - GetSyncableService(model_type)->MergeDataAndStartSyncing( - model_type, - sync_data_list, - sync_processor_delegate_.PassAs<syncer::SyncChangeProcessor>(), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())); - } - - // Test dots in keys that come from sync. - { - ValueStore::ReadResult data = storage->Get(); - ASSERT_FALSE(data->HasError()); - - DictionaryValue expected_data; - expected_data.SetWithoutPathExpansion( - "key.with.dot", - Value::CreateStringValue("value")); - EXPECT_TRUE(Value::Equals(&expected_data, data->settings().get())); - } - - // Test dots in keys going to sync. - { - scoped_ptr<Value> string_value(Value::CreateStringValue("spot")); - storage->Set(DEFAULTS, "key.with.spot", *string_value); - - ASSERT_EQ(1u, sync_processor_->changes().size()); - SettingSyncData sync_data = sync_processor_->changes()[0]; - EXPECT_EQ(syncer::SyncChange::ACTION_ADD, sync_data.change_type()); - EXPECT_EQ("ext", sync_data.extension_id()); - EXPECT_EQ("key.with.spot", sync_data.key()); - EXPECT_TRUE(sync_data.value().Equals(string_value.get())); - } -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_sync_util.cc b/chrome/browser/extensions/settings/settings_sync_util.cc deleted file mode 100644 index 5c6c28a..0000000 --- a/chrome/browser/extensions/settings/settings_sync_util.cc +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/settings_sync_util.h" - -#include "base/json/json_writer.h" -#include "base/values.h" -#include "sync/protocol/app_setting_specifics.pb.h" -#include "sync/protocol/extension_setting_specifics.pb.h" -#include "sync/protocol/sync.pb.h" - -namespace extensions { - -namespace settings_sync_util { - -namespace { - -void PopulateExtensionSettingSpecifics( - const std::string& extension_id, - const std::string& key, - const Value& value, - sync_pb::ExtensionSettingSpecifics* specifics) { - specifics->set_extension_id(extension_id); - specifics->set_key(key); - { - std::string value_as_json; - base::JSONWriter::Write(&value, &value_as_json); - specifics->set_value(value_as_json); - } -} - -void PopulateAppSettingSpecifics( - const std::string& extension_id, - const std::string& key, - const Value& value, - sync_pb::AppSettingSpecifics* specifics) { - PopulateExtensionSettingSpecifics( - extension_id, key, value, specifics->mutable_extension_setting()); -} - -} // namespace - -syncer::SyncData CreateData( - const std::string& extension_id, - const std::string& key, - const Value& value, - syncer::ModelType type) { - sync_pb::EntitySpecifics specifics; - switch (type) { - case syncer::EXTENSION_SETTINGS: - PopulateExtensionSettingSpecifics( - extension_id, - key, - value, - specifics.mutable_extension_setting()); - break; - - case syncer::APP_SETTINGS: - PopulateAppSettingSpecifics( - extension_id, - key, - value, - specifics.mutable_app_setting()); - break; - - default: - NOTREACHED(); - } - - return syncer::SyncData::CreateLocalData( - extension_id + "/" + key, key, specifics); -} - -syncer::SyncChange CreateAdd( - const std::string& extension_id, - const std::string& key, - const Value& value, - syncer::ModelType type) { - return syncer::SyncChange( - FROM_HERE, - syncer::SyncChange::ACTION_ADD, - CreateData(extension_id, key, value, type)); -} - -syncer::SyncChange CreateUpdate( - const std::string& extension_id, - const std::string& key, - const Value& value, - syncer::ModelType type) { - return syncer::SyncChange( - FROM_HERE, - syncer::SyncChange::ACTION_UPDATE, - CreateData(extension_id, key, value, type)); -} - -syncer::SyncChange CreateDelete( - const std::string& extension_id, - const std::string& key, - syncer::ModelType type) { - DictionaryValue no_value; - return syncer::SyncChange( - FROM_HERE, - syncer::SyncChange::ACTION_DELETE, - CreateData(extension_id, key, no_value, type)); -} - -} // namespace settings_sync_util - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_sync_util.h b/chrome/browser/extensions/settings/settings_sync_util.h deleted file mode 100644 index 08769a3..0000000 --- a/chrome/browser/extensions/settings/settings_sync_util.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_SYNC_UTIL_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_SYNC_UTIL_H_ - - -#include "sync/api/sync_change.h" -#include "sync/api/sync_data.h" - -namespace base { -class Value; -} // namespace base - -namespace extensions { - -namespace settings_sync_util { - -// Creates a syncer::SyncData object for an extension or app setting. -syncer::SyncData CreateData( - const std::string& extension_id, - const std::string& key, - const base::Value& value, - syncer::ModelType type); - -// Creates an "add" sync change for an extension or app setting. -syncer::SyncChange CreateAdd( - const std::string& extension_id, - const std::string& key, - const base::Value& value, - syncer::ModelType type); - -// Creates an "update" sync change for an extension or app setting. -syncer::SyncChange CreateUpdate( - const std::string& extension_id, - const std::string& key, - const base::Value& value, - syncer::ModelType type); - -// Creates a "delete" sync change for an extension or app setting. -syncer::SyncChange CreateDelete( - const std::string& extension_id, - const std::string& key, - syncer::ModelType type); - -} // namespace settings_sync_util - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_SYNC_UTIL_H_ diff --git a/chrome/browser/extensions/settings/settings_test_util.cc b/chrome/browser/extensions/settings/settings_test_util.cc deleted file mode 100644 index 7f92850..0000000 --- a/chrome/browser/extensions/settings/settings_test_util.cc +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/settings_test_util.h" - -#include "base/file_path.h" -#include "chrome/common/extensions/extension.h" -#include "chrome/browser/extensions/extension_system_factory.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" - -namespace extensions { - -namespace settings_test_util { - -// Intended as a StorageCallback from GetStorage. -static void AssignStorage(ValueStore** dst, ValueStore* src) { - *dst = src; -} - -ValueStore* GetStorage( - const std::string& extension_id, - settings_namespace::Namespace settings_namespace, - SettingsFrontend* frontend) { - ValueStore* storage = NULL; - frontend->RunWithStorage( - extension_id, - settings_namespace, - base::Bind(&AssignStorage, &storage)); - MessageLoop::current()->RunUntilIdle(); - return storage; -} - -ValueStore* GetStorage( - const std::string& extension_id, SettingsFrontend* frontend) { - return GetStorage(extension_id, settings_namespace::SYNC, frontend); -} - -// MockExtensionService - -MockExtensionService::MockExtensionService() {} - -MockExtensionService::~MockExtensionService() {} - -const Extension* MockExtensionService::GetExtensionById( - const std::string& id, bool include_disabled) const { - std::map<std::string, scoped_refptr<Extension> >::const_iterator - maybe_extension = extensions_.find(id); - return maybe_extension == extensions_.end() ? - NULL : maybe_extension->second.get(); -} - -void MockExtensionService::AddExtensionWithId( - const std::string& id, Extension::Type type) { - std::set<std::string> empty_permissions; - AddExtensionWithIdAndPermissions(id, type, empty_permissions); -} - -void MockExtensionService::AddExtensionWithIdAndPermissions( - const std::string& id, - Extension::Type type, - const std::set<std::string>& permissions_set) { - DictionaryValue manifest; - manifest.SetString("name", std::string("Test extension ") + id); - manifest.SetString("version", "1.0"); - - scoped_ptr<ListValue> permissions(new ListValue()); - for (std::set<std::string>::const_iterator it = permissions_set.begin(); - it != permissions_set.end(); ++it) { - permissions->Append(Value::CreateStringValue(*it)); - } - manifest.Set("permissions", permissions.release()); - - switch (type) { - case Extension::TYPE_EXTENSION: - break; - - case Extension::TYPE_LEGACY_PACKAGED_APP: { - DictionaryValue* app = new DictionaryValue(); - DictionaryValue* app_launch = new DictionaryValue(); - app_launch->SetString("local_path", "fake.html"); - app->Set("launch", app_launch); - manifest.Set("app", app); - break; - } - - default: - NOTREACHED(); - } - - std::string error; - scoped_refptr<Extension> extension(Extension::Create( - FilePath(), - Extension::INTERNAL, - manifest, - Extension::NO_FLAGS, - id, - &error)); - DCHECK(extension.get()); - DCHECK(error.empty()); - extensions_[id] = extension; - - for (std::set<std::string>::const_iterator it = permissions_set.begin(); - it != permissions_set.end(); ++it) { - DCHECK(extension->HasAPIPermission(*it)); - } -} - -// MockExtensionSystem - -MockExtensionSystem::MockExtensionSystem(Profile* profile) - : TestExtensionSystem(profile) {} -MockExtensionSystem::~MockExtensionSystem() {} - -EventRouter* MockExtensionSystem::event_router() { - if (!event_router_.get()) - event_router_.reset(new EventRouter(profile_, NULL)); - return event_router_.get(); -} - -ExtensionService* MockExtensionSystem::extension_service() { - ExtensionServiceInterface* as_interface = - static_cast<ExtensionServiceInterface*>(&extension_service_); - return static_cast<ExtensionService*>(as_interface); -} - -ProfileKeyedService* BuildMockExtensionSystem(Profile* profile) { - return new MockExtensionSystem(profile); -} - -// MockProfile - -MockProfile::MockProfile(const FilePath& file_path) - : TestingProfile(file_path) { - ExtensionSystemFactory::GetInstance()->SetTestingFactoryAndUse(this, - &BuildMockExtensionSystem); -} - -MockProfile::~MockProfile() {} - -// ScopedSettingsFactory - -ScopedSettingsStorageFactory::ScopedSettingsStorageFactory() {} - -ScopedSettingsStorageFactory::ScopedSettingsStorageFactory( - const scoped_refptr<SettingsStorageFactory>& delegate) - : delegate_(delegate) {} - -ScopedSettingsStorageFactory::~ScopedSettingsStorageFactory() {} - -void ScopedSettingsStorageFactory::Reset( - const scoped_refptr<SettingsStorageFactory>& delegate) { - delegate_ = delegate; -} - -ValueStore* ScopedSettingsStorageFactory::Create( - const FilePath& base_path, - const std::string& extension_id) { - DCHECK(delegate_.get()); - return delegate_->Create(base_path, extension_id); -} - -} // namespace settings_test_util - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/settings_test_util.h b/chrome/browser/extensions/settings/settings_test_util.h deleted file mode 100644 index d1f3e44..0000000 --- a/chrome/browser/extensions/settings/settings_test_util.h +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_TEST_UTIL_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_TEST_UTIL_H_ - -#include <set> -#include <string> - -#include "base/compiler_specific.h" -#include "base/memory/linked_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/extensions/event_router.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/settings/settings_namespace.h" -#include "chrome/browser/extensions/settings/settings_storage_factory.h" -#include "chrome/browser/extensions/test_extension_service.h" -#include "chrome/browser/extensions/test_extension_system.h" -#include "chrome/common/extensions/extension.h" -#include "chrome/test/base/testing_profile.h" - -class ValueStore; - -namespace extensions { - -class SettingsFrontend; -// Utilities for extension settings API tests. -namespace settings_test_util { - -// Synchronously gets the storage area for an extension from |frontend|. -ValueStore* GetStorage( - const std::string& extension_id, - settings_namespace::Namespace setting_namespace, - SettingsFrontend* frontend); - -// Synchronously gets the SYNC storage for an extension from |frontend|. -ValueStore* GetStorage( - const std::string& extension_id, - SettingsFrontend* frontend); - -// An ExtensionService which allows extensions to be hand-added to be returned -// by GetExtensionById. -class MockExtensionService : public TestExtensionService { - public: - MockExtensionService(); - virtual ~MockExtensionService(); - - // Adds an extension with id |id| to be returned by GetExtensionById. - void AddExtensionWithId(const std::string& id, Extension::Type type); - - // Adds an extension with id |id| to be returned by GetExtensionById, with - // a set of permissions. - void AddExtensionWithIdAndPermissions( - const std::string& id, - Extension::Type type, - const std::set<std::string>& permissions); - - virtual const Extension* GetExtensionById( - const std::string& id, bool include_disabled) const OVERRIDE; - - private: - std::map<std::string, scoped_refptr<Extension> > extensions_; -}; - -// A mock ExtensionSystem to serve an EventRouter. -class MockExtensionSystem : public TestExtensionSystem { - public: - explicit MockExtensionSystem(Profile* profile); - virtual ~MockExtensionSystem(); - - virtual EventRouter* event_router() OVERRIDE; - virtual ExtensionService* extension_service() OVERRIDE; - - private: - scoped_ptr<EventRouter> event_router_; - MockExtensionService extension_service_; - - DISALLOW_COPY_AND_ASSIGN(MockExtensionSystem); -}; - -// A Profile which returns an ExtensionService with enough functionality for -// the tests. -class MockProfile : public TestingProfile { - public: - explicit MockProfile(const FilePath& file_path); - virtual ~MockProfile(); -}; - -// SettingsStorageFactory which acts as a wrapper for other factories. -class ScopedSettingsStorageFactory : public SettingsStorageFactory { - public: - ScopedSettingsStorageFactory(); - - explicit ScopedSettingsStorageFactory( - const scoped_refptr<SettingsStorageFactory>& delegate); - - // Sets the delegate factory (equivalent to scoped_ptr::reset). - void Reset(const scoped_refptr<SettingsStorageFactory>& delegate); - - // SettingsStorageFactory implementation. - virtual ValueStore* Create(const FilePath& base_path, - const std::string& extension_id) OVERRIDE; - - private: - // SettingsStorageFactory is refcounted. - virtual ~ScopedSettingsStorageFactory(); - - scoped_refptr<SettingsStorageFactory> delegate_; -}; - -} // namespace settings_test_util - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SETTINGS_TEST_UTIL_H_ diff --git a/chrome/browser/extensions/settings/sync_or_local_value_store_cache.cc b/chrome/browser/extensions/settings/sync_or_local_value_store_cache.cc deleted file mode 100644 index e3d951f..0000000 --- a/chrome/browser/extensions/settings/sync_or_local_value_store_cache.cc +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/sync_or_local_value_store_cache.h" - -#include "base/bind.h" -#include "base/callback.h" -#include "base/file_path.h" -#include "base/sequenced_task_runner.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/settings/settings_backend.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" -#include "chrome/browser/extensions/settings/settings_storage_quota_enforcer.h" -#include "chrome/browser/extensions/settings/weak_unlimited_settings_storage.h" -#include "chrome/common/extensions/extension.h" -#include "chrome/common/extensions/permissions/api_permission.h" -#include "content/public/browser/browser_thread.h" - -using content::BrowserThread; - -namespace extensions { - -SyncOrLocalValueStoreCache::SyncOrLocalValueStoreCache( - settings_namespace::Namespace settings_namespace, - const scoped_refptr<SettingsStorageFactory>& factory, - const SettingsStorageQuotaEnforcer::Limits& quota, - const scoped_refptr<SettingsObserverList>& observers, - const FilePath& profile_path) - : settings_namespace_(settings_namespace) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - DCHECK(settings_namespace_ == settings_namespace::LOCAL || - settings_namespace_ == settings_namespace::SYNC); - - // This post is safe since the destructor can only be invoked from the - // same message loop, and any potential post of a deletion task must come - // after the constructor returns. - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - base::Bind(&SyncOrLocalValueStoreCache::InitOnFileThread, - base::Unretained(this), - factory, quota, observers, profile_path)); -} - -SyncOrLocalValueStoreCache::~SyncOrLocalValueStoreCache() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); -} - -SettingsBackend* SyncOrLocalValueStoreCache::GetAppBackend() const { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(app_backend_.get()); - return app_backend_.get(); -} - -SettingsBackend* SyncOrLocalValueStoreCache::GetExtensionBackend() const { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(extension_backend_.get()); - return extension_backend_.get(); -} - -void SyncOrLocalValueStoreCache::RunWithValueStoreForExtension( - const StorageCallback& callback, - scoped_refptr<const Extension> extension) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(app_backend_.get()); - DCHECK(extension_backend_.get()); - SettingsBackend* backend = - extension->is_app() ? app_backend_.get() : extension_backend_.get(); - ValueStore* storage = backend->GetStorage(extension->id()); - - // A neat way to implement unlimited storage; if the extension has the - // unlimited storage permission, force through all calls to Set() (in the - // same way that writes from sync ignore quota). - // But only if it's local storage (bad stuff would happen if sync'ed - // storage is allowed to be unlimited). - bool is_unlimited = - settings_namespace_ == settings_namespace::LOCAL && - extension->HasAPIPermission(APIPermission::kUnlimitedStorage); - - if (is_unlimited) { - WeakUnlimitedSettingsStorage unlimited_storage(storage); - callback.Run(&unlimited_storage); - } else { - callback.Run(storage); - } -} - -void SyncOrLocalValueStoreCache::DeleteStorageSoon( - const std::string& extension_id) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - app_backend_->DeleteStorage(extension_id); - extension_backend_->DeleteStorage(extension_id); -} - -void SyncOrLocalValueStoreCache::InitOnFileThread( - const scoped_refptr<SettingsStorageFactory>& factory, - const SettingsStorageQuotaEnforcer::Limits& quota, - const scoped_refptr<SettingsObserverList>& observers, - const FilePath& profile_path) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(!app_backend_.get()); - DCHECK(!extension_backend_.get()); - const bool local = settings_namespace_ == settings_namespace::LOCAL; - const FilePath app_path = profile_path.AppendASCII( - local ? ExtensionService::kLocalAppSettingsDirectoryName - : ExtensionService::kSyncAppSettingsDirectoryName); - const FilePath extension_path = profile_path.AppendASCII( - local ? ExtensionService::kLocalExtensionSettingsDirectoryName - : ExtensionService::kSyncExtensionSettingsDirectoryName); - app_backend_.reset(new SettingsBackend(factory, app_path, quota, observers)); - extension_backend_.reset( - new SettingsBackend(factory, extension_path, quota, observers)); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/sync_or_local_value_store_cache.h b/chrome/browser/extensions/settings/sync_or_local_value_store_cache.h deleted file mode 100644 index 05cd59e..0000000 --- a/chrome/browser/extensions/settings/sync_or_local_value_store_cache.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SYNC_OR_LOCAL_VALUE_STORE_CACHE_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SYNC_OR_LOCAL_VALUE_STORE_CACHE_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/extensions/settings/settings_observer.h" -#include "chrome/browser/extensions/settings/settings_storage_quota_enforcer.h" -#include "chrome/browser/extensions/settings/value_store_cache.h" - -class FilePath; - -namespace extensions { - -class SettingsBackend; -class SettingsStorageFactory; - -// ValueStoreCache for the LOCAL and SYNC namespaces. It owns a backend for -// apps and another for extensions. Each backend takes care of persistence and -// syncing. -class SyncOrLocalValueStoreCache : public ValueStoreCache { - public: - SyncOrLocalValueStoreCache( - settings_namespace::Namespace settings_namespace, - const scoped_refptr<SettingsStorageFactory>& factory, - const SettingsStorageQuotaEnforcer::Limits& quota, - const scoped_refptr<SettingsObserverList>& observers, - const FilePath& profile_path); - virtual ~SyncOrLocalValueStoreCache(); - - SettingsBackend* GetAppBackend() const; - SettingsBackend* GetExtensionBackend() const; - - // ValueStoreCache implementation: - - virtual void RunWithValueStoreForExtension( - const StorageCallback& callback, - scoped_refptr<const Extension> extension) OVERRIDE; - - virtual void DeleteStorageSoon(const std::string& extension_id) OVERRIDE; - - private: - void InitOnFileThread(const scoped_refptr<SettingsStorageFactory>& factory, - const SettingsStorageQuotaEnforcer::Limits& quota, - const scoped_refptr<SettingsObserverList>& observers, - const FilePath& profile_path); - - settings_namespace::Namespace settings_namespace_; - scoped_ptr<SettingsBackend> app_backend_; - scoped_ptr<SettingsBackend> extension_backend_; - - DISALLOW_COPY_AND_ASSIGN(SyncOrLocalValueStoreCache); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SYNC_OR_LOCAL_VALUE_STORE_CACHE_H_ diff --git a/chrome/browser/extensions/settings/syncable_settings_storage.cc b/chrome/browser/extensions/settings/syncable_settings_storage.cc deleted file mode 100644 index c4edd9c..0000000 --- a/chrome/browser/extensions/settings/syncable_settings_storage.cc +++ /dev/null @@ -1,384 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/syncable_settings_storage.h" - -#include "chrome/browser/extensions/settings/settings_namespace.h" -#include "chrome/browser/extensions/settings/settings_sync_processor.h" -#include "chrome/browser/extensions/settings/settings_sync_util.h" -#include "content/public/browser/browser_thread.h" -#include "sync/api/sync_data.h" -#include "sync/protocol/extension_setting_specifics.pb.h" - -namespace extensions { - -using content::BrowserThread; - -SyncableSettingsStorage::SyncableSettingsStorage( - const scoped_refptr<ObserverListThreadSafe<SettingsObserver> >& - observers, - const std::string& extension_id, - ValueStore* delegate) - : observers_(observers), - extension_id_(extension_id), - delegate_(delegate) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); -} - -SyncableSettingsStorage::~SyncableSettingsStorage() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); -} - -size_t SyncableSettingsStorage::GetBytesInUse(const std::string& key) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - return delegate_->GetBytesInUse(key); -} - -size_t SyncableSettingsStorage::GetBytesInUse( - const std::vector<std::string>& keys) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - return delegate_->GetBytesInUse(keys); -} - -size_t SyncableSettingsStorage::GetBytesInUse() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - return delegate_->GetBytesInUse(); -} - -ValueStore::ReadResult SyncableSettingsStorage::Get( - const std::string& key) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - return delegate_->Get(key); -} - -ValueStore::ReadResult SyncableSettingsStorage::Get( - const std::vector<std::string>& keys) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - return delegate_->Get(keys); -} - -ValueStore::ReadResult SyncableSettingsStorage::Get() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - return delegate_->Get(); -} - -ValueStore::WriteResult SyncableSettingsStorage::Set( - WriteOptions options, const std::string& key, const Value& value) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - WriteResult result = delegate_->Set(options, key, value); - if (result->HasError()) { - return result.Pass(); - } - SyncResultIfEnabled(result); - return result.Pass(); -} - -ValueStore::WriteResult SyncableSettingsStorage::Set( - WriteOptions options, const DictionaryValue& values) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - WriteResult result = delegate_->Set(options, values); - if (result->HasError()) { - return result.Pass(); - } - SyncResultIfEnabled(result); - return result.Pass(); -} - -ValueStore::WriteResult SyncableSettingsStorage::Remove( - const std::string& key) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - WriteResult result = delegate_->Remove(key); - if (result->HasError()) { - return result.Pass(); - } - SyncResultIfEnabled(result); - return result.Pass(); -} - -ValueStore::WriteResult SyncableSettingsStorage::Remove( - const std::vector<std::string>& keys) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - WriteResult result = delegate_->Remove(keys); - if (result->HasError()) { - return result.Pass(); - } - SyncResultIfEnabled(result); - return result.Pass(); -} - -ValueStore::WriteResult SyncableSettingsStorage::Clear() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - WriteResult result = delegate_->Clear(); - if (result->HasError()) { - return result.Pass(); - } - SyncResultIfEnabled(result); - return result.Pass(); -} - -void SyncableSettingsStorage::SyncResultIfEnabled( - const ValueStore::WriteResult& result) { - if (sync_processor_.get() && !result->changes().empty()) { - syncer::SyncError error = sync_processor_->SendChanges(result->changes()); - if (error.IsSet()) - StopSyncing(); - } -} - -// Sync-related methods. - -syncer::SyncError SyncableSettingsStorage::StartSyncing( - const DictionaryValue& sync_state, - scoped_ptr<SettingsSyncProcessor> sync_processor) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(!sync_processor_.get()); - - sync_processor_ = sync_processor.Pass(); - sync_processor_->Init(sync_state); - - ReadResult maybe_settings = delegate_->Get(); - if (maybe_settings->HasError()) { - return syncer::SyncError( - FROM_HERE, - std::string("Failed to get settings: ") + maybe_settings->error(), - sync_processor_->type()); - } - - const DictionaryValue& settings = *maybe_settings->settings().get(); - if (sync_state.empty()) - return SendLocalSettingsToSync(settings); - else - return OverwriteLocalSettingsWithSync(sync_state, settings); -} - -syncer::SyncError SyncableSettingsStorage::SendLocalSettingsToSync( - const DictionaryValue& settings) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - - ValueStoreChangeList changes; - for (DictionaryValue::Iterator i(settings); i.HasNext(); i.Advance()) { - changes.push_back(ValueStoreChange(i.key(), NULL, i.value().DeepCopy())); - } - - if (changes.empty()) - return syncer::SyncError(); - - syncer::SyncError error = sync_processor_->SendChanges(changes); - if (error.IsSet()) - StopSyncing(); - - return error; -} - -syncer::SyncError SyncableSettingsStorage::OverwriteLocalSettingsWithSync( - const DictionaryValue& sync_state, const DictionaryValue& settings) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - // Treat this as a list of changes to sync and use ProcessSyncChanges. - // This gives notifications etc for free. - scoped_ptr<DictionaryValue> new_sync_state(sync_state.DeepCopy()); - - SettingSyncDataList changes; - for (DictionaryValue::Iterator it(settings); it.HasNext(); it.Advance()) { - Value* orphaned_sync_value = NULL; - if (new_sync_state->RemoveWithoutPathExpansion( - it.key(), &orphaned_sync_value)) { - scoped_ptr<Value> sync_value(orphaned_sync_value); - if (sync_value->Equals(&it.value())) { - // Sync and local values are the same, no changes to send. - } else { - // Sync value is different, update local setting with new value. - changes.push_back( - SettingSyncData( - syncer::SyncChange::ACTION_UPDATE, - extension_id_, - it.key(), - sync_value.Pass())); - } - } else { - // Not synced, delete local setting. - changes.push_back( - SettingSyncData( - syncer::SyncChange::ACTION_DELETE, - extension_id_, - it.key(), - scoped_ptr<Value>(new DictionaryValue()))); - } - } - - // Add all new settings to local settings. - while (!new_sync_state->empty()) { - std::string key = *new_sync_state->begin_keys(); - Value* value = NULL; - CHECK(new_sync_state->RemoveWithoutPathExpansion(key, &value)); - changes.push_back( - SettingSyncData( - syncer::SyncChange::ACTION_ADD, - extension_id_, - key, - scoped_ptr<Value>(value))); - } - - if (changes.empty()) - return syncer::SyncError(); - - return ProcessSyncChanges(changes); -} - -void SyncableSettingsStorage::StopSyncing() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - sync_processor_.reset(); -} - -syncer::SyncError SyncableSettingsStorage::ProcessSyncChanges( - const SettingSyncDataList& sync_changes) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - DCHECK(!sync_changes.empty()) << "No sync changes for " << extension_id_; - - if (!sync_processor_.get()) { - return syncer::SyncError( - FROM_HERE, - std::string("Sync is inactive for ") + extension_id_, - syncer::UNSPECIFIED); - } - - std::vector<syncer::SyncError> errors; - ValueStoreChangeList changes; - - for (SettingSyncDataList::const_iterator it = sync_changes.begin(); - it != sync_changes.end(); ++it) { - DCHECK_EQ(extension_id_, it->extension_id()); - - const std::string& key = it->key(); - const Value& value = it->value(); - - scoped_ptr<Value> current_value; - { - ReadResult maybe_settings = Get(it->key()); - if (maybe_settings->HasError()) { - errors.push_back(syncer::SyncError( - FROM_HERE, - std::string("Error getting current sync state for ") + - extension_id_ + "/" + key + ": " + maybe_settings->error(), - sync_processor_->type())); - continue; - } - Value* value = NULL; - if (maybe_settings->settings()->GetWithoutPathExpansion(key, &value)) { - current_value.reset(value->DeepCopy()); - } - } - - syncer::SyncError error; - - switch (it->change_type()) { - case syncer::SyncChange::ACTION_ADD: - if (!current_value.get()) { - error = OnSyncAdd(key, value.DeepCopy(), &changes); - } else { - // Already a value; hopefully a local change has beaten sync in a - // race and it's not a bug, so pretend it's an update. - LOG(WARNING) << "Got add from sync for existing setting " << - extension_id_ << "/" << key; - error = OnSyncUpdate( - key, current_value.release(), value.DeepCopy(), &changes); - } - break; - - case syncer::SyncChange::ACTION_UPDATE: - if (current_value.get()) { - error = OnSyncUpdate( - key, current_value.release(), value.DeepCopy(), &changes); - } else { - // Similarly, pretend it's an add. - LOG(WARNING) << "Got update from sync for nonexistent setting" << - extension_id_ << "/" << key; - error = OnSyncAdd(key, value.DeepCopy(), &changes); - } - break; - - case syncer::SyncChange::ACTION_DELETE: - if (current_value.get()) { - error = OnSyncDelete(key, current_value.release(), &changes); - } else { - // Similarly, ignore it. - LOG(WARNING) << "Got delete from sync for nonexistent setting " << - extension_id_ << "/" << key; - } - break; - - default: - NOTREACHED(); - } - - if (error.IsSet()) { - errors.push_back(error); - } - } - - sync_processor_->NotifyChanges(changes); - - observers_->Notify( - &SettingsObserver::OnSettingsChanged, - extension_id_, - settings_namespace::SYNC, - ValueStoreChange::ToJson(changes)); - - // TODO(kalman): Something sensible with multiple errors. - return errors.empty() ? syncer::SyncError() : errors[0]; -} - -syncer::SyncError SyncableSettingsStorage::OnSyncAdd( - const std::string& key, - Value* new_value, - ValueStoreChangeList* changes) { - DCHECK(new_value); - WriteResult result = delegate_->Set(IGNORE_QUOTA, key, *new_value); - if (result->HasError()) { - return syncer::SyncError( - FROM_HERE, - std::string("Error pushing sync add to local settings: ") + - result->error(), - sync_processor_->type()); - } - changes->push_back(ValueStoreChange(key, NULL, new_value)); - return syncer::SyncError(); -} - -syncer::SyncError SyncableSettingsStorage::OnSyncUpdate( - const std::string& key, - Value* old_value, - Value* new_value, - ValueStoreChangeList* changes) { - DCHECK(old_value); - DCHECK(new_value); - WriteResult result = delegate_->Set(IGNORE_QUOTA, key, *new_value); - if (result->HasError()) { - return syncer::SyncError( - FROM_HERE, - std::string("Error pushing sync update to local settings: ") + - result->error(), - sync_processor_->type()); - } - changes->push_back(ValueStoreChange(key, old_value, new_value)); - return syncer::SyncError(); -} - -syncer::SyncError SyncableSettingsStorage::OnSyncDelete( - const std::string& key, - Value* old_value, - ValueStoreChangeList* changes) { - DCHECK(old_value); - WriteResult result = delegate_->Remove(key); - if (result->HasError()) { - return syncer::SyncError( - FROM_HERE, - std::string("Error pushing sync remove to local settings: ") + - result->error(), - sync_processor_->type()); - } - changes->push_back(ValueStoreChange(key, old_value, NULL)); - return syncer::SyncError(); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/syncable_settings_storage.h b/chrome/browser/extensions/settings/syncable_settings_storage.h deleted file mode 100644 index 993a226..0000000 --- a/chrome/browser/extensions/settings/syncable_settings_storage.h +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_SYNCABLE_SETTINGS_STORAGE_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_SYNCABLE_SETTINGS_STORAGE_H_ - -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list_threadsafe.h" -#include "base/values.h" -#include "chrome/browser/extensions/settings/setting_sync_data.h" -#include "chrome/browser/extensions/settings/settings_observer.h" -#include "chrome/browser/value_store/value_store.h" -#include "sync/api/sync_change.h" -#include "sync/api/syncable_service.h" - -namespace extensions { - -class SettingsSyncProcessor; - -// Decorates a ValueStore with sync behaviour. -class SyncableSettingsStorage : public ValueStore { - public: - SyncableSettingsStorage( - const scoped_refptr<SettingsObserverList>& observers, - const std::string& extension_id, - // Ownership taken. - ValueStore* delegate); - - virtual ~SyncableSettingsStorage(); - - // ValueStore implementation. - virtual size_t GetBytesInUse(const std::string& key) OVERRIDE; - virtual size_t GetBytesInUse(const std::vector<std::string>& keys) OVERRIDE; - virtual size_t GetBytesInUse() OVERRIDE; - virtual ReadResult Get(const std::string& key) OVERRIDE; - virtual ReadResult Get(const std::vector<std::string>& keys) OVERRIDE; - virtual ReadResult Get() OVERRIDE; - virtual WriteResult Set( - WriteOptions options, - const std::string& key, - const Value& value) OVERRIDE; - virtual WriteResult Set( - WriteOptions options, const DictionaryValue& values) OVERRIDE; - virtual WriteResult Remove(const std::string& key) OVERRIDE; - virtual WriteResult Remove(const std::vector<std::string>& keys) OVERRIDE; - virtual WriteResult Clear() OVERRIDE; - - // Sync-related methods, analogous to those on SyncableService (handled by - // ExtensionSettings), but with looser guarantees about when the methods - // can be called. - - // Must only be called if sync isn't already active. - syncer::SyncError StartSyncing( - const DictionaryValue& sync_state, - scoped_ptr<SettingsSyncProcessor> sync_processor); - - // May be called at any time (idempotent). - void StopSyncing(); - - // May be called at any time; changes will be ignored if sync isn't active. - syncer::SyncError ProcessSyncChanges(const SettingSyncDataList& sync_changes); - - private: - // Sends the changes from |result| to sync if it's enabled. - void SyncResultIfEnabled(const ValueStore::WriteResult& result); - - // Sends all local settings to sync (synced settings assumed to be empty). - syncer::SyncError SendLocalSettingsToSync( - const DictionaryValue& settings); - - // Overwrites local state with sync state. - syncer::SyncError OverwriteLocalSettingsWithSync( - const DictionaryValue& sync_state, const DictionaryValue& settings); - - // Called when an Add/Update/Remove comes from sync. Ownership of Value*s - // are taken. - syncer::SyncError OnSyncAdd( - const std::string& key, - Value* new_value, - ValueStoreChangeList* changes); - syncer::SyncError OnSyncUpdate( - const std::string& key, - Value* old_value, - Value* new_value, - ValueStoreChangeList* changes); - syncer::SyncError OnSyncDelete( - const std::string& key, - Value* old_value, - ValueStoreChangeList* changes); - - // List of observers to settings changes. - const scoped_refptr<SettingsObserverList> observers_; - - // Id of the extension these settings are for. - std::string const extension_id_; - - // Storage area to sync. - const scoped_ptr<ValueStore> delegate_; - - // Object which sends changes to sync. - scoped_ptr<SettingsSyncProcessor> sync_processor_; - - DISALLOW_COPY_AND_ASSIGN(SyncableSettingsStorage); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_SYNCABLE_SETTINGS_STORAGE_H_ diff --git a/chrome/browser/extensions/settings/value_store_cache.cc b/chrome/browser/extensions/settings/value_store_cache.cc deleted file mode 100644 index 4d3fd70..0000000 --- a/chrome/browser/extensions/settings/value_store_cache.cc +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/value_store_cache.h" - -namespace extensions { - -ValueStoreCache::~ValueStoreCache() {} - -void ValueStoreCache::ShutdownOnUI() {} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/value_store_cache.h b/chrome/browser/extensions/settings/value_store_cache.h deleted file mode 100644 index b3322f8..0000000 --- a/chrome/browser/extensions/settings/value_store_cache.h +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_VALUE_STORE_CACHE_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_VALUE_STORE_CACHE_H_ - -#include <string> - -#include "base/callback.h" -#include "base/memory/ref_counted.h" - -class ValueStore; - -namespace extensions { - -class Extension; - -// Each namespace of the storage API implements this interface. -// Instances are created on the UI thread, but from then on live on the FILE -// thread. At shutdown, ShutdownOnUI() is first invoked on the UI thread, and -// the destructor is invoked soon after on the FILE thread. This gives -// implementations the chance to work with ValueStores on FILE but observe -// events on UI. -// It also means that any methods invoked on UI *before ShutdownOnUI()* can -// safely post other methods to the FILE thread, since the deletion task is only -// posted to FILE after ShutdownOnUI(). -class ValueStoreCache { - public: - typedef base::Callback<void(ValueStore*)> StorageCallback; - - // Invoked on FILE. - virtual ~ValueStoreCache(); - - // This is invoked from the UI thread during destruction of the Profile that - // ultimately owns this object. Any Profile-related cleanups should be - // performed in this method, since the destructor will execute later, after - // the Profile is already gone. - virtual void ShutdownOnUI(); - - // Requests the cache to invoke |callback| with the appropriate ValueStore - // for the given |extension|. |callback| should be invoked with a NULL - // ValueStore in case of errors. - // |extension| is passed in a scoped_refptr<> because this method is - // asynchronously posted as a task to the loop returned by GetMessageLoop(), - // and this guarantees the Extension is still valid when the method executes. - virtual void RunWithValueStoreForExtension( - const StorageCallback& callback, - scoped_refptr<const Extension> extension) = 0; - - // Requests the cache to delete any storage used by |extension_id|. - virtual void DeleteStorageSoon(const std::string& extension_id) = 0; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_VALUE_STORE_CACHE_H_ diff --git a/chrome/browser/extensions/settings/weak_unlimited_settings_storage.cc b/chrome/browser/extensions/settings/weak_unlimited_settings_storage.cc deleted file mode 100644 index 7afbc2c..0000000 --- a/chrome/browser/extensions/settings/weak_unlimited_settings_storage.cc +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2012 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/extensions/settings/weak_unlimited_settings_storage.h" - -namespace extensions { - -WeakUnlimitedSettingsStorage::WeakUnlimitedSettingsStorage( - ValueStore* delegate) - : delegate_(delegate) {} - -WeakUnlimitedSettingsStorage::~WeakUnlimitedSettingsStorage() {} - -size_t WeakUnlimitedSettingsStorage::GetBytesInUse(const std::string& key) { - return delegate_->GetBytesInUse(key); -} - -size_t WeakUnlimitedSettingsStorage::GetBytesInUse( - const std::vector<std::string>& keys) { - return delegate_->GetBytesInUse(keys); -} - - -size_t WeakUnlimitedSettingsStorage::GetBytesInUse() { - return delegate_->GetBytesInUse(); -} - -ValueStore::ReadResult WeakUnlimitedSettingsStorage::Get( - const std::string& key) { - return delegate_->Get(key); -} - -ValueStore::ReadResult WeakUnlimitedSettingsStorage::Get( - const std::vector<std::string>& keys) { - return delegate_->Get(keys); -} - -ValueStore::ReadResult WeakUnlimitedSettingsStorage::Get() { - return delegate_->Get(); -} - -ValueStore::WriteResult WeakUnlimitedSettingsStorage::Set( - WriteOptions options, const std::string& key, const Value& value) { - return delegate_->Set(IGNORE_QUOTA, key, value); -} - -ValueStore::WriteResult WeakUnlimitedSettingsStorage::Set( - WriteOptions options, const DictionaryValue& values) { - return delegate_->Set(IGNORE_QUOTA, values); -} - -ValueStore::WriteResult WeakUnlimitedSettingsStorage::Remove( - const std::string& key) { - return delegate_->Remove(key); -} - -ValueStore::WriteResult WeakUnlimitedSettingsStorage::Remove( - const std::vector<std::string>& keys) { - return delegate_->Remove(keys); -} - -ValueStore::WriteResult WeakUnlimitedSettingsStorage::Clear() { - return delegate_->Clear(); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/settings/weak_unlimited_settings_storage.h b/chrome/browser/extensions/settings/weak_unlimited_settings_storage.h deleted file mode 100644 index c9e6014..0000000 --- a/chrome/browser/extensions/settings/weak_unlimited_settings_storage.h +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_EXTENSIONS_SETTINGS_WEAK_UNLIMITED_SETTINGS_STORAGE_H_ -#define CHROME_BROWSER_EXTENSIONS_SETTINGS_WEAK_UNLIMITED_SETTINGS_STORAGE_H_ - -#include "base/compiler_specific.h" -#include "chrome/browser/value_store/value_store.h" - -namespace extensions { - -// A ValueStore decorator which makes calls through |Set| ignore quota. -// "Weak" because ownership of the delegate isn't taken; this is designed to be -// temporarily attached to storage areas. -class WeakUnlimitedSettingsStorage : public ValueStore { - public: - // Ownership of |delegate| NOT taken. - explicit WeakUnlimitedSettingsStorage(ValueStore* delegate); - - virtual ~WeakUnlimitedSettingsStorage(); - - // ValueStore implementation. - virtual size_t GetBytesInUse(const std::string& key) OVERRIDE; - virtual size_t GetBytesInUse(const std::vector<std::string>& keys) OVERRIDE; - virtual size_t GetBytesInUse() OVERRIDE; - virtual ReadResult Get(const std::string& key) OVERRIDE; - virtual ReadResult Get(const std::vector<std::string>& keys) OVERRIDE; - virtual ReadResult Get() OVERRIDE; - virtual WriteResult Set( - WriteOptions options, - const std::string& key, - const Value& value) OVERRIDE; - virtual WriteResult Set( - WriteOptions options, const DictionaryValue& values) OVERRIDE; - virtual WriteResult Remove(const std::string& key) OVERRIDE; - virtual WriteResult Remove(const std::vector<std::string>& keys) OVERRIDE; - virtual WriteResult Clear() OVERRIDE; - - private: - // The delegate storage area, NOT OWNED. - ValueStore* const delegate_; - - DISALLOW_COPY_AND_ASSIGN(WeakUnlimitedSettingsStorage); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_SETTINGS_WEAK_UNLIMITED_SETTINGS_STORAGE_H_ diff --git a/chrome/browser/performance_monitor/performance_monitor.gyp b/chrome/browser/performance_monitor/performance_monitor.gyp index 08fe90e..e3587f4 100644 --- a/chrome/browser/performance_monitor/performance_monitor.gyp +++ b/chrome/browser/performance_monitor/performance_monitor.gyp @@ -8,14 +8,14 @@ 'target_name': 'performance_monitor', 'type': 'static_library', 'sources': [ - '<@(json_schema_files)', + '<@(schema_files)', ], 'includes': [ '../../../build/json_schema_compile.gypi', ], 'variables': { 'chromium_code': 1, - 'json_schema_files': [ + 'schema_files': [ 'events.json', ], 'cc_dir': 'chrome/browser/performance_monitor', diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index ff03982..c888a88 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc @@ -17,7 +17,7 @@ #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/extensions/api/commands/command_service.h" -#include "chrome/browser/extensions/api/tabs/tabs.h" +#include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_prefs.h" #include "chrome/browser/extensions/extension_web_ui.h" @@ -278,7 +278,7 @@ void RegisterUserPrefs(PrefServiceSyncable* user_prefs) { #endif #if !defined(OS_ANDROID) - CaptureVisibleTabFunction::RegisterUserPrefs(user_prefs); + TabsCaptureVisibleTabFunction::RegisterUserPrefs(user_prefs); ChromeToMobileService::RegisterUserPrefs(user_prefs); DevToolsWindow::RegisterUserPrefs(user_prefs); extensions::CommandService::RegisterUserPrefs(user_prefs); diff --git a/chrome/browser/sync/glue/chrome_extensions_activity_monitor.cc b/chrome/browser/sync/glue/chrome_extensions_activity_monitor.cc index 1c6d472..7518a83 100644 --- a/chrome/browser/sync/glue/chrome_extensions_activity_monitor.cc +++ b/chrome/browser/sync/glue/chrome_extensions_activity_monitor.cc @@ -5,7 +5,7 @@ #include "chrome/browser/sync/glue/chrome_extensions_activity_monitor.h" #include "base/bind.h" -#include "chrome/browser/extensions/api/bookmarks/bookmark_api.h" +#include "chrome/browser/extensions/api/bookmarks/bookmarks_api.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension.h" #include "content/public/browser/browser_thread.h" diff --git a/chrome/browser/sync/glue/chrome_extensions_activity_monitor_unittest.cc b/chrome/browser/sync/glue/chrome_extensions_activity_monitor_unittest.cc index f03e231..37ddfd6 100644 --- a/chrome/browser/sync/glue/chrome_extensions_activity_monitor_unittest.cc +++ b/chrome/browser/sync/glue/chrome_extensions_activity_monitor_unittest.cc @@ -8,7 +8,7 @@ #include "base/message_loop.h" #include "base/path_service.h" #include "base/values.h" -#include "chrome/browser/extensions/api/bookmarks/bookmark_api.h" +#include "chrome/browser/extensions/api/bookmarks/bookmarks_api.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" @@ -86,18 +86,20 @@ class SyncChromeExtensionsActivityMonitorTest : public testing::Test { // 2. Only the mutating events should be recorded by the // syncer::ExtensionsActivityMonitor. TEST_F(SyncChromeExtensionsActivityMonitorTest, Basic) { - FireBookmarksApiEvent<extensions::RemoveBookmarkFunction>(extension1_, 1); - FireBookmarksApiEvent<extensions::MoveBookmarkFunction>(extension1_, 1); - FireBookmarksApiEvent<extensions::UpdateBookmarkFunction>(extension1_, 2); - FireBookmarksApiEvent<extensions::CreateBookmarkFunction>(extension1_, 3); - FireBookmarksApiEvent<extensions::SearchBookmarksFunction>(extension1_, 5); + FireBookmarksApiEvent<extensions::BookmarksRemoveFunction>(extension1_, 1); + FireBookmarksApiEvent<extensions::BookmarksMoveFunction>(extension1_, 1); + FireBookmarksApiEvent<extensions::BookmarksUpdateFunction>(extension1_, 2); + FireBookmarksApiEvent<extensions::BookmarksCreateFunction>(extension1_, 3); + FireBookmarksApiEvent<extensions::BookmarksSearchFunction>(extension1_, 5); const uint32 writes_by_extension1 = 1 + 1 + 2 + 3; - FireBookmarksApiEvent<extensions::RemoveTreeBookmarkFunction>(extension2_, 8); - FireBookmarksApiEvent<extensions::GetBookmarkTreeFunction>(extension2_, 13); - FireBookmarksApiEvent<extensions::GetBookmarkChildrenFunction>( + FireBookmarksApiEvent<extensions::BookmarksRemoveTreeFunction>( + extension2_, 8); + FireBookmarksApiEvent<extensions::BookmarksGetSubTreeFunction>( + extension2_, 13); + FireBookmarksApiEvent<extensions::BookmarksGetChildrenFunction>( extension2_, 21); - FireBookmarksApiEvent<extensions::GetBookmarksFunction>(extension2_, 33); + FireBookmarksApiEvent<extensions::BookmarksGetTreeFunction>(extension2_, 33); const uint32 writes_by_extension2 = 8; syncer::ExtensionsActivityMonitor::Records results; @@ -115,8 +117,8 @@ TEST_F(SyncChromeExtensionsActivityMonitorTest, Basic) { // and put the old records back. Those should be merged with the new // records correctly. TEST_F(SyncChromeExtensionsActivityMonitorTest, Put) { - FireBookmarksApiEvent<extensions::CreateBookmarkFunction>(extension1_, 5); - FireBookmarksApiEvent<extensions::MoveBookmarkFunction>(extension2_, 8); + FireBookmarksApiEvent<extensions::BookmarksCreateFunction>(extension1_, 5); + FireBookmarksApiEvent<extensions::BookmarksMoveFunction>(extension2_, 8); syncer::ExtensionsActivityMonitor::Records results; monitor_.GetAndClearRecords(&results); @@ -125,8 +127,8 @@ TEST_F(SyncChromeExtensionsActivityMonitorTest, Put) { EXPECT_EQ(5U, results[id1_].bookmark_write_count); EXPECT_EQ(8U, results[id2_].bookmark_write_count); - FireBookmarksApiEvent<extensions::GetBookmarksFunction>(extension2_, 3); - FireBookmarksApiEvent<extensions::UpdateBookmarkFunction>(extension2_, 2); + FireBookmarksApiEvent<extensions::BookmarksGetTreeFunction>(extension2_, 3); + FireBookmarksApiEvent<extensions::BookmarksUpdateFunction>(extension2_, 2); // Simulate a commit failure, which augments the active record set with the // refugee records. @@ -145,7 +147,7 @@ TEST_F(SyncChromeExtensionsActivityMonitorTest, Put) { // times. The mintor should correctly clear its records every time // they're returned. TEST_F(SyncChromeExtensionsActivityMonitorTest, MultiGet) { - FireBookmarksApiEvent<extensions::CreateBookmarkFunction>(extension1_, 5); + FireBookmarksApiEvent<extensions::BookmarksCreateFunction>(extension1_, 5); syncer::ExtensionsActivityMonitor::Records results; monitor_.GetAndClearRecords(&results); @@ -156,7 +158,7 @@ TEST_F(SyncChromeExtensionsActivityMonitorTest, MultiGet) { monitor_.GetAndClearRecords(&results); EXPECT_TRUE(results.empty()); - FireBookmarksApiEvent<extensions::CreateBookmarkFunction>(extension1_, 3); + FireBookmarksApiEvent<extensions::BookmarksCreateFunction>(extension1_, 3); monitor_.GetAndClearRecords(&results); EXPECT_EQ(1U, results.size()); diff --git a/chrome/browser/sync/profile_sync_components_factory_impl.cc b/chrome/browser/sync/profile_sync_components_factory_impl.cc index a9d9a52..acdefba 100644 --- a/chrome/browser/sync/profile_sync_components_factory_impl.cc +++ b/chrome/browser/sync/profile_sync_components_factory_impl.cc @@ -5,11 +5,11 @@ #include "base/command_line.h" #include "build/build_config.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" +#include "chrome/browser/extensions/api/storage/settings_frontend.h" #include "chrome/browser/extensions/app_notification_manager.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/extensions/extension_system_factory.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" #include "chrome/browser/history/history.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/prefs/pref_model_associator.h" @@ -46,8 +46,8 @@ #include "chrome/browser/sync/glue/ui_data_type_controller.h" #include "chrome/browser/sync/profile_sync_components_factory_impl.h" #include "chrome/browser/sync/profile_sync_service.h" -#include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/themes/theme_service.h" +#include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/themes/theme_syncable_service.h" #include "chrome/browser/webdata/autocomplete_syncable_service.h" #include "chrome/browser/webdata/autofill_profile_syncable_service.h" diff --git a/chrome/browser/sync/test/integration/extension_settings_helper.cc b/chrome/browser/sync/test/integration/extension_settings_helper.cc index 5c42b95..be57a4a 100644 --- a/chrome/browser/sync/test/integration/extension_settings_helper.cc +++ b/chrome/browser/sync/test/integration/extension_settings_helper.cc @@ -6,12 +6,12 @@ #include "base/bind.h" #include "base/json/json_writer.h" -#include "base/memory/scoped_ptr.h" #include "base/logging.h" +#include "base/memory/scoped_ptr.h" #include "base/synchronization/waitable_event.h" #include "base/values.h" +#include "chrome/browser/extensions/api/storage/settings_frontend.h" #include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/settings/settings_frontend.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/test/integration/extensions_helper.h" #include "chrome/browser/sync/test/integration/sync_datatype_helper.h" diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm index 97894ed..ebdaa95 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm @@ -17,7 +17,7 @@ #include "chrome/browser/command_updater.h" #include "chrome/browser/defaults.h" #include "chrome/browser/extensions/api/omnibox/omnibox_api.h" -#include "chrome/browser/extensions/api/tabs/tabs.h" +#include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/extension_action.h" #include "chrome/browser/extensions/location_bar_controller.h" #include "chrome/browser/extensions/tab_helper.h" diff --git a/chrome/chrome_browser_extensions.gypi b/chrome/chrome_browser_extensions.gypi index 97b6e33..1765329 100644 --- a/chrome/chrome_browser_extensions.gypi +++ b/chrome/chrome_browser_extensions.gypi @@ -97,14 +97,14 @@ 'browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h', 'browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api_constants.cc', 'browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api_constants.h', - 'browser/extensions/api/bookmarks/bookmark_api.cc', - 'browser/extensions/api/bookmarks/bookmark_api.h', 'browser/extensions/api/bookmarks/bookmark_api_constants.cc', 'browser/extensions/api/bookmarks/bookmark_api_constants.h', 'browser/extensions/api/bookmarks/bookmark_api_factory.cc', 'browser/extensions/api/bookmarks/bookmark_api_factory.h', 'browser/extensions/api/bookmarks/bookmark_api_helpers.cc', 'browser/extensions/api/bookmarks/bookmark_api_helpers.h', + 'browser/extensions/api/bookmarks/bookmarks_api.cc', + 'browser/extensions/api/bookmarks/bookmarks_api.h', 'browser/extensions/api/browsing_data/browsing_data_api.cc', 'browser/extensions/api/browsing_data/browsing_data_api.h', 'browser/extensions/api/cloud_print_private/cloud_print_private_api.cc', @@ -123,8 +123,8 @@ 'browser/extensions/api/content_settings/content_settings_store.h', 'browser/extensions/api/commands/commands.cc', 'browser/extensions/api/commands/commands.h', - 'browser/extensions/api/context_menu/context_menu_api.cc', - 'browser/extensions/api/context_menu/context_menu_api.h', + 'browser/extensions/api/context_menus/context_menus_api.cc', + 'browser/extensions/api/context_menus/context_menus_api.h', 'browser/extensions/api/cookies/cookies_api.cc', 'browser/extensions/api/cookies/cookies_api.h', 'browser/extensions/api/cookies/cookies_api_constants.cc', @@ -324,6 +324,38 @@ 'browser/extensions/api/socket/tcp_socket.h', 'browser/extensions/api/socket/udp_socket.cc', 'browser/extensions/api/socket/udp_socket.h', + 'browser/extensions/api/storage/leveldb_settings_storage_factory.cc', + 'browser/extensions/api/storage/leveldb_settings_storage_factory.h', + 'browser/extensions/api/storage/managed_value_store_cache.cc', + 'browser/extensions/api/storage/managed_value_store_cache.h', + 'browser/extensions/api/storage/policy_value_store.cc', + 'browser/extensions/api/storage/policy_value_store.h', + 'browser/extensions/api/storage/setting_sync_data.cc', + 'browser/extensions/api/storage/setting_sync_data.h', + 'browser/extensions/api/storage/settings_backend.cc', + 'browser/extensions/api/storage/settings_backend.h', + 'browser/extensions/api/storage/settings_frontend.cc', + 'browser/extensions/api/storage/settings_frontend.h', + 'browser/extensions/api/storage/settings_namespace.cc', + 'browser/extensions/api/storage/settings_namespace.h', + 'browser/extensions/api/storage/settings_observer.h', + 'browser/extensions/api/storage/settings_storage_factory.h', + 'browser/extensions/api/storage/settings_storage_quota_enforcer.cc', + 'browser/extensions/api/storage/settings_storage_quota_enforcer.h', + 'browser/extensions/api/storage/settings_sync_processor.cc', + 'browser/extensions/api/storage/settings_sync_processor.h', + 'browser/extensions/api/storage/settings_sync_util.cc', + 'browser/extensions/api/storage/settings_sync_util.h', + 'browser/extensions/api/storage/storage_api.cc', + 'browser/extensions/api/storage/storage_api.h', + 'browser/extensions/api/storage/sync_or_local_value_store_cache.cc', + 'browser/extensions/api/storage/sync_or_local_value_store_cache.h', + 'browser/extensions/api/storage/syncable_settings_storage.cc', + 'browser/extensions/api/storage/syncable_settings_storage.h', + 'browser/extensions/api/storage/value_store_cache.cc', + 'browser/extensions/api/storage/value_store_cache.h', + 'browser/extensions/api/storage/weak_unlimited_settings_storage.cc', + 'browser/extensions/api/storage/weak_unlimited_settings_storage.h', 'browser/extensions/api/sync_file_system/extension_sync_event_observer_factory.cc', 'browser/extensions/api/sync_file_system/extension_sync_event_observer_factory.h', 'browser/extensions/api/sync_file_system/extension_sync_event_observer.cc', @@ -367,10 +399,8 @@ 'browser/extensions/api/tab_capture/tab_capture_registry.h', 'browser/extensions/api/tab_capture/tab_capture_registry_factory.cc', 'browser/extensions/api/tab_capture/tab_capture_registry_factory.h', - 'browser/extensions/api/tabs/execute_code_in_tab_function.cc', - 'browser/extensions/api/tabs/execute_code_in_tab_function.h', - 'browser/extensions/api/tabs/tabs.cc', - 'browser/extensions/api/tabs/tabs.h', + 'browser/extensions/api/tabs/tabs_api.cc', + 'browser/extensions/api/tabs/tabs_api.h', 'browser/extensions/api/tabs/tabs_windows_api.cc', 'browser/extensions/api/tabs/tabs_windows_api.h', 'browser/extensions/api/tabs/tabs_constants.cc', @@ -636,38 +666,6 @@ 'browser/extensions/script_bubble_controller.h', 'browser/extensions/script_executor.cc', 'browser/extensions/script_executor.h', - 'browser/extensions/settings/leveldb_settings_storage_factory.cc', - 'browser/extensions/settings/leveldb_settings_storage_factory.h', - 'browser/extensions/settings/managed_value_store_cache.cc', - 'browser/extensions/settings/managed_value_store_cache.h', - 'browser/extensions/settings/policy_value_store.cc', - 'browser/extensions/settings/policy_value_store.h', - 'browser/extensions/settings/setting_sync_data.cc', - 'browser/extensions/settings/setting_sync_data.h', - 'browser/extensions/settings/settings_api.cc', - 'browser/extensions/settings/settings_api.h', - 'browser/extensions/settings/settings_backend.cc', - 'browser/extensions/settings/settings_backend.h', - 'browser/extensions/settings/settings_frontend.cc', - 'browser/extensions/settings/settings_frontend.h', - 'browser/extensions/settings/settings_namespace.cc', - 'browser/extensions/settings/settings_namespace.h', - 'browser/extensions/settings/settings_observer.h', - 'browser/extensions/settings/settings_storage_factory.h', - 'browser/extensions/settings/settings_storage_quota_enforcer.cc', - 'browser/extensions/settings/settings_storage_quota_enforcer.h', - 'browser/extensions/settings/settings_sync_processor.cc', - 'browser/extensions/settings/settings_sync_processor.h', - 'browser/extensions/settings/settings_sync_util.cc', - 'browser/extensions/settings/settings_sync_util.h', - 'browser/extensions/settings/sync_or_local_value_store_cache.cc', - 'browser/extensions/settings/sync_or_local_value_store_cache.h', - 'browser/extensions/settings/syncable_settings_storage.cc', - 'browser/extensions/settings/syncable_settings_storage.h', - 'browser/extensions/settings/value_store_cache.cc', - 'browser/extensions/settings/value_store_cache.h', - 'browser/extensions/settings/weak_unlimited_settings_storage.cc', - 'browser/extensions/settings/weak_unlimited_settings_storage.h', 'browser/extensions/shell_window_geometry_cache.cc', 'browser/extensions/shell_window_geometry_cache.h', 'browser/extensions/shell_window_registry.cc', @@ -786,6 +784,7 @@ ['include', '^browser/extensions/api/proxy/proxy_api_constants.cc'], ['include', '^browser/extensions/api/push_messaging/push_messaging_api.cc'], ['include', '^browser/extensions/api/runtime/runtime_api.cc'], + ['include', '^browser/extensions/api/storage/.*\.cc'], ['include', '^browser/extensions/api/system_info_cpu/cpu_info_provider.cc'], ['include', '^browser/extensions/api/system_info_cpu/cpu_info_provider_android.cc'], ['include', '^browser/extensions/api/tabs/tabs_constants.cc'], @@ -832,10 +831,10 @@ ], }, { # configuration_policy==0 'sources!': [ - 'browser/extensions/settings/managed_value_store_cache.cc', - 'browser/extensions/settings/managed_value_store_cache.h', - 'browser/extensions/settings/policy_value_store.cc', - 'browser/extensions/settings/policy_value_store.h', + 'browser/extensions/api/storage/managed_value_store_cache.cc', + 'browser/extensions/api/storage/managed_value_store_cache.h', + 'browser/extensions/api/storage/policy_value_store.cc', + 'browser/extensions/api/storage/policy_value_store.h', ], }], ['OS=="win"', { diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi index ad69e62..7449b3e 100644 --- a/chrome/chrome_tests.gypi +++ b/chrome/chrome_tests.gypi @@ -969,7 +969,7 @@ 'browser/extensions/api/browsing_data/browsing_data_test.cc', 'browser/extensions/api/cloud_print_private/cloud_print_private_apitest.cc', 'browser/extensions/api/content_settings/content_settings_apitest.cc', - 'browser/extensions/api/context_menu/context_menu_apitest.cc', + 'browser/extensions/api/context_menus/context_menu_apitest.cc', 'browser/extensions/api/cookies/cookies_apitest.cc', 'browser/extensions/api/debugger/debugger_apitest.cc', 'browser/extensions/api/declarative/declarative_apitest.cc', @@ -1088,7 +1088,7 @@ 'browser/extensions/process_management_browsertest.cc', 'browser/extensions/requirements_checker_browsertest.cc', 'browser/extensions/sandboxed_pages_apitest.cc', - 'browser/extensions/settings/settings_apitest.cc', + 'browser/extensions/api/storage/settings_apitest.cc', 'browser/extensions/stubs_apitest.cc', 'browser/extensions/subscribe_page_action_browsertest.cc', 'browser/extensions/system/system_apitest.cc', diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi index 16a90bd..e0240b7 100644 --- a/chrome/chrome_tests_unit.gypi +++ b/chrome/chrome_tests_unit.gypi @@ -735,12 +735,12 @@ 'browser/extensions/sandboxed_unpacker_unittest.cc', 'browser/extensions/script_badge_controller_unittest.cc', 'browser/extensions/script_bubble_controller_unittest.cc', - 'browser/extensions/settings/policy_value_store_unittest.cc', - 'browser/extensions/settings/settings_frontend_unittest.cc', - 'browser/extensions/settings/settings_quota_unittest.cc', - 'browser/extensions/settings/settings_sync_unittest.cc', - 'browser/extensions/settings/settings_test_util.cc', - 'browser/extensions/settings/settings_test_util.h', + 'browser/extensions/api/storage/policy_value_store_unittest.cc', + 'browser/extensions/api/storage/settings_frontend_unittest.cc', + 'browser/extensions/api/storage/settings_quota_unittest.cc', + 'browser/extensions/api/storage/settings_sync_unittest.cc', + 'browser/extensions/api/storage/settings_test_util.cc', + 'browser/extensions/api/storage/settings_test_util.h', 'browser/extensions/shell_window_geometry_cache_unittest.cc', 'browser/extensions/standard_management_policy_provider_unittest.cc', 'browser/extensions/updater/extension_updater_unittest.cc', @@ -1788,7 +1788,7 @@ }], ['configuration_policy==0', { 'sources!': [ - 'browser/extensions/settings/policy_value_store_unittest.cc', + 'browser/extensions/api/storage/policy_value_store_unittest.cc', 'browser/managed_mode/managed_mode_url_filter_unittest.cc', 'browser/prefs/proxy_policy_unittest.cc', 'browser/ui/webui/policy_ui_unittest.cc', diff --git a/chrome/common/extensions/api/api.gyp b/chrome/common/extensions/api/api.gyp index 95af0dc..fce4407 100644 --- a/chrome/common/extensions/api/api.gyp +++ b/chrome/common/extensions/api/api.gyp @@ -8,8 +8,7 @@ 'target_name': 'api', 'type': 'static_library', 'sources': [ - '<@(idl_schema_files)', - '<@(json_schema_files)', + '<@(schema_files)', ], 'includes': [ '../../../../build/json_schema_bundle_compile.gypi', @@ -17,75 +16,71 @@ ], 'variables': { 'chromium_code': 1, - 'json_schema_files': [ - 'bookmarks.json', - 'cloud_print_private.json', - 'content_settings.json', - 'context_menus.json', - 'cookies.json', - 'debugger.json', - 'events.json', - 'experimental_history.json', - 'experimental_record.json', - 'file_browser_handler_internal.json', - 'i18n.json', - 'font_settings.json', - 'history.json', - 'management.json', - 'page_capture.json', - 'permissions.json', - 'storage.json', - 'tabs.json', - 'web_navigation.json', - 'web_request.json', - 'windows.json', - ], - 'idl_schema_files': [ + 'schema_files': [ 'alarms.idl', 'app_current_window_internal.idl', 'app_runtime.idl', 'app_window.idl', 'autotest_private.idl', 'bluetooth.idl', + 'bookmarks.json', + 'cloud_print_private.json', + 'content_settings.json', + 'context_menus.json', + 'cookies.json', + 'debugger.json', 'developer_private.idl', 'dial.idl', 'downloads.idl', + 'events.json', 'experimental_discovery.idl', 'experimental_dns.idl', + 'experimental_history.json', 'experimental_identity.idl', 'experimental_idltest.idl', 'experimental_media_galleries.idl', 'experimental_notification.idl', + 'experimental_record.json', 'experimental_system_info_cpu.idl', 'experimental_system_info_display.idl', 'experimental_system_info_memory.idl', 'experimental_system_info_storage.idl', + 'file_browser_handler_internal.json', 'file_system.idl', + 'font_settings.json', + 'history.json', + 'i18n.json', + 'management.json', 'media_galleries.idl', 'media_galleries_private.idl', + 'page_capture.json', + 'permissions.json', 'push_messaging.idl', 'rtc_private.idl', 'serial.idl', 'socket.idl', + 'storage.json', 'sync_file_system.idl', 'system_indicator.idl', 'tab_capture.idl', + 'tabs.json', 'usb.idl', + 'web_navigation.json', + 'web_request.json', + 'windows.json', ], 'cc_dir': 'chrome/common/extensions/api', 'root_namespace': 'extensions::api', }, 'conditions': [ ['OS=="android"', { - 'idl_schema_files!': [ + 'schema_files!': [ 'usb.idl', ], }], ['OS!="chromeos"', { - 'json_schema_files!': [ + 'schema_files!': [ 'file_browser_handler_internal.json', - ], - 'idl_schema_files!': [ 'rtc_private.idl', ], }], diff --git a/chrome/common/extensions/api/content_settings.json b/chrome/common/extensions/api/content_settings.json index 3c04bac..43643dd 100644 --- a/chrome/common/extensions/api/content_settings.json +++ b/chrome/common/extensions/api/content_settings.json @@ -5,6 +5,9 @@ [ { "namespace": "contentSettings", + "compiler_options": { + "generate_type_functions": true + }, "types": [ { "id": "ResourceIdentifier", diff --git a/chrome/common/extensions/api/events.json b/chrome/common/extensions/api/events.json index cacc8dc..b003fb6 100644 --- a/chrome/common/extensions/api/events.json +++ b/chrome/common/extensions/api/events.json @@ -5,6 +5,10 @@ [ { "namespace": "events", + "compiler_options": { + "implemented_in": "chrome/browser/extensions/api/declarative/declarative_api.h", + "generate_type_functions": true + }, "internal": true, "unprivileged": true, "types": [ diff --git a/chrome/common/extensions/api/extension_api.cc b/chrome/common/extensions/api/extension_api.cc index fc38a24..85207e7 100644 --- a/chrome/common/extensions/api/extension_api.cc +++ b/chrome/common/extensions/api/extension_api.cc @@ -344,8 +344,6 @@ void ExtensionAPI::InitDefaultConfiguration() { CHECK(unloaded_schemas_.empty()); RegisterSchema("app", ReadFromResource( IDR_EXTENSION_API_JSON_APP)); - RegisterSchema("bookmarks", ReadFromResource( - IDR_EXTENSION_API_JSON_BOOKMARKS)); RegisterSchema("bookmarkManagerPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_BOOKMARKMANAGERPRIVATE)); RegisterSchema("browserAction", ReadFromResource( @@ -354,30 +352,16 @@ void ExtensionAPI::InitDefaultConfiguration() { IDR_EXTENSION_API_JSON_BROWSINGDATA)); RegisterSchema("chromeosInfoPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_CHROMEOSINFOPRIVATE)); - RegisterSchema("cloudPrintPrivate", ReadFromResource( - IDR_EXTENSION_API_JSON_CLOUDPRINTPRIVATE)); RegisterSchema("commands", ReadFromResource( IDR_EXTENSION_API_JSON_COMMANDS)); - RegisterSchema("contentSettings", ReadFromResource( - IDR_EXTENSION_API_JSON_CONTENTSETTINGS)); - RegisterSchema("contextMenus", ReadFromResource( - IDR_EXTENSION_API_JSON_CONTEXTMENUS)); - RegisterSchema("cookies", ReadFromResource( - IDR_EXTENSION_API_JSON_COOKIES)); - RegisterSchema("debugger", ReadFromResource( - IDR_EXTENSION_API_JSON_DEBUGGER)); RegisterSchema("declarativeWebRequest", ReadFromResource( IDR_EXTENSION_API_JSON_DECLARATIVE_WEBREQUEST)); RegisterSchema("devtools", ReadFromResource( IDR_EXTENSION_API_JSON_DEVTOOLS)); - RegisterSchema("events", ReadFromResource( - IDR_EXTENSION_API_JSON_EVENTS)); RegisterSchema("experimental.accessibility", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_ACCESSIBILITY)); RegisterSchema("experimental.app", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_APP)); - RegisterSchema("experimental.history", ReadFromResource( - IDR_EXTENSION_API_JSON_EXPERIMENTAL_HISTORY)); RegisterSchema("experimental.infobars", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_INFOBARS)); RegisterSchema("experimental.input.virtualKeyboard", ReadFromResource( @@ -386,8 +370,6 @@ void ExtensionAPI::InitDefaultConfiguration() { IDR_EXTENSION_API_JSON_EXPERIMENTAL_POWER)); RegisterSchema("experimental.processes", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_PROCESSES)); - RegisterSchema("experimental.record", ReadFromResource( - IDR_EXTENSION_API_JSON_EXPERIMENTAL_RECORD)); RegisterSchema("experimental.rlz", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_RLZ)); RegisterSchema("runtime", ReadFromResource( @@ -398,16 +380,8 @@ void ExtensionAPI::InitDefaultConfiguration() { IDR_EXTENSION_API_JSON_EXTENSION)); RegisterSchema("fileBrowserHandler", ReadFromResource( IDR_EXTENSION_API_JSON_FILEBROWSERHANDLER)); - RegisterSchema("fileBrowserHandlerInternal", ReadFromResource( - IDR_EXTENSION_API_JSON_FILEBROWSERHANDLERINTERNAL)); RegisterSchema("fileBrowserPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_FILEBROWSERPRIVATE)); - RegisterSchema("fontSettings", ReadFromResource( - IDR_EXTENSION_API_JSON_FONTSSETTINGS)); - RegisterSchema("history", ReadFromResource( - IDR_EXTENSION_API_JSON_HISTORY)); - RegisterSchema("i18n", ReadFromResource( - IDR_EXTENSION_API_JSON_I18N)); RegisterSchema("idle", ReadFromResource( IDR_EXTENSION_API_JSON_IDLE)); RegisterSchema("input.ime", ReadFromResource( @@ -416,8 +390,6 @@ void ExtensionAPI::InitDefaultConfiguration() { IDR_EXTENSION_API_JSON_INPUTMETHODPRIVATE)); RegisterSchema("managedModePrivate", ReadFromResource( IDR_EXTENSION_API_JSON_MANAGEDMODEPRIVATE)); - RegisterSchema("management", ReadFromResource( - IDR_EXTENSION_API_JSON_MANAGEMENT)); RegisterSchema("mediaPlayerPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_MEDIAPLAYERPRIVATE)); RegisterSchema("metricsPrivate", ReadFromResource( @@ -430,8 +402,6 @@ void ExtensionAPI::InitDefaultConfiguration() { IDR_EXTENSION_API_JSON_PAGEACTION)); RegisterSchema("pageActions", ReadFromResource( IDR_EXTENSION_API_JSON_PAGEACTIONS)); - RegisterSchema("pageCapture", ReadFromResource( - IDR_EXTENSION_API_JSON_PAGECAPTURE)); RegisterSchema("permissions", ReadFromResource( IDR_EXTENSION_API_JSON_PERMISSIONS)); RegisterSchema("privacy", ReadFromResource( @@ -440,12 +410,8 @@ void ExtensionAPI::InitDefaultConfiguration() { IDR_EXTENSION_API_JSON_PROXY)); RegisterSchema("scriptBadge", ReadFromResource( IDR_EXTENSION_API_JSON_SCRIPTBADGE)); - RegisterSchema("storage", ReadFromResource( - IDR_EXTENSION_API_JSON_STORAGE)); RegisterSchema("systemPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_SYSTEMPRIVATE)); - RegisterSchema("tabs", ReadFromResource( - IDR_EXTENSION_API_JSON_TABS)); RegisterSchema("terminalPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_TERMINALPRIVATE)); RegisterSchema("test", ReadFromResource( @@ -460,10 +426,6 @@ void ExtensionAPI::InitDefaultConfiguration() { IDR_EXTENSION_API_JSON_TYPES)); RegisterSchema("wallpaperPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_WALLPAPERPRIVATE)); - RegisterSchema("webNavigation", ReadFromResource( - IDR_EXTENSION_API_JSON_WEBNAVIGATION)); - RegisterSchema("webRequest", ReadFromResource( - IDR_EXTENSION_API_JSON_WEBREQUEST)); RegisterSchema("webRequestInternal", ReadFromResource( IDR_EXTENSION_API_JSON_WEBREQUESTINTERNAL)); RegisterSchema("webSocketProxyPrivate", ReadFromResource( @@ -472,8 +434,6 @@ void ExtensionAPI::InitDefaultConfiguration() { IDR_EXTENSION_API_JSON_WEBSTORE)); RegisterSchema("webstorePrivate", ReadFromResource( IDR_EXTENSION_API_JSON_WEBSTOREPRIVATE)); - RegisterSchema("windows", ReadFromResource( - IDR_EXTENSION_API_JSON_WINDOWS)); // Schemas to be loaded via JSON generated from IDL files. GeneratedSchemas::Get(&unloaded_schemas_); diff --git a/chrome/common/extensions/api/file_browser_handler_internal.json b/chrome/common/extensions/api/file_browser_handler_internal.json index 38fa8d3..a50a0a8 100644 --- a/chrome/common/extensions/api/file_browser_handler_internal.json +++ b/chrome/common/extensions/api/file_browser_handler_internal.json @@ -5,6 +5,9 @@ [ { "namespace": "fileBrowserHandlerInternal", + "compiler_options": { + "implemented_in": "chrome/browser/chromeos/extensions/file_browser_handler_api.h" + }, "nodoc": true, "internal": true, "platforms": ["chromeos"], diff --git a/chrome/common/extensions/api/i18n.json b/chrome/common/extensions/api/i18n.json index db3c3f6..765760d 100644 --- a/chrome/common/extensions/api/i18n.json +++ b/chrome/common/extensions/api/i18n.json @@ -23,6 +23,7 @@ }, { "name": "getMessage", + "nocompile": true, "type": "function", "unprivileged": true, "description": "Gets the localized string for the specified message. If the message is missing, this method returns an empty string (''). If the format of the <code>getMessage()</code> call is wrong — for example, <em>messageName</em> is not a string or the <em>substitutions</em> array has more than 9 elements — this method returns <code>undefined</code>.", diff --git a/chrome/common/extensions/api/storage.json b/chrome/common/extensions/api/storage.json index 3e02335..a75de09 100644 --- a/chrome/common/extensions/api/storage.json +++ b/chrome/common/extensions/api/storage.json @@ -6,6 +6,9 @@ { "namespace": "storage", "unprivileged": true, + "compiler_options": { + "generate_type_functions": true + }, "types": [ { "id": "StorageChange", diff --git a/chrome/common/extensions/api/windows.json b/chrome/common/extensions/api/windows.json index dbfe080..ee0702b 100644 --- a/chrome/common/extensions/api/windows.json +++ b/chrome/common/extensions/api/windows.json @@ -5,6 +5,9 @@ [ { "namespace": "windows", + "compiler_options": { + "implemented_in": "chrome/browser/extensions/api/tabs/tabs_api.h" + }, "dependencies": [ "tabs" ], "types": [ { diff --git a/chrome/common/extensions/docs/server2/api_data_source.py b/chrome/common/extensions/docs/server2/api_data_source.py index 8826768..5cb8824 100644 --- a/chrome/common/extensions/docs/server2/api_data_source.py +++ b/chrome/common/extensions/docs/server2/api_data_source.py @@ -14,9 +14,10 @@ import third_party.json_schema_compiler.idl_schema as idl_schema import third_party.json_schema_compiler.idl_parser as idl_parser # Increment this version when there are changes to the data stored in any of -# the caches used by APIDataSource. This allows the cache to be invalidated -# without having to flush memcache on the production server. -_VERSION = 9 +# the caches used by APIDataSource. This would include changes to model.py in +# JSON schema compiler! This allows the cache to be invalidated without having +# to flush memcache on the production server. +_VERSION = 10 def _RemoveNoDocs(item): if json_parse.IsDict(item): diff --git a/chrome/common/extensions_api_resources.grd b/chrome/common/extensions_api_resources.grd index bbf2c0d..915a1c8 100644 --- a/chrome/common/extensions_api_resources.grd +++ b/chrome/common/extensions_api_resources.grd @@ -10,57 +10,40 @@ <release seq="1"> <includes> <include name="IDR_EXTENSION_API_JSON_APP" file="extensions\api\app.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_BOOKMARKS" file="extensions\api\bookmarks.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_BOOKMARKMANAGERPRIVATE" file="extensions\api\bookmark_manager_private.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_BROWSERACTION" file="extensions\api\browser_action.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_BROWSINGDATA" file="extensions\api\browsing_data.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_CHROMEOSINFOPRIVATE" file="extensions\api\chromeos_info_private.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_CLOUDPRINTPRIVATE" file="extensions\api\cloud_print_private.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_COMMANDS" file="extensions\api\commands.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_CONTENTSETTINGS" file="extensions\api\content_settings.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_CONTEXTMENUS" file="extensions\api\context_menus.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_COOKIES" file="extensions\api\cookies.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_DEBUGGER" file="extensions\api\debugger.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_DECLARATIVE_WEBREQUEST" file="extensions\api\declarative_web_request.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_DEVTOOLS" file="extensions\api\devtools.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_ECHOPRIVATE" file="extensions\api\echo_private.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_EVENTS" file="extensions\api\events.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_ACCESSIBILITY" file="extensions\api\experimental_accessibility.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_APP" file="extensions\api\experimental_app.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_HISTORY" file="extensions\api\experimental_history.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_INFOBARS" file="extensions\api\experimental_infobars.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_INPUT_VIRTUALKEYBOARD" file="extensions\api\experimental_input_virtual_keyboard.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_POWER" file="extensions\api\experimental_power.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_PROCESSES" file="extensions\api\experimental_processes.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_RECORD" file="extensions\api\experimental_record.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_RLZ" file="extensions\api\experimental_rlz.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_EXPERIMENTAL_SPEECHINPUT" file="extensions\api\experimental_speech_input.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_EXTENSION" file="extensions\api\extension.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_FILEBROWSERHANDLER" file="extensions\api\file_browser_handler.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_FILEBROWSERHANDLERINTERNAL" file="extensions\api\file_browser_handler_internal.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_FILEBROWSERPRIVATE" file="extensions\api\file_browser_private.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_FONTSSETTINGS" file="extensions\api\font_settings.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_HISTORY" file="extensions\api\history.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_I18N" file="extensions\api\i18n.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_INPUT_IME" file="extensions\api\input_ime.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_IDLE" file="extensions\api\idle.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_INPUTMETHODPRIVATE" file="extensions\api\input_method_private.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_MANAGEDMODEPRIVATE" file="extensions\api\managed_mode_private.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_MANAGEMENT" file="extensions\api\management.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_MEDIAPLAYERPRIVATE" file="extensions\api\media_player_private.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_METRICSPRIVATE" file="extensions\api\metrics_private.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_OMNIBOX" file="extensions\api\omnibox.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_PAGEACTION" file="extensions\api\page_action.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_PAGEACTIONS" file="extensions\api\page_actions.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_PAGECAPTURE" file="extensions\api\page_capture.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_PERMISSIONS" file="extensions\api\permissions.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_PRIVACY" file="extensions\api\privacy.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_PROXY" file="extensions\api\proxy.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_RUNTIME" file="extensions\api\runtime.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_SCRIPTBADGE" file="extensions\api\script_badge.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_STORAGE" file="extensions\api\storage.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_SYSTEMPRIVATE" file="extensions\api\system_private.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_TABS" file="extensions\api\tabs.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_TERMINALPRIVATE" file="extensions\api\terminal_private.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_TEST" file="extensions\api\test.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_TOPSITES" file="extensions\api\top_sites.json" type="BINDATA" /> @@ -68,13 +51,10 @@ <include name="IDR_EXTENSION_API_JSON_TTSENGINE" file="extensions\api\tts_engine.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_TYPES" file="extensions\api\types.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_WALLPAPERPRIVATE" file="extensions\api\wallpaper_private.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_WEBNAVIGATION" file="extensions\api\web_navigation.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_WEBREQUEST" file="extensions\api\web_request.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_WEBSOCKETPROXYPRIVATE" file="extensions\api\web_socket_proxy_private.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_WEBREQUESTINTERNAL" file="extensions\api\web_request_internal.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_WEBSTORE" file="extensions\api\webstore.json" type="BINDATA" /> <include name="IDR_EXTENSION_API_JSON_WEBSTOREPRIVATE" file="extensions\api\webstore_private.json" type="BINDATA" /> - <include name="IDR_EXTENSION_API_JSON_WINDOWS" file="extensions\api\windows.json" type="BINDATA" /> </includes> </release> </grit> diff --git a/tools/json_schema_compiler/code.py b/tools/json_schema_compiler/code.py index 07f6574..e4326d4 100644 --- a/tools/json_schema_compiler/code.py +++ b/tools/json_schema_compiler/code.py @@ -14,15 +14,17 @@ class Code(object): self._indent_size = indent_size self._comment_length = comment_length - def Append(self, line='', substitute=True): + def Append(self, line='', substitute=True, indent_level=None): """Appends a line of code at the current indent level or just a newline if line is not specified. Trailing whitespace is stripped. substitute: indicated whether this line should be affected by code.Substitute(). """ - self._code.append(Line(((' ' * self._indent_level) + line).rstrip(), - substitute=substitute)) + if indent_level is None: + indent_level = self._indent_level + self._code.append(Line(((' ' * indent_level) + line).rstrip(), + substitute=substitute)) return self def IsEmpty(self): diff --git a/tools/json_schema_compiler/compiler.py b/tools/json_schema_compiler/compiler.py index ae92373..a347541 100755 --- a/tools/json_schema_compiler/compiler.py +++ b/tools/json_schema_compiler/compiler.py @@ -69,13 +69,16 @@ def handle_single_schema(filename, dest_dir, root, root_namespace): referenced_api_defs = json_schema.Load(referenced_schema_path) for namespace in referenced_api_defs: - api_model.AddNamespace(namespace, + api_model.AddNamespace( + namespace, os.path.relpath(referenced_schema_path, opts.root)) # Gets the relative path from opts.root to the schema to correctly determine # the include path. relpath = os.path.relpath(schema, opts.root) - namespace = api_model.AddNamespace(target_namespace, relpath) + namespace = api_model.AddNamespace(target_namespace, + relpath, + include_compiler_options=True) if not namespace: continue @@ -130,7 +133,9 @@ def handle_bundle_schema(filenames, dest_dir, root, root_namespace): relpath = os.path.relpath(os.path.normpath(filenames[0]), root) for target_namespace, schema_filename in zip(api_defs, filenames): - namespace = api_model.AddNamespace(target_namespace, relpath) + namespace = api_model.AddNamespace(target_namespace, + relpath, + include_compiler_options=True) path, filename = os.path.split(schema_filename) short_filename, extension = os.path.splitext(filename) diff --git a/tools/json_schema_compiler/model.py b/tools/json_schema_compiler/model.py index b583712..36be5a3 100644 --- a/tools/json_schema_compiler/model.py +++ b/tools/json_schema_compiler/model.py @@ -26,10 +26,12 @@ class Model(object): def __init__(self): self.namespaces = {} - def AddNamespace(self, json, source_file): + def AddNamespace(self, json, source_file, include_compiler_options=False): """Add a namespace's json to the model and returns the namespace. """ - namespace = Namespace(json, source_file) + namespace = Namespace(json, + source_file, + include_compiler_options=include_compiler_options) self.namespaces[namespace.name] = namespace return namespace @@ -42,21 +44,28 @@ class Namespace(object): - |source_file| the file that contained the namespace definition - |source_file_dir| the directory component of |source_file| - |source_file_filename| the filename component of |source_file| + - |platforms| if not None, the list of platforms that the namespace is + available to - |types| a map of type names to their model.Type - |functions| a map of function names to their model.Function - |events| a map of event names to their model.Function - |properties| a map of property names to their model.Property + - |compiler_options| the compiler_options dict, only present if + |include_compiler_options| is True """ - def __init__(self, json, source_file): + def __init__(self, json, source_file, include_compiler_options=False): self.name = json['namespace'] self.unix_name = UnixName(self.name) self.source_file = source_file self.source_file_dir, self.source_file_filename = os.path.split(source_file) self.parent = None + self.platforms = _GetPlatforms(json) _AddTypes(self, json, self) _AddFunctions(self, json, self) _AddEvents(self, json, self) _AddProperties(self, json, self) + if include_compiler_options: + self.compiler_options = json.get('compiler_options', {}) class Type(object): """A Type defined in the json. @@ -127,13 +136,15 @@ class Function(object): Properties: - |name| the function name + - |platforms| if not None, the list of platforms that the function is + available to - |params| a list of parameters to the function (order matters). A separate - parameter is used for each choice of a 'choices' parameter. + parameter is used for each choice of a 'choices' parameter - |description| a description of the function (if provided) - |callback| the callback parameter to the function. There should be exactly - one + one - |optional| whether the Function is "optional"; this only makes sense to be - present when the Function is representing a callback property. + present when the Function is representing a callback property - |simple_name| the name of this Function without a namespace """ def __init__(self, @@ -144,6 +155,7 @@ class Function(object): from_client=False): self.name = json['name'] self.simple_name = _StripNamespace(self.name, namespace) + self.platforms = _GetPlatforms(json) self.params = [] self.description = json.get('description') self.callback = None @@ -357,23 +369,37 @@ class Property(object): unix_name = property(GetUnixName, SetUnixName) -class _PropertyTypeInfo(object): - """This class is not an inner class of |PropertyType| so it can be pickled. +class _Enum(object): + """Superclass for enum types with a "name" field, setting up repr/eq/ne. + Enums need to do this so that equality/non-equality work over pickling. """ - def __init__(self, is_fundamental, name): - self.is_fundamental = is_fundamental + + @staticmethod + def GetAll(cls): + """Yields all _Enum objects declared in |cls|. + """ + for prop_key in dir(cls): + prop_value = getattr(cls, prop_key) + if isinstance(prop_value, _Enum): + yield prop_value + + def __init__(self, name): self.name = name - def __repr__(self): + def __repr(self): return self.name def __eq__(self, other): - return isinstance(other, _PropertyTypeInfo) and self.name == other.name + return type(other) == type(self) and other.name == self.name def __ne__(self, other): - # Yes. You seriously do need this. return not (self == other) +class _PropertyTypeInfo(_Enum): + def __init__(self, is_fundamental, name): + _Enum.__init__(self, name) + self.is_fundamental = is_fundamental + class PropertyType(object): """Enum of different types of properties/parameters. """ @@ -461,3 +487,27 @@ def _AddProperties(model, namespace, from_json=from_json, from_client=from_client) + +class _PlatformInfo(_Enum): + def __init__(self, name): + _Enum.__init__(self, name) + +class Platforms(object): + """Enum of the possible platforms. + """ + CHROMEOS = _PlatformInfo("chromeos") + CHROMEOS_TOUCH = _PlatformInfo("chromeos_touch") + LINUX = _PlatformInfo("linux") + MAC = _PlatformInfo("mac") + WIN = _PlatformInfo("win") + +def _GetPlatforms(json): + if 'platforms' not in json: + return None + platforms = [] + for platform_name in json['platforms']: + for platform_enum in _Enum.GetAll(Platforms): + if platform_name == platform_enum.name: + platforms.append(platform_enum) + break + return platforms diff --git a/tools/json_schema_compiler/schema_bundle_generator.py b/tools/json_schema_compiler/schema_bundle_generator.py index d391ea7..3272be1 100644 --- a/tools/json_schema_compiler/schema_bundle_generator.py +++ b/tools/json_schema_compiler/schema_bundle_generator.py @@ -4,6 +4,7 @@ import code import cpp_util +from model import Platforms from schema_util import CapitalizeFirstLetter from schema_util import JsFunctionNameToClassName @@ -44,6 +45,20 @@ class SchemaBundleGenerator(object): c.Append() return c + def _GetPlatformIfdefs(self, model_object): + """Generates the "defined" conditional for an #if check if |model_object| + has platform restrictions. Returns None if there are no restrictions. + """ + if model_object.platforms is None: + return None + ifdefs = [] + for platform in model_object.platforms: + if platform == Platforms.CHROMEOS: + ifdefs.append('defined(OS_CHROMEOS)') + else: + raise ValueError("Unsupported platform ifdef: %s" % platform.name) + return ' and '.join(ifdefs) + def GenerateAPIHeader(self): """Generates the header for API registration / declaration""" c = code.Code() @@ -53,9 +68,19 @@ class SchemaBundleGenerator(object): c.Append('#include "base/basictypes.h"') for namespace in self._model.namespaces.values(): + ifdefs = self._GetPlatformIfdefs(namespace) + if ifdefs is not None: + c.Append("#if %s" % ifdefs, indent_level=0) + namespace_name = namespace.unix_name.replace("experimental_", "") - c.Append('#include "chrome/browser/extensions/api/%s/%s_api.h"' % ( - namespace_name, namespace_name)) + implementation_header = namespace.compiler_options.get( + "implemented_in", + "chrome/browser/extensions/api/%s/%s_api.h" % (namespace_name, + namespace_name)) + c.Append('#include "%s"' % implementation_header) + + if ifdefs is not None: + c.Append("#endif // %s" % ifdefs, indent_level=0) c.Append() c.Append("class ExtensionFunctionRegistry;") @@ -70,20 +95,41 @@ class SchemaBundleGenerator(object): c.Append() return self.GenerateHeader('generated_api', c) + def _GetNamespaceFunctions(self, namespace): + functions = list(namespace.functions.values()) + if namespace.compiler_options.get("generate_type_functions", False): + for type_ in namespace.types.values(): + functions += list(type_.functions.values()) + return functions + def GenerateFunctionRegistry(self): c = code.Code() c.Sblock("class GeneratedFunctionRegistry {") - c.Append("public:") + c.Append(" public:") c.Sblock("static void RegisterAll(ExtensionFunctionRegistry* registry) {") for namespace in self._model.namespaces.values(): + namespace_ifdefs = self._GetPlatformIfdefs(namespace) + if namespace_ifdefs is not None: + c.Append("#if %s" % namespace_ifdefs, indent_level=0) + namespace_name = CapitalizeFirstLetter(namespace.name.replace( "experimental.", "")) - for function in namespace.functions.values(): + for function in self._GetNamespaceFunctions(namespace): if function.nocompile: continue + function_ifdefs = self._GetPlatformIfdefs(function) + if function_ifdefs is not None: + c.Append("#if %s" % function_ifdefs, indent_level=0) + function_name = JsFunctionNameToClassName(namespace.name, function.name) c.Append("registry->RegisterFunction<%sFunction>();" % ( function_name)) + + if function_ifdefs is not None: + c.Append("#endif // %s" % function_ifdefs, indent_level=0) + + if namespace_ifdefs is not None: + c.Append("#endif // %s" % namespace_ifdefs, indent_level=0) c.Eblock("}") c.Eblock("};") c.Append() @@ -100,7 +146,7 @@ class SchemaBundleGenerator(object): c.Concat(self._cpp_type_generator.GetRootNamespaceStart()) c.Append() c.Sblock('class GeneratedSchemas {') - c.Append('public:') + c.Append(' public:') c.Append('// Puts all API schemas in |schemas|.') c.Append('static void Get(' 'std::map<std::string, base::StringPiece>* schemas);') diff --git a/tools/json_schema_compiler/test/json_schema_compiler_tests.gyp b/tools/json_schema_compiler/test/json_schema_compiler_tests.gyp index f8e5dc3..43ec909 100644 --- a/tools/json_schema_compiler/test/json_schema_compiler_tests.gyp +++ b/tools/json_schema_compiler/test/json_schema_compiler_tests.gyp @@ -9,9 +9,9 @@ 'type': 'static_library', 'variables': { 'chromium_code': 1, - 'json_schema_files': [ - 'any.json', + 'schema_files': [ 'additional_properties.json', + 'any.json', 'arrays.json', 'callbacks.json', 'choices.json', @@ -19,22 +19,19 @@ 'enums.json', 'functions_as_parameters.json', 'functions_on_types.json', + 'idl_basics.idl', + 'idl_object_types.idl', 'objects.json', 'simple_api.json', ], - 'idl_schema_files': [ - 'idl_basics.idl', - 'idl_object_types.idl' - ], 'cc_dir': 'tools/json_schema_compiler/test', 'root_namespace': 'test::api', }, 'inputs': [ - '<@(idl_schema_files)', + '<@(schema_files)', ], 'sources': [ - '<@(json_schema_files)', - '<@(idl_schema_files)', + '<@(schema_files)', ], 'includes': ['../../../build/json_schema_compile.gypi'], }, |