diff options
125 files changed, 3225 insertions, 3026 deletions
diff --git a/base/BUILD.gn b/base/BUILD.gn index 3f8380c..cf0d5a1 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn @@ -1465,82 +1465,17 @@ if (is_ios || is_android || is_win || (is_linux && !is_chromeos)) { } } -component("prefs") { - sources = [ - "prefs/default_pref_store.cc", - "prefs/default_pref_store.h", - "prefs/json_pref_store.cc", - "prefs/json_pref_store.h", - "prefs/overlay_user_pref_store.cc", - "prefs/overlay_user_pref_store.h", - "prefs/pref_change_registrar.cc", - "prefs/pref_change_registrar.h", - "prefs/pref_member.cc", - "prefs/pref_member.h", - "prefs/pref_notifier_impl.cc", - "prefs/pref_notifier_impl.h", - "prefs/pref_registry.cc", - "prefs/pref_registry.h", - "prefs/pref_registry_simple.cc", - "prefs/pref_registry_simple.h", - "prefs/pref_service.cc", - "prefs/pref_service.h", - "prefs/pref_service_factory.cc", - "prefs/pref_service_factory.h", - "prefs/pref_store.cc", - "prefs/pref_store.h", - "prefs/pref_value_map.cc", - "prefs/pref_value_map.h", - "prefs/pref_value_store.cc", - "prefs/pref_value_store.h", - "prefs/scoped_user_pref_update.cc", - "prefs/scoped_user_pref_update.h", - "prefs/value_map_pref_store.cc", - "prefs/value_map_pref_store.h", - ] - if (!is_ios) { - sources += [ - "prefs/base_prefs_export.h", - "prefs/persistent_pref_store.h", - "prefs/pref_filter.h", - "prefs/pref_notifier.h", - "prefs/pref_observer.h", - "prefs/writeable_pref_store.h", - ] - } - - defines = [ "BASE_PREFS_IMPLEMENTATION" ] - - deps = [ - ":base", +# TODO(brettw) remove these forwarding targets when all references to prefs are +# updated to point to components. +group("prefs") { + public_deps = [ + "//components/prefs", ] - - if (!is_debug) { - configs -= [ "//build/config/compiler:default_optimization" ] - configs += [ "//build/config/compiler:optimize_max" ] - } } - -source_set("prefs_test_support") { +group("prefs_test_support") { testonly = true - sources = [ - "prefs/mock_pref_change_callback.cc", - "prefs/mock_pref_change_callback.h", - "prefs/pref_store_observer_mock.cc", - "prefs/pref_store_observer_mock.h", - "prefs/testing_pref_service.cc", - "prefs/testing_pref_service.h", - "prefs/testing_pref_store.cc", - "prefs/testing_pref_store.h", - ] - public_deps = [ - ":prefs", - ] - deps = [ - ":base", - "//testing/gmock", - "//testing/gtest", + "//components/prefs:test_support", ] } @@ -1731,16 +1666,6 @@ test("base_unittests") { "posix/file_descriptor_shuffle_unittest.cc", "posix/unix_domain_socket_linux_unittest.cc", "power_monitor/power_monitor_unittest.cc", - "prefs/default_pref_store_unittest.cc", - "prefs/json_pref_store_unittest.cc", - "prefs/overlay_user_pref_store_unittest.cc", - "prefs/pref_change_registrar_unittest.cc", - "prefs/pref_member_unittest.cc", - "prefs/pref_notifier_impl_unittest.cc", - "prefs/pref_service_unittest.cc", - "prefs/pref_value_map_unittest.cc", - "prefs/pref_value_store_unittest.cc", - "prefs/scoped_user_pref_update_unittest.cc", "process/memory_unittest.cc", "process/memory_unittest_mac.h", "process/memory_unittest_mac.mm", @@ -1860,8 +1785,6 @@ test("base_unittests") { ":base", ":i18n", ":message_loop_tests", - ":prefs", - ":prefs_test_support", "//base/test:run_all_unittests", "//base/test:test_support", "//base/third_party/dynamic_annotations", diff --git a/base/base.gyp b/base/base.gyp index bc315b6..929a3e4 100644 --- a/base/base.gyp +++ b/base/base.gyp @@ -312,82 +312,6 @@ ], }, { - 'target_name': 'base_prefs', - 'type': '<(component)', - 'variables': { - 'enable_wexit_time_destructors': 1, - 'optimize': 'max', - }, - 'dependencies': [ - 'base', - ], - 'export_dependent_settings': [ - 'base', - ], - 'defines': [ - 'BASE_PREFS_IMPLEMENTATION', - ], - 'sources': [ - 'prefs/base_prefs_export.h', - 'prefs/default_pref_store.cc', - 'prefs/default_pref_store.h', - 'prefs/json_pref_store.cc', - 'prefs/json_pref_store.h', - 'prefs/overlay_user_pref_store.cc', - 'prefs/overlay_user_pref_store.h', - 'prefs/persistent_pref_store.h', - 'prefs/pref_change_registrar.cc', - 'prefs/pref_change_registrar.h', - 'prefs/pref_filter.h', - 'prefs/pref_member.cc', - 'prefs/pref_member.h', - 'prefs/pref_notifier.h', - 'prefs/pref_notifier_impl.cc', - 'prefs/pref_notifier_impl.h', - 'prefs/pref_observer.h', - 'prefs/pref_registry.cc', - 'prefs/pref_registry.h', - 'prefs/pref_registry_simple.cc', - 'prefs/pref_registry_simple.h', - 'prefs/pref_service.cc', - 'prefs/pref_service.h', - 'prefs/pref_service_factory.cc', - 'prefs/pref_service_factory.h', - 'prefs/pref_store.cc', - 'prefs/pref_store.h', - 'prefs/pref_value_map.cc', - 'prefs/pref_value_map.h', - 'prefs/pref_value_store.cc', - 'prefs/pref_value_store.h', - 'prefs/scoped_user_pref_update.cc', - 'prefs/scoped_user_pref_update.h', - 'prefs/value_map_pref_store.cc', - 'prefs/value_map_pref_store.h', - 'prefs/writeable_pref_store.h', - ], - 'includes': [ - '../build/android/increase_size_for_speed.gypi', - ], - }, - { - 'target_name': 'base_prefs_test_support', - 'type': 'static_library', - 'dependencies': [ - 'base', - 'base_prefs', - '../testing/gmock.gyp:gmock', - ], - 'sources': [ - 'prefs/mock_pref_change_callback.cc', - 'prefs/pref_store_observer_mock.cc', - 'prefs/pref_store_observer_mock.h', - 'prefs/testing_pref_service.cc', - 'prefs/testing_pref_service.h', - 'prefs/testing_pref_store.cc', - 'prefs/testing_pref_store.h', - ], - }, - { # This is the subset of files from base that should not be used with a # dynamic library. Note that this library cannot depend on base because # base depends on base_static. @@ -566,17 +490,6 @@ 'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc', - 'prefs/default_pref_store_unittest.cc', - 'prefs/json_pref_store_unittest.cc', - 'prefs/mock_pref_change_callback.h', - 'prefs/overlay_user_pref_store_unittest.cc', - 'prefs/pref_change_registrar_unittest.cc', - 'prefs/pref_member_unittest.cc', - 'prefs/pref_notifier_impl_unittest.cc', - 'prefs/pref_service_unittest.cc', - 'prefs/pref_value_map_unittest.cc', - 'prefs/pref_value_store_unittest.cc', - 'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc', 'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm', @@ -678,8 +591,6 @@ 'base', 'base_i18n', 'base_message_loop_tests', - 'base_prefs', - 'base_prefs_test_support', 'base_static', 'run_all_unittests', 'test_support_base', diff --git a/base/prefs/DEPS b/base/prefs/DEPS new file mode 100644 index 0000000..2edd44e --- /dev/null +++ b/base/prefs/DEPS @@ -0,0 +1,4 @@ +# TODO(brettw) remove this when prefs is completely moved to components. +include_rules = [ + "+components/prefs", +] diff --git a/base/prefs/README b/base/prefs/README deleted file mode 100644 index 52d9c43..0000000 --- a/base/prefs/README +++ /dev/null @@ -1,6 +0,0 @@ -Prefs is a general-purpose key-value store for application preferences. - -The Prefs code lives in base/prefs but is not part of the -'base/base.gyp:base' library because of a desire to keep its use -optional. If you use Prefs, you should add a GYP dependency on -base/base.gyp:base_prefs. diff --git a/base/prefs/base_prefs_export.h b/base/prefs/base_prefs_export.h index 3d207db..477e1aa 100644 --- a/base/prefs/base_prefs_export.h +++ b/base/prefs/base_prefs_export.h @@ -2,28 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_BASE_PREFS_EXPORT_H_ -#define BASE_PREFS_BASE_PREFS_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(BASE_PREFS_IMPLEMENTATION) -#define BASE_PREFS_EXPORT __declspec(dllexport) -#else -#define BASE_PREFS_EXPORT __declspec(dllimport) -#endif // defined(BASE_PREFS_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(BASE_PREFS_IMPLEMENTATION) -#define BASE_PREFS_EXPORT __attribute__((visibility("default"))) -#else -#define BASE_PREFS_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define BASE_PREFS_EXPORT -#endif - -#endif // BASE_PREFS_BASE_PREFS_EXPORT_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/base_prefs_export.h" diff --git a/base/prefs/default_pref_store.h b/base/prefs/default_pref_store.h index ac5364d..e590bf8 100644 --- a/base/prefs/default_pref_store.h +++ b/base/prefs/default_pref_store.h @@ -2,52 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_DEFAULT_PREF_STORE_H_ -#define BASE_PREFS_DEFAULT_PREF_STORE_H_ - -#include <string> - -#include "base/macros.h" -#include "base/observer_list.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/pref_store.h" -#include "base/prefs/pref_value_map.h" -#include "base/values.h" - -// Used within a PrefRegistry to keep track of default preference values. -class BASE_PREFS_EXPORT DefaultPrefStore : public PrefStore { - public: - typedef PrefValueMap::const_iterator const_iterator; - - DefaultPrefStore(); - - // PrefStore implementation: - bool GetValue(const std::string& key, - const base::Value** result) const override; - void AddObserver(PrefStore::Observer* observer) override; - void RemoveObserver(PrefStore::Observer* observer) override; - bool HasObservers() const override; - - // Sets a |value| for |key|. Should only be called if a value has not been - // set yet; otherwise call ReplaceDefaultValue(). - void SetDefaultValue(const std::string& key, scoped_ptr<base::Value> value); - - // Replaces the the value for |key| with a new value. Should only be called - // if a value has alreday been set; otherwise call SetDefaultValue(). - void ReplaceDefaultValue(const std::string& key, - scoped_ptr<base::Value> value); - - const_iterator begin() const; - const_iterator end() const; - - private: - ~DefaultPrefStore() override; - - PrefValueMap prefs_; - - base::ObserverList<PrefStore::Observer, true> observers_; - - DISALLOW_COPY_AND_ASSIGN(DefaultPrefStore); -}; - -#endif // BASE_PREFS_DEFAULT_PREF_STORE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/default_pref_store.h" diff --git a/base/prefs/json_pref_store.h b/base/prefs/json_pref_store.h index 6342977..247102f 100644 --- a/base/prefs/json_pref_store.h +++ b/base/prefs/json_pref_store.h @@ -2,228 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_JSON_PREF_STORE_H_ -#define BASE_PREFS_JSON_PREF_STORE_H_ - -#include <stdint.h> - -#include <set> -#include <string> - -#include "base/callback_forward.h" -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/files/important_file_writer.h" -#include "base/gtest_prod_util.h" -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/persistent_pref_store.h" -#include "base/threading/non_thread_safe.h" - -class PrefFilter; - -namespace base { -class Clock; -class DictionaryValue; -class FilePath; -class HistogramBase; -class JsonPrefStoreLossyWriteTest; -class SequencedTaskRunner; -class SequencedWorkerPool; -class Value; -FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestBasic); -FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestSinglePeriod); -FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestMultiplePeriods); -FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestPeriodWithGaps); -} - -// A writable PrefStore implementation that is used for user preferences. -class BASE_PREFS_EXPORT JsonPrefStore - : public PersistentPrefStore, - public base::ImportantFileWriter::DataSerializer, - public base::SupportsWeakPtr<JsonPrefStore>, - public base::NonThreadSafe { - public: - struct ReadResult; - - // Returns instance of SequencedTaskRunner which guarantees that file - // operations on the same file will be executed in sequenced order. - static scoped_refptr<base::SequencedTaskRunner> GetTaskRunnerForFile( - const base::FilePath& pref_filename, - base::SequencedWorkerPool* worker_pool); - - // Same as the constructor below with no alternate filename. - JsonPrefStore( - const base::FilePath& pref_filename, - const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner, - scoped_ptr<PrefFilter> pref_filter); - - // |sequenced_task_runner| must be a shutdown-blocking task runner, ideally - // created by the GetTaskRunnerForFile() method above. - // |pref_filename| is the path to the file to read prefs from. - // |pref_alternate_filename| is the path to an alternate file which the - // desired prefs may have previously been written to. If |pref_filename| - // doesn't exist and |pref_alternate_filename| does, |pref_alternate_filename| - // will be moved to |pref_filename| before the read occurs. - JsonPrefStore( - const base::FilePath& pref_filename, - const base::FilePath& pref_alternate_filename, - const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner, - scoped_ptr<PrefFilter> pref_filter); - - // PrefStore overrides: - bool GetValue(const std::string& key, - const base::Value** result) const override; - void AddObserver(PrefStore::Observer* observer) override; - void RemoveObserver(PrefStore::Observer* observer) override; - bool HasObservers() const override; - bool IsInitializationComplete() const override; - - // PersistentPrefStore overrides: - bool GetMutableValue(const std::string& key, base::Value** result) override; - void SetValue(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) override; - void SetValueSilently(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) override; - void RemoveValue(const std::string& key, uint32_t flags) override; - bool ReadOnly() const override; - PrefReadError GetReadError() const override; - // Note this method may be asynchronous if this instance has a |pref_filter_| - // in which case it will return PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE. - // See details in pref_filter.h. - PrefReadError ReadPrefs() override; - void ReadPrefsAsync(ReadErrorDelegate* error_delegate) override; - void CommitPendingWrite() override; - void SchedulePendingLossyWrites() override; - void ReportValueChanged(const std::string& key, uint32_t flags) override; - - // Just like RemoveValue(), but doesn't notify observers. Used when doing some - // cleanup that shouldn't otherwise alert observers. - void RemoveValueSilently(const std::string& key, uint32_t flags); - - // Registers |on_next_successful_write| to be called once, on the next - // successful write event of |writer_|. - void RegisterOnNextSuccessfulWriteCallback( - const base::Closure& on_next_successful_write); - - private: - // Represents a histogram for recording the number of writes to the pref file - // that occur every kHistogramWriteReportIntervalInMins minutes. - class BASE_PREFS_EXPORT WriteCountHistogram { - public: - static const int32_t kHistogramWriteReportIntervalMins; - - WriteCountHistogram(const base::TimeDelta& commit_interval, - const base::FilePath& path); - // Constructor for testing. |clock| is a test Clock that is used to retrieve - // the time. - WriteCountHistogram(const base::TimeDelta& commit_interval, - const base::FilePath& path, - scoped_ptr<base::Clock> clock); - ~WriteCountHistogram(); - - // Record that a write has occured. - void RecordWriteOccured(); - - // Reports writes (that have not yet been reported) in all of the recorded - // intervals that have elapsed up until current time. - void ReportOutstandingWrites(); - - base::HistogramBase* GetHistogram(); - - private: - // The minimum interval at which writes can occur. - const base::TimeDelta commit_interval_; - - // The path to the file. - const base::FilePath path_; - - // Clock which is used to retrieve the current time. - scoped_ptr<base::Clock> clock_; - - // The interval at which to report write counts. - const base::TimeDelta report_interval_; - - // The time at which the last histogram value was reported for the number - // of write counts. - base::Time last_report_time_; - - // The number of writes that have occured since the last write count was - // reported. - uint32_t writes_since_last_report_; - - DISALLOW_COPY_AND_ASSIGN(WriteCountHistogram); - }; - - FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest, - WriteCountHistogramTestBasic); - FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest, - WriteCountHistogramTestSinglePeriod); - FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest, - WriteCountHistogramTestMultiplePeriods); - FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest, - WriteCountHistogramTestPeriodWithGaps); - friend class base::JsonPrefStoreLossyWriteTest; - - ~JsonPrefStore() override; - - // This method is called after the JSON file has been read. It then hands - // |value| (or an empty dictionary in some read error cases) to the - // |pref_filter| if one is set. It also gives a callback pointing at - // FinalizeFileRead() to that |pref_filter_| which is then responsible for - // invoking it when done. If there is no |pref_filter_|, FinalizeFileRead() - // is invoked directly. - void OnFileRead(scoped_ptr<ReadResult> read_result); - - // ImportantFileWriter::DataSerializer overrides: - bool SerializeData(std::string* output) override; - - // This method is called after the JSON file has been read and the result has - // potentially been intercepted and modified by |pref_filter_|. - // |initialization_successful| is pre-determined by OnFileRead() and should - // be used when reporting OnInitializationCompleted(). - // |schedule_write| indicates whether a write should be immediately scheduled - // (typically because the |pref_filter_| has already altered the |prefs|) -- - // this will be ignored if this store is read-only. - void FinalizeFileRead(bool initialization_successful, - scoped_ptr<base::DictionaryValue> prefs, - bool schedule_write); - - // Schedule a write with the file writer as long as |flags| doesn't contain - // WriteablePrefStore::LOSSY_PREF_WRITE_FLAG. - void ScheduleWrite(uint32_t flags); - - const base::FilePath path_; - const base::FilePath alternate_path_; - const scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_; - - scoped_ptr<base::DictionaryValue> prefs_; - - bool read_only_; - - // Helper for safely writing pref data. - base::ImportantFileWriter writer_; - - scoped_ptr<PrefFilter> pref_filter_; - base::ObserverList<PrefStore::Observer, true> observers_; - - scoped_ptr<ReadErrorDelegate> error_delegate_; - - bool initialized_; - bool filtering_in_progress_; - bool pending_lossy_write_; - PrefReadError read_error_; - - std::set<std::string> keys_need_empty_value_; - - WriteCountHistogram write_count_histogram_; - - DISALLOW_COPY_AND_ASSIGN(JsonPrefStore); -}; - -#endif // BASE_PREFS_JSON_PREF_STORE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/json_pref_store.h" diff --git a/base/prefs/mock_pref_change_callback.h b/base/prefs/mock_pref_change_callback.h index 3030fab..90ad294 100644 --- a/base/prefs/mock_pref_change_callback.h +++ b/base/prefs/mock_pref_change_callback.h @@ -2,50 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_MOCK_PREF_CHANGE_CALLBACK_H_ -#define BASE_PREFS_MOCK_PREF_CHANGE_CALLBACK_H_ - -#include <string> - -#include "base/prefs/pref_change_registrar.h" -#include "base/prefs/pref_service.h" -#include "testing/gmock/include/gmock/gmock.h" - -using testing::Pointee; -using testing::Property; -using testing::Truly; - -// Matcher that checks whether the current value of the preference named -// |pref_name| in |prefs| matches |value|. If |value| is NULL, the matcher -// checks that the value is not set. -MATCHER_P3(PrefValueMatches, prefs, pref_name, value, "") { - const PrefService::Preference* pref = prefs->FindPreference(pref_name); - if (!pref) - return false; - - const base::Value* actual_value = pref->GetValue(); - if (!actual_value) - return value == NULL; - if (!value) - return actual_value == NULL; - return value->Equals(actual_value); -} - -// A mock for testing preference notifications and easy setup of expectations. -class MockPrefChangeCallback { - public: - explicit MockPrefChangeCallback(PrefService* prefs); - virtual ~MockPrefChangeCallback(); - - PrefChangeRegistrar::NamedChangeCallback GetCallback(); - - MOCK_METHOD1(OnPreferenceChanged, void(const std::string&)); - - void Expect(const std::string& pref_name, - const base::Value* value); - - private: - PrefService* prefs_; -}; - -#endif // BASE_PREFS_MOCK_PREF_CHANGE_CALLBACK_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/mock_pref_change_callback.h" diff --git a/base/prefs/overlay_user_pref_store.h b/base/prefs/overlay_user_pref_store.h index 35ada57..594c501 100644 --- a/base/prefs/overlay_user_pref_store.h +++ b/base/prefs/overlay_user_pref_store.h @@ -2,88 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_OVERLAY_USER_PREF_STORE_H_ -#define BASE_PREFS_OVERLAY_USER_PREF_STORE_H_ - -#include <stdint.h> - -#include <map> -#include <string> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/observer_list.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/persistent_pref_store.h" -#include "base/prefs/pref_value_map.h" - -// PersistentPrefStore that directs all write operations into an in-memory -// PrefValueMap. Read operations are first answered by the PrefValueMap. -// If the PrefValueMap does not contain a value for the requested key, -// the look-up is passed on to an underlying PersistentPrefStore |underlay_|. -class BASE_PREFS_EXPORT OverlayUserPrefStore : public PersistentPrefStore, - public PrefStore::Observer { - public: - explicit OverlayUserPrefStore(PersistentPrefStore* underlay); - - // Returns true if a value has been set for the |key| in this - // OverlayUserPrefStore, i.e. if it potentially overrides a value - // from the |underlay_|. - virtual bool IsSetInOverlay(const std::string& key) const; - - // Methods of PrefStore. - void AddObserver(PrefStore::Observer* observer) override; - void RemoveObserver(PrefStore::Observer* observer) override; - bool HasObservers() const override; - bool IsInitializationComplete() const override; - bool GetValue(const std::string& key, - const base::Value** result) const override; - - // Methods of PersistentPrefStore. - bool GetMutableValue(const std::string& key, base::Value** result) override; - void SetValue(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) override; - void SetValueSilently(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) override; - void RemoveValue(const std::string& key, uint32_t flags) override; - bool ReadOnly() const override; - PrefReadError GetReadError() const override; - PrefReadError ReadPrefs() override; - void ReadPrefsAsync(ReadErrorDelegate* delegate) override; - void CommitPendingWrite() override; - void SchedulePendingLossyWrites() override; - void ReportValueChanged(const std::string& key, uint32_t flags) override; - - // Methods of PrefStore::Observer. - void OnPrefValueChanged(const std::string& key) override; - void OnInitializationCompleted(bool succeeded) override; - - void RegisterOverlayPref(const std::string& key); - void RegisterOverlayPref(const std::string& overlay_key, - const std::string& underlay_key); - - protected: - ~OverlayUserPrefStore() override; - - private: - typedef std::map<std::string, std::string> NamesMap; - - const std::string& GetOverlayKey(const std::string& underlay_key) const; - const std::string& GetUnderlayKey(const std::string& overlay_key) const; - - // Returns true if |key| corresponds to a preference that shall be stored in - // an in-memory PrefStore that is not persisted to disk. - bool ShallBeStoredInOverlay(const std::string& key) const; - - base::ObserverList<PrefStore::Observer, true> observers_; - PrefValueMap overlay_; - scoped_refptr<PersistentPrefStore> underlay_; - NamesMap overlay_to_underlay_names_map_; - NamesMap underlay_to_overlay_names_map_; - - DISALLOW_COPY_AND_ASSIGN(OverlayUserPrefStore); -}; - -#endif // BASE_PREFS_OVERLAY_USER_PREF_STORE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/overlay_user_pref_store.h" diff --git a/base/prefs/persistent_pref_store.h b/base/prefs/persistent_pref_store.h index 89c7a71..a0fcf68 100644 --- a/base/prefs/persistent_pref_store.h +++ b/base/prefs/persistent_pref_store.h @@ -2,76 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PERSISTENT_PREF_STORE_H_ -#define BASE_PREFS_PERSISTENT_PREF_STORE_H_ - -#include <string> - -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/writeable_pref_store.h" - -// This interface is complementary to the PrefStore interface, declaring -// additional functionality that adds support for setting values and persisting -// the data to some backing store. -class BASE_PREFS_EXPORT PersistentPrefStore : public WriteablePrefStore { - public: - // Unique integer code for each type of error so we can report them - // distinctly in a histogram. - // NOTE: Don't change the explicit values of the enums as it will change the - // server's meaning of the histogram. - enum PrefReadError { - PREF_READ_ERROR_NONE = 0, - PREF_READ_ERROR_JSON_PARSE = 1, - PREF_READ_ERROR_JSON_TYPE = 2, - PREF_READ_ERROR_ACCESS_DENIED = 3, - PREF_READ_ERROR_FILE_OTHER = 4, - PREF_READ_ERROR_FILE_LOCKED = 5, - PREF_READ_ERROR_NO_FILE = 6, - PREF_READ_ERROR_JSON_REPEAT = 7, - // PREF_READ_ERROR_OTHER = 8, // Deprecated. - PREF_READ_ERROR_FILE_NOT_SPECIFIED = 9, - // Indicates that ReadPrefs() couldn't complete synchronously and is waiting - // for an asynchronous task to complete first. - PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE = 10, - PREF_READ_ERROR_MAX_ENUM - }; - - class ReadErrorDelegate { - public: - virtual ~ReadErrorDelegate() {} - - virtual void OnError(PrefReadError error) = 0; - }; - - // Whether the store is in a pseudo-read-only mode where changes are not - // actually persisted to disk. This happens in some cases when there are - // read errors during startup. - virtual bool ReadOnly() const = 0; - - // Gets the read error. Only valid if IsInitializationComplete() returns true. - virtual PrefReadError GetReadError() const = 0; - - // Reads the preferences from disk. Notifies observers via - // "PrefStore::OnInitializationCompleted" when done. - virtual PrefReadError ReadPrefs() = 0; - - // Reads the preferences from disk asynchronously. Notifies observers via - // "PrefStore::OnInitializationCompleted" when done. Also it fires - // |error_delegate| if it is not NULL and reading error has occurred. - // Owns |error_delegate|. - virtual void ReadPrefsAsync(ReadErrorDelegate* error_delegate) = 0; - - // Lands any pending writes to disk. - virtual void CommitPendingWrite() = 0; - - // Schedule a write if there is any lossy data pending. Unlike - // CommitPendingWrite() this does not immediately sync to disk, instead it - // triggers an eventual write if there is lossy data pending and if there - // isn't one scheduled already. - virtual void SchedulePendingLossyWrites() = 0; - - protected: - ~PersistentPrefStore() override {} -}; - -#endif // BASE_PREFS_PERSISTENT_PREF_STORE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/persistent_pref_store.h" diff --git a/base/prefs/pref_change_registrar.h b/base/prefs/pref_change_registrar.h index cd5a233..517b63f 100644 --- a/base/prefs/pref_change_registrar.h +++ b/base/prefs/pref_change_registrar.h @@ -2,80 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_CHANGE_REGISTRAR_H_ -#define BASE_PREFS_PREF_CHANGE_REGISTRAR_H_ - -#include <map> -#include <string> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/pref_observer.h" - -class PrefService; - -// Automatically manages the registration of one or more pref change observers -// with a PrefStore. Functions much like NotificationRegistrar, but specifically -// manages observers of preference changes. When the Registrar is destroyed, -// all registered observers are automatically unregistered with the PrefStore. -class BASE_PREFS_EXPORT PrefChangeRegistrar : public PrefObserver { - public: - // You can register this type of callback if you need to know the - // path of the preference that is changing. - typedef base::Callback<void(const std::string&)> NamedChangeCallback; - - PrefChangeRegistrar(); - virtual ~PrefChangeRegistrar(); - - // Must be called before adding or removing observers. Can be called more - // than once as long as the value of |service| doesn't change. - void Init(PrefService* service); - - // Adds a pref observer for the specified pref |path| and |obs| observer - // object. All registered observers will be automatically unregistered - // when the registrar's destructor is called. - // - // The second version binds a callback that will receive the path of - // the preference that is changing as its parameter. - // - // Only one observer may be registered per path. - void Add(const std::string& path, const base::Closure& obs); - void Add(const std::string& path, const NamedChangeCallback& obs); - - // Removes the pref observer registered for |path|. - void Remove(const std::string& path); - - // Removes all observers that have been previously added with a call to Add. - void RemoveAll(); - - // Returns true if no pref observers are registered. - bool IsEmpty() const; - - // Check whether |pref| is in the set of preferences being observed. - bool IsObserved(const std::string& pref); - - // Check whether any of the observed preferences has the managed bit set. - bool IsManaged(); - - // Return the PrefService for this registrar. - PrefService* prefs(); - const PrefService* prefs() const; - - private: - // PrefObserver: - void OnPreferenceChanged(PrefService* service, - const std::string& pref_name) override; - - static void InvokeUnnamedCallback(const base::Closure& callback, - const std::string& pref_name); - - typedef std::map<std::string, NamedChangeCallback> ObserverMap; - - ObserverMap observers_; - PrefService* service_; - - DISALLOW_COPY_AND_ASSIGN(PrefChangeRegistrar); -}; - -#endif // BASE_PREFS_PREF_CHANGE_REGISTRAR_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_change_registrar.h" diff --git a/base/prefs/pref_filter.h b/base/prefs/pref_filter.h index 82a44c6..6ed06bc 100644 --- a/base/prefs/pref_filter.h +++ b/base/prefs/pref_filter.h @@ -2,54 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_FILTER_H_ -#define BASE_PREFS_PREF_FILTER_H_ - -#include <string> - -#include "base/callback_forward.h" -#include "base/memory/scoped_ptr.h" -#include "base/prefs/base_prefs_export.h" - -namespace base { -class DictionaryValue; -class Value; -} // namespace base - -// Filters preferences as they are loaded from disk or updated at runtime. -// Currently supported only by JsonPrefStore. -class BASE_PREFS_EXPORT PrefFilter { - public: - // A callback to be invoked when |prefs| have been read (and possibly - // pre-modified) and are now ready to be handed back to this callback's - // builder. |schedule_write| indicates whether a write should be immediately - // scheduled (typically because the |prefs| were pre-modified). - typedef base::Callback<void(scoped_ptr<base::DictionaryValue> prefs, - bool schedule_write)> PostFilterOnLoadCallback; - - virtual ~PrefFilter() {} - - // This method is given ownership of the |pref_store_contents| read from disk - // before the underlying PersistentPrefStore gets to use them. It must hand - // them back via |post_filter_on_load_callback|, but may modify them first. - // Note: This method is asynchronous, which may make calls like - // PersistentPrefStore::ReadPrefs() asynchronous. The owner of filtered - // PersistentPrefStores should handle this to make the reads look synchronous - // to external users (see SegregatedPrefStore::ReadPrefs() for an example). - virtual void FilterOnLoad( - const PostFilterOnLoadCallback& post_filter_on_load_callback, - scoped_ptr<base::DictionaryValue> pref_store_contents) = 0; - - // Receives notification when a pref store value is changed, before Observers - // are notified. - virtual void FilterUpdate(const std::string& path) = 0; - - // Receives notification when the pref store is about to serialize data - // contained in |pref_store_contents| to a string. Modifications to - // |pref_store_contents| will be persisted to disk and also affect the - // in-memory state. - virtual void FilterSerializeData( - base::DictionaryValue* pref_store_contents) = 0; -}; - -#endif // BASE_PREFS_PREF_FILTER_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_filter.h" diff --git a/base/prefs/pref_member.h b/base/prefs/pref_member.h index 4290c0d..ff90e5e 100644 --- a/base/prefs/pref_member.h +++ b/base/prefs/pref_member.h @@ -1,355 +1,7 @@ // 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. -// -// A helper class that stays in sync with a preference (bool, int, real, -// string or filepath). For example: -// -// class MyClass { -// public: -// MyClass(PrefService* prefs) { -// my_string_.Init(prefs::kHomePage, prefs); -// } -// private: -// StringPrefMember my_string_; -// }; -// -// my_string_ should stay in sync with the prefs::kHomePage pref and will -// update if either the pref changes or if my_string_.SetValue is called. -// -// An optional observer can be passed into the Init method which can be used to -// notify MyClass of changes. Note that if you use SetValue(), the observer -// will not be notified. -#ifndef BASE_PREFS_PREF_MEMBER_H_ -#define BASE_PREFS_PREF_MEMBER_H_ - -#include <string> -#include <vector> - -#include "base/bind.h" -#include "base/callback_forward.h" -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/pref_observer.h" -#include "base/single_thread_task_runner.h" -#include "base/values.h" - -class PrefService; - -namespace subtle { - -class BASE_PREFS_EXPORT PrefMemberBase : public PrefObserver { - public: - // Type of callback you can register if you need to know the name of - // the pref that is changing. - typedef base::Callback<void(const std::string&)> NamedChangeCallback; - - PrefService* prefs() { return prefs_; } - const PrefService* prefs() const { return prefs_; } - - protected: - class BASE_PREFS_EXPORT Internal - : public base::RefCountedThreadSafe<Internal> { - public: - Internal(); - - // Update the value, either by calling |UpdateValueInternal| directly - // or by dispatching to the right thread. - // Takes ownership of |value|. - void UpdateValue(base::Value* value, - bool is_managed, - bool is_user_modifiable, - const base::Closure& callback) const; - - void MoveToThread(scoped_refptr<base::SingleThreadTaskRunner> task_runner); - - // See PrefMember<> for description. - bool IsManaged() const { - return is_managed_; - } - - bool IsUserModifiable() const { - return is_user_modifiable_; - } - - protected: - friend class base::RefCountedThreadSafe<Internal>; - virtual ~Internal(); - - void CheckOnCorrectThread() const { - DCHECK(IsOnCorrectThread()); - } - - private: - // This method actually updates the value. It should only be called from - // the thread the PrefMember is on. - virtual bool UpdateValueInternal(const base::Value& value) const = 0; - - bool IsOnCorrectThread() const; - - scoped_refptr<base::SingleThreadTaskRunner> thread_task_runner_; - mutable bool is_managed_; - mutable bool is_user_modifiable_; - - DISALLOW_COPY_AND_ASSIGN(Internal); - }; - - PrefMemberBase(); - virtual ~PrefMemberBase(); - - // See PrefMember<> for description. - void Init(const std::string& pref_name, - PrefService* prefs, - const NamedChangeCallback& observer); - void Init(const std::string& pref_name, PrefService* prefs); - - virtual void CreateInternal() const = 0; - - // See PrefMember<> for description. - void Destroy(); - - void MoveToThread(scoped_refptr<base::SingleThreadTaskRunner> task_runner); - - // PrefObserver - void OnPreferenceChanged(PrefService* service, - const std::string& pref_name) override; - - void VerifyValuePrefName() const { - DCHECK(!pref_name_.empty()); - } - - // This method is used to do the actual sync with the preference. - // Note: it is logically const, because it doesn't modify the state - // seen by the outside world. It is just doing a lazy load behind the scenes. - void UpdateValueFromPref(const base::Closure& callback) const; - - // Verifies the preference name, and lazily loads the preference value if - // it hasn't been loaded yet. - void VerifyPref() const; - - const std::string& pref_name() const { return pref_name_; } - - virtual Internal* internal() const = 0; - - // Used to allow registering plain base::Closure callbacks. - static void InvokeUnnamedCallback(const base::Closure& callback, - const std::string& pref_name); - - private: - // Ordered the members to compact the class instance. - std::string pref_name_; - NamedChangeCallback observer_; - PrefService* prefs_; - - protected: - bool setting_value_; -}; - -// This function implements StringListPrefMember::UpdateValue(). -// It is exposed here for testing purposes. -bool BASE_PREFS_EXPORT PrefMemberVectorStringUpdate( - const base::Value& value, - std::vector<std::string>* string_vector); - -} // namespace subtle - -template <typename ValueType> -class PrefMember : public subtle::PrefMemberBase { - public: - // Defer initialization to an Init method so it's easy to make this class be - // a member variable. - PrefMember() {} - virtual ~PrefMember() {} - - // Do the actual initialization of the class. Use the two-parameter - // version if you don't want any notifications of changes. This - // method should only be called on the UI thread. - void Init(const std::string& pref_name, - PrefService* prefs, - const NamedChangeCallback& observer) { - subtle::PrefMemberBase::Init(pref_name, prefs, observer); - } - void Init(const std::string& pref_name, - PrefService* prefs, - const base::Closure& observer) { - subtle::PrefMemberBase::Init( - pref_name, prefs, - base::Bind(&PrefMemberBase::InvokeUnnamedCallback, observer)); - } - void Init(const std::string& pref_name, PrefService* prefs) { - subtle::PrefMemberBase::Init(pref_name, prefs); - } - - // Unsubscribes the PrefMember from the PrefService. After calling this - // function, the PrefMember may not be used any more on the UI thread. - // Assuming |MoveToThread| was previously called, |GetValue|, |IsManaged|, - // and |IsUserModifiable| can still be called from the other thread but - // the results will no longer update from the PrefService. - // This method should only be called on the UI thread. - void Destroy() { - subtle::PrefMemberBase::Destroy(); - } - - // Moves the PrefMember to another thread, allowing read accesses from there. - // Changes from the PrefService will be propagated asynchronously - // via PostTask. - // This method should only be used from the thread the PrefMember is currently - // on, which is the UI thread by default. - void MoveToThread(scoped_refptr<base::SingleThreadTaskRunner> task_runner) { - subtle::PrefMemberBase::MoveToThread(task_runner); - } - - // Check whether the pref is managed, i.e. controlled externally through - // enterprise configuration management (e.g. windows group policy). Returns - // false for unknown prefs. - // This method should only be used from the thread the PrefMember is currently - // on, which is the UI thread unless changed by |MoveToThread|. - bool IsManaged() const { - VerifyPref(); - return internal_->IsManaged(); - } - - // Checks whether the pref can be modified by the user. This returns false - // when the pref is managed by a policy or an extension, and when a command - // line flag overrides the pref. - // This method should only be used from the thread the PrefMember is currently - // on, which is the UI thread unless changed by |MoveToThread|. - bool IsUserModifiable() const { - VerifyPref(); - return internal_->IsUserModifiable(); - } - - // Retrieve the value of the member variable. - // This method should only be used from the thread the PrefMember is currently - // on, which is the UI thread unless changed by |MoveToThread|. - ValueType GetValue() const { - VerifyPref(); - return internal_->value(); - } - - // Provided as a convenience. - ValueType operator*() const { - return GetValue(); - } - - // Set the value of the member variable. - // This method should only be called on the UI thread. - void SetValue(const ValueType& value) { - VerifyValuePrefName(); - setting_value_ = true; - UpdatePref(value); - setting_value_ = false; - } - - // Returns the pref name. - const std::string& GetPrefName() const { - return pref_name(); - } - - private: - class Internal : public subtle::PrefMemberBase::Internal { - public: - Internal() : value_(ValueType()) {} - - ValueType value() { - CheckOnCorrectThread(); - return value_; - } - - protected: - ~Internal() override {} - - BASE_PREFS_EXPORT bool UpdateValueInternal( - const base::Value& value) const override; - - // We cache the value of the pref so we don't have to keep walking the pref - // tree. - mutable ValueType value_; - - private: - DISALLOW_COPY_AND_ASSIGN(Internal); - }; - - Internal* internal() const override { return internal_.get(); } - void CreateInternal() const override { internal_ = new Internal(); } - - // This method is used to do the actual sync with pref of the specified type. - void BASE_PREFS_EXPORT UpdatePref(const ValueType& value); - - mutable scoped_refptr<Internal> internal_; - - DISALLOW_COPY_AND_ASSIGN(PrefMember); -}; - -// Declaration of template specialization need to be repeated here -// specifically for each specialization (rather than just once above) -// or at least one of our compilers won't be happy in all cases. -// Specifically, it was failing on ChromeOS with a complaint about -// PrefMember<FilePath>::UpdateValueInternal not being defined when -// built in a chroot with the following parameters: -// -// FEATURES="noclean nostrip" USE="-chrome_debug -chrome_remoting -// -chrome_internal -chrome_pdf component_build" -// ~/trunk/goma/goma-wrapper cros_chrome_make --board=${BOARD} -// --install --runhooks - -template <> -BASE_PREFS_EXPORT void PrefMember<bool>::UpdatePref(const bool& value); - -template <> -BASE_PREFS_EXPORT bool PrefMember<bool>::Internal::UpdateValueInternal( - const base::Value& value) const; - -template <> -BASE_PREFS_EXPORT void PrefMember<int>::UpdatePref(const int& value); - -template <> -BASE_PREFS_EXPORT bool PrefMember<int>::Internal::UpdateValueInternal( - const base::Value& value) const; - -template <> -BASE_PREFS_EXPORT void PrefMember<double>::UpdatePref(const double& value); - -template <> -BASE_PREFS_EXPORT bool PrefMember<double>::Internal::UpdateValueInternal( - const base::Value& value) const; - -template <> -BASE_PREFS_EXPORT void PrefMember<std::string>::UpdatePref( - const std::string& value); - -template <> -BASE_PREFS_EXPORT bool PrefMember<std::string>::Internal::UpdateValueInternal( - const base::Value& value) const; - -template <> -BASE_PREFS_EXPORT void PrefMember<base::FilePath>::UpdatePref( - const base::FilePath& value); - -template <> -BASE_PREFS_EXPORT bool -PrefMember<base::FilePath>::Internal::UpdateValueInternal( - const base::Value& value) const; - -template <> -BASE_PREFS_EXPORT void PrefMember<std::vector<std::string> >::UpdatePref( - const std::vector<std::string>& value); - -template <> -BASE_PREFS_EXPORT bool -PrefMember<std::vector<std::string> >::Internal::UpdateValueInternal( - const base::Value& value) const; - -typedef PrefMember<bool> BooleanPrefMember; -typedef PrefMember<int> IntegerPrefMember; -typedef PrefMember<double> DoublePrefMember; -typedef PrefMember<std::string> StringPrefMember; -typedef PrefMember<base::FilePath> FilePathPrefMember; -// This preference member is expensive for large string arrays. -typedef PrefMember<std::vector<std::string> > StringListPrefMember; - -#endif // BASE_PREFS_PREF_MEMBER_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_member.h" diff --git a/base/prefs/pref_notifier.h b/base/prefs/pref_notifier.h index e0df260..d99f5b8 100644 --- a/base/prefs/pref_notifier.h +++ b/base/prefs/pref_notifier.h @@ -2,25 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_NOTIFIER_H_ -#define BASE_PREFS_PREF_NOTIFIER_H_ - -#include <string> - -// Delegate interface used by PrefValueStore to notify its owner about changes -// to the preference values. -// TODO(mnissler, danno): Move this declaration to pref_value_store.h once we've -// cleaned up all public uses of this interface. -class PrefNotifier { - public: - virtual ~PrefNotifier() {} - - // Sends out a change notification for the preference identified by - // |pref_name|. - virtual void OnPreferenceChanged(const std::string& pref_name) = 0; - - // Broadcasts the intialization completed notification. - virtual void OnInitializationCompleted(bool succeeded) = 0; -}; - -#endif // BASE_PREFS_PREF_NOTIFIER_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_notifier.h" diff --git a/base/prefs/pref_notifier_impl.h b/base/prefs/pref_notifier_impl.h index 6e62e23..f47cc3e 100644 --- a/base/prefs/pref_notifier_impl.h +++ b/base/prefs/pref_notifier_impl.h @@ -2,73 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_NOTIFIER_IMPL_H_ -#define BASE_PREFS_PREF_NOTIFIER_IMPL_H_ - -#include <list> -#include <string> - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/containers/hash_tables.h" -#include "base/macros.h" -#include "base/observer_list.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/pref_notifier.h" -#include "base/prefs/pref_observer.h" -#include "base/threading/thread_checker.h" - -class PrefService; - -// The PrefNotifier implementation used by the PrefService. -class BASE_PREFS_EXPORT PrefNotifierImpl - : public NON_EXPORTED_BASE(PrefNotifier) { - public: - PrefNotifierImpl(); - explicit PrefNotifierImpl(PrefService* pref_service); - ~PrefNotifierImpl() override; - - // If the pref at the given path changes, we call the observer's - // OnPreferenceChanged method. - void AddPrefObserver(const std::string& path, PrefObserver* observer); - void RemovePrefObserver(const std::string& path, PrefObserver* observer); - - // We run the callback once, when initialization completes. The bool - // parameter will be set to true for successful initialization, - // false for unsuccessful. - void AddInitObserver(base::Callback<void(bool)> observer); - - void SetPrefService(PrefService* pref_service); - - protected: - // PrefNotifier overrides. - void OnPreferenceChanged(const std::string& pref_name) override; - void OnInitializationCompleted(bool succeeded) override; - - // A map from pref names to a list of observers. Observers get fired in the - // order they are added. These should only be accessed externally for unit - // testing. - typedef base::ObserverList<PrefObserver> PrefObserverList; - typedef base::hash_map<std::string, PrefObserverList*> PrefObserverMap; - - typedef std::list<base::Callback<void(bool)>> PrefInitObserverList; - - const PrefObserverMap* pref_observers() const { return &pref_observers_; } - - private: - // For the given pref_name, fire any observer of the pref. Virtual so it can - // be mocked for unit testing. - virtual void FireObservers(const std::string& path); - - // Weak reference; the notifier is owned by the PrefService. - PrefService* pref_service_; - - PrefObserverMap pref_observers_; - PrefInitObserverList init_observers_; - - base::ThreadChecker thread_checker_; - - DISALLOW_COPY_AND_ASSIGN(PrefNotifierImpl); -}; - -#endif // BASE_PREFS_PREF_NOTIFIER_IMPL_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_notifier_impl.h" diff --git a/base/prefs/pref_observer.h b/base/prefs/pref_observer.h index 5d8f5b6..df5d1af 100644 --- a/base/prefs/pref_observer.h +++ b/base/prefs/pref_observer.h @@ -2,20 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_OBSERVER_H_ -#define BASE_PREFS_PREF_OBSERVER_H_ - -#include <string> - -class PrefService; - -// Used internally to the Prefs subsystem to pass preference change -// notifications between PrefService, PrefNotifierImpl and -// PrefChangeRegistrar. -class PrefObserver { - public: - virtual void OnPreferenceChanged(PrefService* service, - const std::string& pref_name) = 0; -}; - -#endif // BASE_PREFS_PREF_OBSERVER_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_observer.h" diff --git a/base/prefs/pref_registry.h b/base/prefs/pref_registry.h index 7e141d8..94126d1 100644 --- a/base/prefs/pref_registry.h +++ b/base/prefs/pref_registry.h @@ -2,88 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_REGISTRY_H_ -#define BASE_PREFS_PREF_REGISTRY_H_ - -#include <stdint.h> - -#include "base/containers/hash_tables.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/pref_value_map.h" - -namespace base { -class Value; -} - -class DefaultPrefStore; -class PrefStore; - -// Preferences need to be registered with a type and default value -// before they are used. -// -// The way you use a PrefRegistry is that you register all required -// preferences on it (via one of its subclasses), then pass it as a -// construction parameter to PrefService. -// -// Currently, registrations after constructing the PrefService will -// also work, but this is being deprecated. -class BASE_PREFS_EXPORT PrefRegistry : public base::RefCounted<PrefRegistry> { - public: - // Registration flags that can be specified which impact how the pref will - // behave or be stored. This will be passed in a bitmask when the pref is - // registered. Subclasses of PrefRegistry can specify their own flags. Care - // must be taken to ensure none of these overlap with the flags below. - enum PrefRegistrationFlags : uint32_t { - // No flags are specified. - NO_REGISTRATION_FLAGS = 0, - - // The first 8 bits are reserved for subclasses of PrefRegistry to use. - - // This marks the pref as "lossy". There is no strict time guarantee on when - // a lossy pref will be persisted to permanent storage when it is modified. - LOSSY_PREF = 1 << 8, - }; - - typedef PrefValueMap::const_iterator const_iterator; - typedef base::hash_map<std::string, uint32_t> PrefRegistrationFlagsMap; - - PrefRegistry(); - - // Retrieve the set of registration flags for the given preference. The return - // value is a bitmask of PrefRegistrationFlags. - uint32_t GetRegistrationFlags(const std::string& pref_name) const; - - // Gets the registered defaults. - scoped_refptr<PrefStore> defaults(); - - // Allows iteration over defaults. - const_iterator begin() const; - const_iterator end() const; - - // Changes the default value for a preference. Takes ownership of |value|. - // - // |pref_name| must be a previously registered preference. - void SetDefaultPrefValue(const std::string& pref_name, base::Value* value); - - protected: - friend class base::RefCounted<PrefRegistry>; - virtual ~PrefRegistry(); - - // Used by subclasses to register a default value and registration flags for - // a preference. |flags| is a bitmask of |PrefRegistrationFlags|. - void RegisterPreference(const std::string& path, - base::Value* default_value, - uint32_t flags); - - scoped_refptr<DefaultPrefStore> defaults_; - - // A map of pref name to a bitmask of PrefRegistrationFlags. - PrefRegistrationFlagsMap registration_flags_; - - private: - DISALLOW_COPY_AND_ASSIGN(PrefRegistry); -}; - -#endif // BASE_PREFS_PREF_REGISTRY_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_registry.h" diff --git a/base/prefs/pref_registry_simple.h b/base/prefs/pref_registry_simple.h index 6afc012..0f157a2 100644 --- a/base/prefs/pref_registry_simple.h +++ b/base/prefs/pref_registry_simple.h @@ -2,90 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_REGISTRY_SIMPLE_H_ -#define BASE_PREFS_PREF_REGISTRY_SIMPLE_H_ - -#include <stdint.h> - -#include <string> - -#include "base/macros.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/pref_registry.h" - -namespace base { -class DictionaryValue; -class FilePath; -class ListValue; -} - -// A simple implementation of PrefRegistry. -class BASE_PREFS_EXPORT PrefRegistrySimple : public PrefRegistry { - public: - PrefRegistrySimple(); - - void RegisterBooleanPref(const std::string& path, bool default_value); - void RegisterIntegerPref(const std::string& path, int default_value); - void RegisterDoublePref(const std::string& path, double default_value); - void RegisterStringPref(const std::string& path, - const std::string& default_value); - void RegisterFilePathPref(const std::string& path, - const base::FilePath& default_value); - void RegisterListPref(const std::string& path); - void RegisterDictionaryPref(const std::string& path); - void RegisterListPref(const std::string& path, - base::ListValue* default_value); - void RegisterDictionaryPref(const std::string& path, - base::DictionaryValue* default_value); - void RegisterInt64Pref(const std::string& path, int64_t default_value); - void RegisterUint64Pref(const std::string&, uint64_t default_value); - - // Versions of registration functions that accept PrefRegistrationFlags. - // |flags| is a bitmask of PrefRegistrationFlags. - void RegisterBooleanPref(const std::string&, - bool default_value, - uint32_t flags); - void RegisterIntegerPref(const std::string&, - int default_value, - uint32_t flags); - void RegisterDoublePref(const std::string&, - double default_value, - uint32_t flags); - void RegisterStringPref(const std::string&, - const std::string& default_value, - uint32_t flags); - void RegisterFilePathPref(const std::string&, - const base::FilePath& default_value, - uint32_t flags); - void RegisterListPref(const std::string&, uint32_t flags); - void RegisterDictionaryPref(const std::string&, uint32_t flags); - void RegisterListPref(const std::string&, - base::ListValue* default_value, - uint32_t flags); - void RegisterDictionaryPref(const std::string&, - base::DictionaryValue* default_value, - uint32_t flags); - void RegisterInt64Pref(const std::string&, - int64_t default_value, - uint32_t flags); - void RegisterUint64Pref(const std::string&, - uint64_t default_value, - uint32_t flags); - - protected: - ~PrefRegistrySimple() override; - - // Allows subclasses to hook into pref registration. - virtual void OnPrefRegistered(const std::string&, - base::Value* default_value, - uint32_t flags); - - private: - void RegisterPrefAndNotify(const std::string&, - base::Value* default_value, - uint32_t flags); - - DISALLOW_COPY_AND_ASSIGN(PrefRegistrySimple); -}; - -#endif // BASE_PREFS_PREF_REGISTRY_SIMPLE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_registry_simple.h" diff --git a/base/prefs/pref_service.h b/base/prefs/pref_service.h index bec7830..aced2f0 100644 --- a/base/prefs/pref_service.h +++ b/base/prefs/pref_service.h @@ -2,384 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// This provides a way to access the application's current preferences. - -// Chromium settings and storage represent user-selected preferences and -// information and MUST not be extracted, overwritten or modified except -// through Chromium defined APIs. - -#ifndef BASE_PREFS_PREF_SERVICE_H_ -#define BASE_PREFS_PREF_SERVICE_H_ - -#include <stdint.h> - -#include <set> -#include <string> - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/containers/hash_tables.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/persistent_pref_store.h" -#include "base/threading/non_thread_safe.h" -#include "base/values.h" - -class PrefNotifier; -class PrefNotifierImpl; -class PrefObserver; -class PrefRegistry; -class PrefValueStore; -class PrefStore; - -namespace base { -class FilePath; -} - -namespace subtle { -class PrefMemberBase; -class ScopedUserPrefUpdateBase; -} - -// Base class for PrefServices. You can use the base class to read and -// interact with preferences, but not to register new preferences; for -// that see e.g. PrefRegistrySimple. -// -// Settings and storage accessed through this class represent -// user-selected preferences and information and MUST not be -// extracted, overwritten or modified except through the defined APIs. -class BASE_PREFS_EXPORT PrefService : public base::NonThreadSafe { - public: - enum PrefInitializationStatus { - INITIALIZATION_STATUS_WAITING, - INITIALIZATION_STATUS_SUCCESS, - INITIALIZATION_STATUS_CREATED_NEW_PREF_STORE, - INITIALIZATION_STATUS_ERROR - }; - - // A helper class to store all the information associated with a preference. - class BASE_PREFS_EXPORT Preference { - public: - // The type of the preference is determined by the type with which it is - // registered. This type needs to be a boolean, integer, double, string, - // dictionary (a branch), or list. You shouldn't need to construct this on - // your own; use the PrefService::Register*Pref methods instead. - Preference(const PrefService* service, - const std::string& name, - base::Value::Type type); - ~Preference() {} - - // Returns the name of the Preference (i.e., the key, e.g., - // browser.window_placement). - const std::string name() const; - - // Returns the registered type of the preference. - base::Value::Type GetType() const; - - // Returns the value of the Preference, falling back to the registered - // default value if no other has been set. - const base::Value* GetValue() const; - - // Returns the value recommended by the admin, if any. - const base::Value* GetRecommendedValue() const; - - // Returns true if the Preference is managed, i.e. set by an admin policy. - // Since managed prefs have the highest priority, this also indicates - // whether the pref is actually being controlled by the policy setting. - bool IsManaged() const; - - // Returns true if the Preference is controlled by the custodian of the - // supervised user. Since a supervised user is not expected to have an admin - // policy, this is the controlling pref if set. - bool IsManagedByCustodian() const; - - // Returns true if the Preference is recommended, i.e. set by an admin - // policy but the user is allowed to change it. - bool IsRecommended() const; - - // Returns true if the Preference has a value set by an extension, even if - // that value is being overridden by a higher-priority source. - bool HasExtensionSetting() const; - - // Returns true if the Preference has a user setting, even if that value is - // being overridden by a higher-priority source. - bool HasUserSetting() const; - - // Returns true if the Preference value is currently being controlled by an - // extension, and not by any higher-priority source. - bool IsExtensionControlled() const; - - // Returns true if the Preference value is currently being controlled by a - // user setting, and not by any higher-priority source. - bool IsUserControlled() const; - - // Returns true if the Preference is currently using its default value, - // and has not been set by any higher-priority source (even with the same - // value). - bool IsDefaultValue() const; - - // Returns true if the user can change the Preference value, which is the - // case if no higher-priority source than the user store controls the - // Preference. - bool IsUserModifiable() const; - - // Returns true if an extension can change the Preference value, which is - // the case if no higher-priority source than the extension store controls - // the Preference. - bool IsExtensionModifiable() const; - - // Return the registration flags for this pref as a bitmask of - // PrefRegistry::PrefRegistrationFlags. - uint32_t registration_flags() const { return registration_flags_; } - - private: - friend class PrefService; - - PrefValueStore* pref_value_store() const { - return pref_service_->pref_value_store_.get(); - } - - const std::string name_; - - const base::Value::Type type_; - - uint32_t registration_flags_; - - // Reference to the PrefService in which this pref was created. - const PrefService* pref_service_; - }; - - // You may wish to use PrefServiceFactory or one of its subclasses - // for simplified construction. - PrefService( - PrefNotifierImpl* pref_notifier, - PrefValueStore* pref_value_store, - PersistentPrefStore* user_prefs, - PrefRegistry* pref_registry, - base::Callback<void(PersistentPrefStore::PrefReadError)> - read_error_callback, - bool async); - virtual ~PrefService(); - - // Lands pending writes to disk. This should only be used if we need to save - // immediately (basically, during shutdown). - void CommitPendingWrite(); - - // Schedule a write if there is any lossy data pending. Unlike - // CommitPendingWrite() this does not immediately sync to disk, instead it - // triggers an eventual write if there is lossy data pending and if there - // isn't one scheduled already. - void SchedulePendingLossyWrites(); - - // Returns true if the preference for the given preference name is available - // and is managed. - bool IsManagedPreference(const std::string& pref_name) const; - - // Returns true if the preference for the given preference name is available - // and is controlled by the parent/guardian of the child Account. - bool IsPreferenceManagedByCustodian(const std::string& pref_name) const; - - // Returns |true| if a preference with the given name is available and its - // value can be changed by the user. - bool IsUserModifiablePreference(const std::string& pref_name) const; - - // Look up a preference. Returns NULL if the preference is not - // registered. - const PrefService::Preference* FindPreference(const std::string& path) const; - - // If the path is valid and the value at the end of the path matches the type - // specified, it will return the specified value. Otherwise, the default - // value (set when the pref was registered) will be returned. - bool GetBoolean(const std::string& path) const; - int GetInteger(const std::string& path) const; - double GetDouble(const std::string& path) const; - std::string GetString(const std::string& path) const; - base::FilePath GetFilePath(const std::string& path) const; - - // Returns the branch if it exists, or the registered default value otherwise. - // Note that |path| must point to a registered preference. In that case, these - // functions will never return NULL. - const base::DictionaryValue* GetDictionary(const std::string& path) const; - const base::ListValue* GetList(const std::string& path) const; - - // Removes a user pref and restores the pref to its default value. - void ClearPref(const std::string& path); - - // If the path is valid (i.e., registered), update the pref value in the user - // prefs. - // To set the value of dictionary or list values in the pref tree use - // Set(), but to modify the value of a dictionary or list use either - // ListPrefUpdate or DictionaryPrefUpdate from scoped_user_pref_update.h. - void Set(const std::string& path, const base::Value& value); - void SetBoolean(const std::string& path, bool value); - void SetInteger(const std::string& path, int value); - void SetDouble(const std::string& path, double value); - void SetString(const std::string& path, const std::string& value); - void SetFilePath(const std::string& path, const base::FilePath& value); - - // Int64 helper methods that actually store the given value as a string. - // Note that if obtaining the named value via GetDictionary or GetList, the - // Value type will be TYPE_STRING. - void SetInt64(const std::string& path, int64_t value); - int64_t GetInt64(const std::string& path) const; - - // As above, but for unsigned values. - void SetUint64(const std::string& path, uint64_t value); - uint64_t GetUint64(const std::string& path) const; - - // Returns the value of the given preference, from the user pref store. If - // the preference is not set in the user pref store, returns NULL. - const base::Value* GetUserPrefValue(const std::string& path) const; - - // Changes the default value for a preference. Takes ownership of |value|. - // - // Will cause a pref change notification to be fired if this causes - // the effective value to change. - void SetDefaultPrefValue(const std::string& path, base::Value* value); - - // Returns the default value of the given preference. |path| must point to a - // registered preference. In that case, will never return NULL. - const base::Value* GetDefaultPrefValue(const std::string& path) const; - - // Returns true if a value has been set for the specified path. - // NOTE: this is NOT the same as FindPreference. In particular - // FindPreference returns whether RegisterXXX has been invoked, where as - // this checks if a value exists for the path. - bool HasPrefPath(const std::string& path) const; - - // Returns a dictionary with effective preference values. - scoped_ptr<base::DictionaryValue> GetPreferenceValues() const; - - // Returns a dictionary with effective preference values, omitting prefs that - // are at their default values. - scoped_ptr<base::DictionaryValue> GetPreferenceValuesOmitDefaults() const; - - // Returns a dictionary with effective preference values. Contrary to - // GetPreferenceValues(), the paths of registered preferences are not split on - // '.' characters. If a registered preference stores a dictionary, however, - // the hierarchical structure inside the preference will be preserved. - // For example, if "foo.bar" is a registered preference, the result could look - // like this: - // {"foo.bar": {"a": {"b": true}}}. - scoped_ptr<base::DictionaryValue> GetPreferenceValuesWithoutPathExpansion() - const; - - bool ReadOnly() const; - - PrefInitializationStatus GetInitializationStatus() const; - - // Tell our PrefValueStore to update itself to |command_line_store|. - // Takes ownership of the store. - virtual void UpdateCommandLinePrefStore(PrefStore* command_line_store); - - // We run the callback once, when initialization completes. The bool - // parameter will be set to true for successful initialization, - // false for unsuccessful. - void AddPrefInitObserver(base::Callback<void(bool)> callback); - - // Returns the PrefRegistry object for this service. You should not - // use this; the intent is for no registrations to take place after - // PrefService has been constructed. - // - // Instead of using this method, the recommended approach is to - // register all preferences for a class Xyz up front in a static - // Xyz::RegisterPrefs function, which gets invoked early in the - // application's start-up, before a PrefService is created. - // - // As an example, prefs registration in Chrome is triggered by the - // functions chrome::RegisterPrefs (for global preferences) and - // chrome::RegisterProfilePrefs (for user-specific preferences) - // implemented in chrome/browser/prefs/browser_prefs.cc. - PrefRegistry* DeprecatedGetPrefRegistry(); - - protected: - // The PrefNotifier handles registering and notifying preference observers. - // It is created and owned by this PrefService. Subclasses may access it for - // unit testing. - scoped_ptr<PrefNotifierImpl> pref_notifier_; - - // The PrefValueStore provides prioritized preference values. It is owned by - // this PrefService. Subclasses may access it for unit testing. - scoped_ptr<PrefValueStore> pref_value_store_; - - scoped_refptr<PrefRegistry> pref_registry_; - - // Pref Stores and profile that we passed to the PrefValueStore. - scoped_refptr<PersistentPrefStore> user_pref_store_; - - // Callback to call when a read error occurs. - base::Callback<void(PersistentPrefStore::PrefReadError)> read_error_callback_; - - private: - // Hash map expected to be fastest here since it minimises expensive - // string comparisons. Order is unimportant, and deletions are rare. - // Confirmed on Android where this speeded Chrome startup by roughly 50ms - // vs. std::map, and by roughly 180ms vs. std::set of Preference pointers. - typedef base::hash_map<std::string, Preference> PreferenceMap; - - // Give access to ReportUserPrefChanged() and GetMutableUserPref(). - friend class subtle::ScopedUserPrefUpdateBase; - friend class PrefServiceTest_WriteablePrefStoreFlags_Test; - - // Registration of pref change observers must be done using the - // PrefChangeRegistrar, which is declared as a friend here to grant it - // access to the otherwise protected members Add/RemovePrefObserver. - // PrefMember registers for preferences changes notification directly to - // avoid the storage overhead of the registrar, so its base class must be - // declared as a friend, too. - friend class PrefChangeRegistrar; - friend class subtle::PrefMemberBase; - - // These are protected so they can only be accessed by the friend - // classes listed above. - // - // If the pref at the given path changes, we call the observer's - // OnPreferenceChanged method. Note that observers should not call - // these methods directly but rather use a PrefChangeRegistrar to - // make sure the observer gets cleaned up properly. - // - // Virtual for testing. - virtual void AddPrefObserver(const std::string& path, PrefObserver* obs); - virtual void RemovePrefObserver(const std::string& path, PrefObserver* obs); - - // Sends notification of a changed preference. This needs to be called by - // a ScopedUserPrefUpdate if a DictionaryValue or ListValue is changed. - void ReportUserPrefChanged(const std::string& key); - - // Sets the value for this pref path in the user pref store and informs the - // PrefNotifier of the change. - void SetUserPrefValue(const std::string& path, base::Value* new_value); - - // Load preferences from storage, attempting to diagnose and handle errors. - // This should only be called from the constructor. - void InitFromStorage(bool async); - - // Used to set the value of dictionary or list values in the user pref store. - // This will create a dictionary or list if one does not exist in the user - // pref store. This method returns NULL only if you're requesting an - // unregistered pref or a non-dict/non-list pref. - // |type| may only be Values::TYPE_DICTIONARY or Values::TYPE_LIST and - // |path| must point to a registered preference of type |type|. - // Ownership of the returned value remains at the user pref store. - base::Value* GetMutableUserPref(const std::string& path, - base::Value::Type type); - - // GetPreferenceValue is the equivalent of FindPreference(path)->GetValue(), - // it has been added for performance. If is faster because it does - // not need to find or create a Preference object to get the - // value (GetValue() calls back though the preference service to - // actually get the value.). - const base::Value* GetPreferenceValue(const std::string& path) const; - - // Local cache of registered Preference objects. The pref_registry_ - // is authoritative with respect to what the types and default values - // of registered preferences are. - mutable PreferenceMap prefs_map_; - - DISALLOW_COPY_AND_ASSIGN(PrefService); -}; - -#endif // BASE_PREFS_PREF_SERVICE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_service.h" diff --git a/base/prefs/pref_service_factory.h b/base/prefs/pref_service_factory.h index f84e037..3bc4932 100644 --- a/base/prefs/pref_service_factory.h +++ b/base/prefs/pref_service_factory.h @@ -2,90 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_SERVICE_FACTORY_H_ -#define BASE_PREFS_PREF_SERVICE_FACTORY_H_ - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/persistent_pref_store.h" -#include "base/prefs/pref_registry.h" -#include "base/prefs/pref_store.h" - -class PrefService; - -namespace base { - -class FilePath; -class SequencedTaskRunner; - -// A class that allows convenient building of PrefService. -class BASE_PREFS_EXPORT PrefServiceFactory { - public: - PrefServiceFactory(); - virtual ~PrefServiceFactory(); - - // Functions for setting the various parameters of the PrefService to build. - void set_managed_prefs(const scoped_refptr<PrefStore>& managed_prefs) { - managed_prefs_ = managed_prefs; - } - void set_supervised_user_prefs( - const scoped_refptr<PrefStore>& supervised_user_prefs) { - supervised_user_prefs_ = supervised_user_prefs; - } - void set_extension_prefs(const scoped_refptr<PrefStore>& extension_prefs) { - extension_prefs_ = extension_prefs; - } - void set_command_line_prefs( - const scoped_refptr<PrefStore>& command_line_prefs) { - command_line_prefs_ = command_line_prefs; - } - void set_user_prefs(const scoped_refptr<PersistentPrefStore>& user_prefs) { - user_prefs_ = user_prefs; - } - void set_recommended_prefs( - const scoped_refptr<PrefStore>& recommended_prefs) { - recommended_prefs_ = recommended_prefs; - } - - // Sets up error callback for the PrefService. A do-nothing default - // is provided if this is not called. - void set_read_error_callback( - const base::Callback<void(PersistentPrefStore::PrefReadError)>& - read_error_callback) { - read_error_callback_ = read_error_callback; - } - - // Specifies to use an actual file-backed user pref store. - void SetUserPrefsFile(const base::FilePath& prefs_file, - base::SequencedTaskRunner* task_runner); - - void set_async(bool async) { - async_ = async; - } - - // Creates a PrefService object initialized with the parameters from - // this factory. - scoped_ptr<PrefService> Create(PrefRegistry* registry); - - protected: - scoped_refptr<PrefStore> managed_prefs_; - scoped_refptr<PrefStore> supervised_user_prefs_; - scoped_refptr<PrefStore> extension_prefs_; - scoped_refptr<PrefStore> command_line_prefs_; - scoped_refptr<PersistentPrefStore> user_prefs_; - scoped_refptr<PrefStore> recommended_prefs_; - - base::Callback<void(PersistentPrefStore::PrefReadError)> read_error_callback_; - - // Defaults to false. - bool async_; - - private: - DISALLOW_COPY_AND_ASSIGN(PrefServiceFactory); -}; - -} // namespace base - -#endif // BASE_PREFS_PREF_SERVICE_FACTORY_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_service_factory.h" diff --git a/base/prefs/pref_store.h b/base/prefs/pref_store.h index f95c8c4..c1c6583 100644 --- a/base/prefs/pref_store.h +++ b/base/prefs/pref_store.h @@ -2,62 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_STORE_H_ -#define BASE_PREFS_PREF_STORE_H_ - -#include <string> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/prefs/base_prefs_export.h" - -namespace base { -class Value; -} - -// This is an abstract interface for reading and writing from/to a persistent -// preference store, used by PrefService. An implementation using a JSON file -// can be found in JsonPrefStore, while an implementation without any backing -// store for testing can be found in TestingPrefStore. Furthermore, there is -// CommandLinePrefStore, which bridges command line options to preferences and -// ConfigurationPolicyPrefStore, which is used for hooking up configuration -// policy with the preference subsystem. -class BASE_PREFS_EXPORT PrefStore : public base::RefCounted<PrefStore> { - public: - // Observer interface for monitoring PrefStore. - class BASE_PREFS_EXPORT Observer { - public: - // Called when the value for the given |key| in the store changes. - virtual void OnPrefValueChanged(const std::string& key) = 0; - // Notification about the PrefStore being fully initialized. - virtual void OnInitializationCompleted(bool succeeded) = 0; - - protected: - virtual ~Observer() {} - }; - - PrefStore() {} - - // Add and remove observers. - virtual void AddObserver(Observer* observer) {} - virtual void RemoveObserver(Observer* observer) {} - virtual bool HasObservers() const; - - // Whether the store has completed all asynchronous initialization. - virtual bool IsInitializationComplete() const; - - // Get the value for a given preference |key| and stores it in |*result|. - // |*result| is only modified if the return value is true and if |result| - // is not NULL. Ownership of the |*result| value remains with the PrefStore. - virtual bool GetValue(const std::string& key, - const base::Value** result) const = 0; - - protected: - friend class base::RefCounted<PrefStore>; - virtual ~PrefStore() {} - - private: - DISALLOW_COPY_AND_ASSIGN(PrefStore); -}; - -#endif // BASE_PREFS_PREF_STORE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_store.h" diff --git a/base/prefs/pref_store_observer_mock.h b/base/prefs/pref_store_observer_mock.h index 1b24b4e..be8e4d5 100644 --- a/base/prefs/pref_store_observer_mock.h +++ b/base/prefs/pref_store_observer_mock.h @@ -2,34 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_STORE_OBSERVER_MOCK_H_ -#define BASE_PREFS_PREF_STORE_OBSERVER_MOCK_H_ - -#include <string> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/prefs/pref_store.h" - -// A mock implementation of PrefStore::Observer. -class PrefStoreObserverMock : public PrefStore::Observer { - public: - PrefStoreObserverMock(); - ~PrefStoreObserverMock() override; - - void VerifyAndResetChangedKey(const std::string& expected); - - // PrefStore::Observer implementation - void OnPrefValueChanged(const std::string& key) override; - void OnInitializationCompleted(bool success) override; - - std::vector<std::string> changed_keys; - bool initialized; - bool initialization_success; // Only valid if |initialized|. - - private: - DISALLOW_COPY_AND_ASSIGN(PrefStoreObserverMock); -}; - -#endif // BASE_PREFS_PREF_STORE_OBSERVER_MOCK_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_store_observer_mock.h" diff --git a/base/prefs/pref_value_map.h b/base/prefs/pref_value_map.h index 349fe68..e1ec94a 100644 --- a/base/prefs/pref_value_map.h +++ b/base/prefs/pref_value_map.h @@ -2,90 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_VALUE_MAP_H_ -#define BASE_PREFS_PREF_VALUE_MAP_H_ - -#include <string> -#include <vector> - -#include "base/containers/scoped_ptr_hash_map.h" -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "base/prefs/base_prefs_export.h" - -namespace base { -class Value; -} - -// A generic string to value map used by the PrefStore implementations. -class BASE_PREFS_EXPORT PrefValueMap { - public: - using Map = base::ScopedPtrHashMap<std::string, scoped_ptr<base::Value>>; - using iterator = Map::iterator; - using const_iterator = Map::const_iterator; - - PrefValueMap(); - virtual ~PrefValueMap(); - - // Gets the value for |key| and stores it in |value|. Ownership remains with - // the map. Returns true if a value is present. If not, |value| is not - // touched. - bool GetValue(const std::string& key, const base::Value** value) const; - bool GetValue(const std::string& key, base::Value** value); - - // Sets a new |value| for |key|. |value| must be non-null. Returns true if the - // value changed. - bool SetValue(const std::string& key, scoped_ptr<base::Value> value); - - // Removes the value for |key| from the map. Returns true if a value was - // removed. - bool RemoveValue(const std::string& key); - - // Clears the map. - void Clear(); - - // Swaps the contents of two maps. - void Swap(PrefValueMap* other); - - iterator begin(); - iterator end(); - const_iterator begin() const; - const_iterator end() const; - - // Gets a boolean value for |key| and stores it in |value|. Returns true if - // the value was found and of the proper type. - bool GetBoolean(const std::string& key, bool* value) const; - - // Sets the value for |key| to the boolean |value|. - void SetBoolean(const std::string& key, bool value); - - // Gets a string value for |key| and stores it in |value|. Returns true if - // the value was found and of the proper type. - bool GetString(const std::string& key, std::string* value) const; - - // Sets the value for |key| to the string |value|. - void SetString(const std::string& key, const std::string& value); - - // Gets an int value for |key| and stores it in |value|. Returns true if - // the value was found and of the proper type. - bool GetInteger(const std::string& key, int* value) const; - - // Sets the value for |key| to the int |value|. - void SetInteger(const std::string& key, const int value); - - // Sets the value for |key| to the double |value|. - void SetDouble(const std::string& key, const double value); - - // Compares this value map against |other| and stores all key names that have - // different values in |differing_keys|. This includes keys that are present - // only in one of the maps. - void GetDifferingKeys(const PrefValueMap* other, - std::vector<std::string>* differing_keys) const; - - private: - Map prefs_; - - DISALLOW_COPY_AND_ASSIGN(PrefValueMap); -}; - -#endif // BASE_PREFS_PREF_VALUE_MAP_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_value_map.h" diff --git a/base/prefs/pref_value_store.h b/base/prefs/pref_value_store.h index 8ec8c59..de10c56 100644 --- a/base/prefs/pref_value_store.h +++ b/base/prefs/pref_value_store.h @@ -2,259 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_PREF_VALUE_STORE_H_ -#define BASE_PREFS_PREF_VALUE_STORE_H_ - -#include <map> -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/pref_store.h" -#include "base/values.h" - -class PrefNotifier; -class PrefStore; - -// The PrefValueStore manages various sources of values for Preferences -// (e.g., configuration policies, extensions, and user settings). It returns -// the value of a Preference from the source with the highest priority, and -// allows setting user-defined values for preferences that are not managed. -// -// Unless otherwise explicitly noted, all of the methods of this class must -// be called on the UI thread. -class BASE_PREFS_EXPORT PrefValueStore { - public: - typedef base::Callback<void(const std::string&)> PrefChangedCallback; - - // In decreasing order of precedence: - // |managed_prefs| contains all preferences from mandatory policies. - // |supervised_user_prefs| contains all preferences from supervised user - // settings, i.e. settings configured for a supervised user by their - // custodian. - // |extension_prefs| contains preference values set by extensions. - // |command_line_prefs| contains preference values set by command-line - // switches. - // |user_prefs| contains all user-set preference values. - // |recommended_prefs| contains all preferences from recommended policies. - // |default_prefs| contains application-default preference values. It must - // be non-null if any preferences are to be registered. - // - // |pref_notifier| facilitates broadcasting preference change notifications - // to the world. - PrefValueStore(PrefStore* managed_prefs, - PrefStore* supervised_user_prefs, - PrefStore* extension_prefs, - PrefStore* command_line_prefs, - PrefStore* user_prefs, - PrefStore* recommended_prefs, - PrefStore* default_prefs, - PrefNotifier* pref_notifier); - virtual ~PrefValueStore(); - - // Creates a clone of this PrefValueStore with PrefStores overwritten - // by the parameters passed, if unequal NULL. - PrefValueStore* CloneAndSpecialize(PrefStore* managed_prefs, - PrefStore* supervised_user_prefs, - PrefStore* extension_prefs, - PrefStore* command_line_prefs, - PrefStore* user_prefs, - PrefStore* recommended_prefs, - PrefStore* default_prefs, - PrefNotifier* pref_notifier); - - // A PrefValueStore can have exactly one callback that is directly - // notified of preferences changing in the store. This does not - // filter through the PrefNotifier mechanism, which may not forward - // certain changes (e.g. unregistered prefs). - void set_callback(const PrefChangedCallback& callback); - - // Gets the value for the given preference name that has the specified value - // type. Values stored in a PrefStore that have the matching |name| but - // a non-matching |type| are silently skipped. Returns true if a valid value - // was found in any of the available PrefStores. Most callers should use - // Preference::GetValue() instead of calling this method directly. - bool GetValue(const std::string& name, - base::Value::Type type, - const base::Value** out_value) const; - - // Gets the recommended value for the given preference name that has the - // specified value type. A value stored in the recommended PrefStore that has - // the matching |name| but a non-matching |type| is silently ignored. Returns - // true if a valid value was found. Most callers should use - // Preference::GetRecommendedValue() instead of calling this method directly. - bool GetRecommendedValue(const std::string& name, - base::Value::Type type, - const base::Value** out_value) const; - - // These methods return true if a preference with the given name is in the - // indicated pref store, even if that value is currently being overridden by - // a higher-priority source. - bool PrefValueInManagedStore(const std::string& name) const; - bool PrefValueInSupervisedStore(const std::string& name) const; - bool PrefValueInExtensionStore(const std::string& name) const; - bool PrefValueInUserStore(const std::string& name) const; - - // These methods return true if a preference with the given name is actually - // being controlled by the indicated pref store and not being overridden by - // a higher-priority source. - bool PrefValueFromExtensionStore(const std::string& name) const; - bool PrefValueFromUserStore(const std::string& name) const; - bool PrefValueFromRecommendedStore(const std::string& name) const; - bool PrefValueFromDefaultStore(const std::string& name) const; - - // Check whether a Preference value is modifiable by the user, i.e. whether - // there is no higher-priority source controlling it. - bool PrefValueUserModifiable(const std::string& name) const; - - // Check whether a Preference value is modifiable by an extension, i.e. - // whether there is no higher-priority source controlling it. - bool PrefValueExtensionModifiable(const std::string& name) const; - - // Update the command line PrefStore with |command_line_prefs|. - void UpdateCommandLinePrefStore(PrefStore* command_line_prefs); - - private: - // PrefStores must be listed here in order from highest to lowest priority. - // MANAGED contains all managed preference values that are provided by - // mandatory policies (e.g. Windows Group Policy or cloud policy). - // SUPERVISED_USER contains preferences that are valid for supervised users. - // EXTENSION contains preference values set by extensions. - // COMMAND_LINE contains preference values set by command-line switches. - // USER contains all user-set preference values. - // RECOMMENDED contains all preferences that are provided by recommended - // policies. - // DEFAULT contains all application default preference values. - enum PrefStoreType { - // INVALID_STORE is not associated with an actual PrefStore but used as - // an invalid marker, e.g. as a return value. - INVALID_STORE = -1, - MANAGED_STORE = 0, - SUPERVISED_USER_STORE, - EXTENSION_STORE, - COMMAND_LINE_STORE, - USER_STORE, - RECOMMENDED_STORE, - DEFAULT_STORE, - PREF_STORE_TYPE_MAX = DEFAULT_STORE - }; - - // Keeps a PrefStore reference on behalf of the PrefValueStore and monitors - // the PrefStore for changes, forwarding notifications to PrefValueStore. This - // indirection is here for the sake of disambiguating notifications from the - // individual PrefStores. - class PrefStoreKeeper : public PrefStore::Observer { - public: - PrefStoreKeeper(); - ~PrefStoreKeeper() override; - - // Takes ownership of |pref_store|. - void Initialize(PrefValueStore* store, - PrefStore* pref_store, - PrefStoreType type); - - PrefStore* store() { return pref_store_.get(); } - const PrefStore* store() const { return pref_store_.get(); } - - private: - // PrefStore::Observer implementation. - void OnPrefValueChanged(const std::string& key) override; - void OnInitializationCompleted(bool succeeded) override; - - // PrefValueStore this keeper is part of. - PrefValueStore* pref_value_store_; - - // The PrefStore managed by this keeper. - scoped_refptr<PrefStore> pref_store_; - - // Type of the pref store. - PrefStoreType type_; - - DISALLOW_COPY_AND_ASSIGN(PrefStoreKeeper); - }; - - typedef std::map<std::string, base::Value::Type> PrefTypeMap; - - // Returns true if the preference with the given name has a value in the - // given PrefStoreType, of the same value type as the preference was - // registered with. - bool PrefValueInStore(const std::string& name, PrefStoreType store) const; - - // Returns true if a preference has an explicit value in any of the - // stores in the range specified by |first_checked_store| and - // |last_checked_store|, even if that value is currently being - // overridden by a higher-priority store. - bool PrefValueInStoreRange(const std::string& name, - PrefStoreType first_checked_store, - PrefStoreType last_checked_store) const; - - // Returns the pref store type identifying the source that controls the - // Preference identified by |name|. If none of the sources has a value, - // INVALID_STORE is returned. In practice, the default PrefStore - // should always have a value for any registered preferencem, so INVALID_STORE - // indicates an error. - PrefStoreType ControllingPrefStoreForPref(const std::string& name) const; - - // Get a value from the specified |store|. - bool GetValueFromStore(const std::string& name, - PrefStoreType store, - const base::Value** out_value) const; - - // Get a value from the specified |store| if its |type| matches. - bool GetValueFromStoreWithType(const std::string& name, - base::Value::Type type, - PrefStoreType store, - const base::Value** out_value) const; - - // Called upon changes in individual pref stores in order to determine whether - // the user-visible pref value has changed. Triggers the change notification - // if the effective value of the preference has changed, or if the store - // controlling the pref has changed. - void NotifyPrefChanged(const std::string& path, PrefStoreType new_store); - - // Called from the PrefStoreKeeper implementation when a pref value for |key| - // changed in the pref store for |type|. - void OnPrefValueChanged(PrefStoreType type, const std::string& key); - - // Handle the event that the store for |type| has completed initialization. - void OnInitializationCompleted(PrefStoreType type, bool succeeded); - - // Initializes a pref store keeper. Sets up a PrefStoreKeeper that will take - // ownership of the passed |pref_store|. - void InitPrefStore(PrefStoreType type, PrefStore* pref_store); - - // Checks whether initialization is completed and tells the notifier if that - // is the case. - void CheckInitializationCompleted(); - - // Get the PrefStore pointer for the given type. May return NULL if there is - // no PrefStore for that type. - PrefStore* GetPrefStore(PrefStoreType type) { - return pref_stores_[type].store(); - } - const PrefStore* GetPrefStore(PrefStoreType type) const { - return pref_stores_[type].store(); - } - - // Keeps the PrefStore references in order of precedence. - PrefStoreKeeper pref_stores_[PREF_STORE_TYPE_MAX + 1]; - - PrefChangedCallback pref_changed_callback_; - - // Used for generating notifications. This is a weak reference, - // since the notifier is owned by the corresponding PrefService. - PrefNotifier* pref_notifier_; - - // A mapping of preference names to their registered types. - PrefTypeMap pref_types_; - - // True if not all of the PrefStores were initialized successfully. - bool initialization_failed_; - - DISALLOW_COPY_AND_ASSIGN(PrefValueStore); -}; - -#endif // BASE_PREFS_PREF_VALUE_STORE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/pref_value_store.h" diff --git a/base/prefs/scoped_user_pref_update.h b/base/prefs/scoped_user_pref_update.h index 29ad852..ce03c6a 100644 --- a/base/prefs/scoped_user_pref_update.h +++ b/base/prefs/scoped_user_pref_update.h @@ -1,108 +1,7 @@ // Copyright 2013 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. -// -// A helper class that assists preferences in firing notifications when lists -// or dictionaries are changed. -#ifndef BASE_PREFS_SCOPED_USER_PREF_UPDATE_H_ -#define BASE_PREFS_SCOPED_USER_PREF_UPDATE_H_ - -#include <string> - -#include "base/macros.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/pref_service.h" -#include "base/threading/non_thread_safe.h" -#include "base/values.h" - -class PrefService; - -namespace base { -class DictionaryValue; -class ListValue; -} - -namespace subtle { - -// Base class for ScopedUserPrefUpdateTemplate that contains the parts -// that do not depend on ScopedUserPrefUpdateTemplate's template parameter. -// -// We need this base class mostly for making it a friend of PrefService -// and getting access to PrefService::GetMutableUserPref and -// PrefService::ReportUserPrefChanged. -class BASE_PREFS_EXPORT ScopedUserPrefUpdateBase : public base::NonThreadSafe { - protected: - ScopedUserPrefUpdateBase(PrefService* service, const std::string& path); - - // Calls Notify(). - ~ScopedUserPrefUpdateBase(); - - // Sets |value_| to |service_|->GetMutableUserPref and returns it. - base::Value* GetValueOfType(base::Value::Type type); - - private: - // If |value_| is not null, triggers a notification of PrefObservers and - // resets |value_|. - void Notify(); - - // Weak pointer. - PrefService* service_; - // Path of the preference being updated. - std::string path_; - // Cache of value from user pref store (set between Get() and Notify() calls). - base::Value* value_; - - DISALLOW_COPY_AND_ASSIGN(ScopedUserPrefUpdateBase); -}; - -} // namespace subtle - -// Class to support modifications to DictionaryValues and ListValues while -// guaranteeing that PrefObservers are notified of changed values. -// -// This class may only be used on the UI thread as it requires access to the -// PrefService. -template <typename T, base::Value::Type type_enum_value> -class ScopedUserPrefUpdate : public subtle::ScopedUserPrefUpdateBase { - public: - ScopedUserPrefUpdate(PrefService* service, const std::string& path) - : ScopedUserPrefUpdateBase(service, path) {} - - // Triggers an update notification if Get() was called. - virtual ~ScopedUserPrefUpdate() {} - - // Returns a mutable |T| instance that - // - is already in the user pref store, or - // - is (silently) created and written to the user pref store if none existed - // before. - // - // Calling Get() implies that an update notification is necessary at - // destruction time. - // - // The ownership of the return value remains with the user pref store. - // Virtual so it can be overriden in subclasses that transform the value - // before returning it (for example to return a subelement of a dictionary). - virtual T* Get() { - return static_cast<T*>(GetValueOfType(type_enum_value)); - } - - T& operator*() { - return *Get(); - } - - T* operator->() { - return Get(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(ScopedUserPrefUpdate); -}; - -typedef ScopedUserPrefUpdate<base::DictionaryValue, - base::Value::TYPE_DICTIONARY> - DictionaryPrefUpdate; -typedef ScopedUserPrefUpdate<base::ListValue, base::Value::TYPE_LIST> - ListPrefUpdate; - -#endif // BASE_PREFS_SCOPED_USER_PREF_UPDATE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/scoped_user_pref_update.h" diff --git a/base/prefs/testing_pref_service.h b/base/prefs/testing_pref_service.h index 85a2879..c60b89e 100644 --- a/base/prefs/testing_pref_service.h +++ b/base/prefs/testing_pref_service.h @@ -2,195 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_TESTING_PREF_SERVICE_H_ -#define BASE_PREFS_TESTING_PREF_SERVICE_H_ - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/prefs/pref_registry.h" -#include "base/prefs/pref_service.h" -#include "base/prefs/testing_pref_store.h" - -class PrefNotifierImpl; -class PrefRegistrySimple; -class TestingPrefStore; - -// A PrefService subclass for testing. It operates totally in memory and -// provides additional API for manipulating preferences at the different levels -// (managed, extension, user) conveniently. -// -// Use this via its specializations, e.g. TestingPrefServiceSimple. -template <class SuperPrefService, class ConstructionPrefRegistry> -class TestingPrefServiceBase : public SuperPrefService { - public: - virtual ~TestingPrefServiceBase(); - - // Read the value of a preference from the managed layer. Returns NULL if the - // preference is not defined at the managed layer. - const base::Value* GetManagedPref(const std::string& path) const; - - // Set a preference on the managed layer and fire observers if the preference - // changed. Assumes ownership of |value|. - void SetManagedPref(const std::string& path, base::Value* value); - - // Clear the preference on the managed layer and fire observers if the - // preference has been defined previously. - void RemoveManagedPref(const std::string& path); - - // Similar to the above, but for user preferences. - const base::Value* GetUserPref(const std::string& path) const; - void SetUserPref(const std::string& path, base::Value* value); - void RemoveUserPref(const std::string& path); - - // Similar to the above, but for recommended policy preferences. - const base::Value* GetRecommendedPref(const std::string& path) const; - void SetRecommendedPref(const std::string& path, base::Value* value); - void RemoveRecommendedPref(const std::string& path); - - // Do-nothing implementation for TestingPrefService. - static void HandleReadError(PersistentPrefStore::PrefReadError error) {} - - protected: - TestingPrefServiceBase( - TestingPrefStore* managed_prefs, - TestingPrefStore* user_prefs, - TestingPrefStore* recommended_prefs, - ConstructionPrefRegistry* pref_registry, - PrefNotifierImpl* pref_notifier); - - private: - // Reads the value of the preference indicated by |path| from |pref_store|. - // Returns NULL if the preference was not found. - const base::Value* GetPref(TestingPrefStore* pref_store, - const std::string& path) const; - - // Sets the value for |path| in |pref_store|. - void SetPref(TestingPrefStore* pref_store, - const std::string& path, - base::Value* value); - - // Removes the preference identified by |path| from |pref_store|. - void RemovePref(TestingPrefStore* pref_store, const std::string& path); - - // Pointers to the pref stores our value store uses. - scoped_refptr<TestingPrefStore> managed_prefs_; - scoped_refptr<TestingPrefStore> user_prefs_; - scoped_refptr<TestingPrefStore> recommended_prefs_; - - DISALLOW_COPY_AND_ASSIGN(TestingPrefServiceBase); -}; - -// Test version of PrefService. -class TestingPrefServiceSimple - : public TestingPrefServiceBase<PrefService, PrefRegistry> { - public: - TestingPrefServiceSimple(); - ~TestingPrefServiceSimple() override; - - // This is provided as a convenience for registering preferences on - // an existing TestingPrefServiceSimple instance. On a production - // PrefService you would do all registrations before constructing - // it, passing it a PrefRegistry via its constructor (or via - // e.g. PrefServiceFactory). - PrefRegistrySimple* registry(); - - private: - DISALLOW_COPY_AND_ASSIGN(TestingPrefServiceSimple); -}; - -template<> -TestingPrefServiceBase<PrefService, PrefRegistry>::TestingPrefServiceBase( - TestingPrefStore* managed_prefs, - TestingPrefStore* user_prefs, - TestingPrefStore* recommended_prefs, - PrefRegistry* pref_registry, - PrefNotifierImpl* pref_notifier); - -template<class SuperPrefService, class ConstructionPrefRegistry> -TestingPrefServiceBase< - SuperPrefService, ConstructionPrefRegistry>::~TestingPrefServiceBase() { -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -const base::Value* TestingPrefServiceBase< - SuperPrefService, - ConstructionPrefRegistry>::GetManagedPref(const std::string& path) const { - return GetPref(managed_prefs_.get(), path); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: - SetManagedPref(const std::string& path, base::Value* value) { - SetPref(managed_prefs_.get(), path, value); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: - RemoveManagedPref(const std::string& path) { - RemovePref(managed_prefs_.get(), path); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -const base::Value* -TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>::GetUserPref( - const std::string& path) const { - return GetPref(user_prefs_.get(), path); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: - SetUserPref(const std::string& path, base::Value* value) { - SetPref(user_prefs_.get(), path, value); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: - RemoveUserPref(const std::string& path) { - RemovePref(user_prefs_.get(), path); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -const base::Value* -TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: - GetRecommendedPref(const std::string& path) const { - return GetPref(recommended_prefs_, path); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: - SetRecommendedPref(const std::string& path, base::Value* value) { - SetPref(recommended_prefs_.get(), path, value); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: - RemoveRecommendedPref(const std::string& path) { - RemovePref(recommended_prefs_.get(), path); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -const base::Value* -TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>::GetPref( - TestingPrefStore* pref_store, - const std::string& path) const { - const base::Value* res; - return pref_store->GetValue(path, &res) ? res : NULL; -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: - SetPref(TestingPrefStore* pref_store, - const std::string& path, - base::Value* value) { - pref_store->SetValue(path, make_scoped_ptr(value), - WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); -} - -template <class SuperPrefService, class ConstructionPrefRegistry> -void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: - RemovePref(TestingPrefStore* pref_store, const std::string& path) { - pref_store->RemoveValue(path, WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); -} - -#endif // BASE_PREFS_TESTING_PREF_SERVICE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/testing_pref_service.h" diff --git a/base/prefs/testing_pref_store.h b/base/prefs/testing_pref_store.h index 713e69a..297aa11 100644 --- a/base/prefs/testing_pref_store.h +++ b/base/prefs/testing_pref_store.h @@ -2,113 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_TESTING_PREF_STORE_H_ -#define BASE_PREFS_TESTING_PREF_STORE_H_ - -#include <stdint.h> - -#include <string> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/observer_list.h" -#include "base/prefs/persistent_pref_store.h" -#include "base/prefs/pref_value_map.h" - -// |TestingPrefStore| is a preference store implementation that allows tests to -// explicitly manipulate the contents of the store, triggering notifications -// where appropriate. -class TestingPrefStore : public PersistentPrefStore { - public: - TestingPrefStore(); - - // Overriden from PrefStore. - bool GetValue(const std::string& key, - const base::Value** result) const override; - void AddObserver(PrefStore::Observer* observer) override; - void RemoveObserver(PrefStore::Observer* observer) override; - bool HasObservers() const override; - bool IsInitializationComplete() const override; - - // PersistentPrefStore overrides: - bool GetMutableValue(const std::string& key, base::Value** result) override; - void ReportValueChanged(const std::string& key, uint32_t flags) override; - void SetValue(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) override; - void SetValueSilently(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) override; - void RemoveValue(const std::string& key, uint32_t flags) override; - bool ReadOnly() const override; - PrefReadError GetReadError() const override; - PersistentPrefStore::PrefReadError ReadPrefs() override; - void ReadPrefsAsync(ReadErrorDelegate* error_delegate) override; - void CommitPendingWrite() override; - void SchedulePendingLossyWrites() override; - - // Marks the store as having completed initialization. - void SetInitializationCompleted(); - - // Used for tests to trigger notifications explicitly. - void NotifyPrefValueChanged(const std::string& key); - void NotifyInitializationCompleted(); - - // Some convenience getters/setters. - void SetString(const std::string& key, const std::string& value); - void SetInteger(const std::string& key, int value); - void SetBoolean(const std::string& key, bool value); - - bool GetString(const std::string& key, std::string* value) const; - bool GetInteger(const std::string& key, int* value) const; - bool GetBoolean(const std::string& key, bool* value) const; - - // Determines whether ReadPrefsAsync completes immediately. Defaults to false - // (non-blocking). To block, invoke this with true (blocking) before the call - // to ReadPrefsAsync. To unblock, invoke again with false (non-blocking) after - // the call to ReadPrefsAsync. - void SetBlockAsyncRead(bool block_async_read); - - // Getter and Setter methods for setting and getting the state of the - // |TestingPrefStore|. - virtual void set_read_only(bool read_only); - void set_read_success(bool read_success); - void set_read_error(PersistentPrefStore::PrefReadError read_error); - bool committed() { return committed_; } - - protected: - ~TestingPrefStore() override; - - private: - // Stores the preference values. - PrefValueMap prefs_; - - // Flag that indicates if the PrefStore is read-only - bool read_only_; - - // The result to pass to PrefStore::Observer::OnInitializationCompleted - bool read_success_; - - // The result to return from ReadPrefs or ReadPrefsAsync. - PersistentPrefStore::PrefReadError read_error_; - - // Whether a call to ReadPrefsAsync should block. - bool block_async_read_; - - // Whether there is a pending call to ReadPrefsAsync. - bool pending_async_read_; - - // Whether initialization has been completed. - bool init_complete_; - - // Whether the store contents have been committed to disk since the last - // mutation. - bool committed_; - - scoped_ptr<ReadErrorDelegate> error_delegate_; - base::ObserverList<PrefStore::Observer, true> observers_; - - DISALLOW_COPY_AND_ASSIGN(TestingPrefStore); -}; - -#endif // BASE_PREFS_TESTING_PREF_STORE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/testing_pref_store.h" diff --git a/base/prefs/value_map_pref_store.h b/base/prefs/value_map_pref_store.h index eac785d..4373ff7 100644 --- a/base/prefs/value_map_pref_store.h +++ b/base/prefs/value_map_pref_store.h @@ -2,56 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_VALUE_MAP_PREF_STORE_H_ -#define BASE_PREFS_VALUE_MAP_PREF_STORE_H_ - -#include <stdint.h> - -#include <map> -#include <string> - -#include "base/macros.h" -#include "base/observer_list.h" -#include "base/prefs/base_prefs_export.h" -#include "base/prefs/pref_value_map.h" -#include "base/prefs/writeable_pref_store.h" - -// A basic PrefStore implementation that uses a simple name-value map for -// storing the preference values. -class BASE_PREFS_EXPORT ValueMapPrefStore : public WriteablePrefStore { - public: - ValueMapPrefStore(); - - // PrefStore overrides: - bool GetValue(const std::string& key, - const base::Value** value) const override; - void AddObserver(PrefStore::Observer* observer) override; - void RemoveObserver(PrefStore::Observer* observer) override; - bool HasObservers() const override; - - // WriteablePrefStore overrides: - void SetValue(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) override; - void RemoveValue(const std::string& key, uint32_t flags) override; - bool GetMutableValue(const std::string& key, base::Value** value) override; - void ReportValueChanged(const std::string& key, uint32_t flags) override; - void SetValueSilently(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) override; - - protected: - ~ValueMapPrefStore() override; - - // Notify observers about the initialization completed event. - void NotifyInitializationCompleted(); - - private: - PrefValueMap prefs_; - - base::ObserverList<PrefStore::Observer, true> observers_; - - DISALLOW_COPY_AND_ASSIGN(ValueMapPrefStore); -}; - -#endif // BASE_PREFS_VALUE_MAP_PREF_STORE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/value_map_pref_store.h" diff --git a/base/prefs/writeable_pref_store.h b/base/prefs/writeable_pref_store.h index f7da279..69bd2cb 100644 --- a/base/prefs/writeable_pref_store.h +++ b/base/prefs/writeable_pref_store.h @@ -2,71 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_PREFS_WRITEABLE_PREF_STORE_H_ -#define BASE_PREFS_WRITEABLE_PREF_STORE_H_ - -#include <stdint.h> - -#include <string> - -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "base/prefs/pref_store.h" - -namespace base { -class Value; -} - -// A pref store that can be written to as well as read from. -class BASE_PREFS_EXPORT WriteablePrefStore : public PrefStore { - public: - // PrefWriteFlags can be used to change the way a pref will be written to - // storage. - enum PrefWriteFlags : uint32_t { - // No flags are specified. - DEFAULT_PREF_WRITE_FLAGS = 0, - - // This marks the pref as "lossy". There is no strict time guarantee on when - // a lossy pref will be persisted to permanent storage when it is modified. - LOSSY_PREF_WRITE_FLAG = 1 << 1 - }; - - WriteablePrefStore() {} - - // Sets a |value| for |key| in the store. |value| must be non-NULL. |flags| is - // a bitmask of PrefWriteFlags. - virtual void SetValue(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) = 0; - - // Removes the value for |key|. - virtual void RemoveValue(const std::string& key, uint32_t flags) = 0; - - // Equivalent to PrefStore::GetValue but returns a mutable value. - virtual bool GetMutableValue(const std::string& key, - base::Value** result) = 0; - - // Triggers a value changed notification. This function needs to be called - // if one retrieves a list or dictionary with GetMutableValue and change its - // value. SetValue takes care of notifications itself. Note that - // ReportValueChanged will trigger notifications even if nothing has changed. - // |flags| is a bitmask of PrefWriteFlags. - virtual void ReportValueChanged(const std::string& key, uint32_t flags) = 0; - - // Same as SetValue, but doesn't generate notifications. This is used by - // PrefService::GetMutableUserPref() in order to put empty entries - // into the user pref store. Using SetValue is not an option since existing - // tests rely on the number of notifications generated. |flags| is a bitmask - // of PrefWriteFlags. - virtual void SetValueSilently(const std::string& key, - scoped_ptr<base::Value> value, - uint32_t flags) = 0; - - protected: - ~WriteablePrefStore() override {} - - private: - DISALLOW_COPY_AND_ASSIGN(WriteablePrefStore); -}; - -#endif // BASE_PREFS_WRITEABLE_PREF_STORE_H_ +// TODO(brettw) remove this forwarding header when prefs is completely moved to +// components. +#include "components/prefs/writeable_pref_store.h" diff --git a/base/test/data/prefs/invalid.json b/base/test/data/prefs/invalid.json deleted file mode 100644 index 43392a9..0000000 --- a/base/test/data/prefs/invalid.json +++ /dev/null @@ -1 +0,0 @@ -!@#$%^&
\ No newline at end of file diff --git a/base/test/data/prefs/read.json b/base/test/data/prefs/read.json deleted file mode 100644 index ea578a4..0000000 --- a/base/test/data/prefs/read.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "homepage": "http://www.cnn.com", - "some_directory": "/usr/local/", - "tabs": { - "new_windows_in_tabs": true, - "max_tabs": 20 - } -} diff --git a/base/test/data/prefs/write.golden.json b/base/test/data/prefs/write.golden.json deleted file mode 100644 index fb1fff1..0000000 --- a/base/test/data/prefs/write.golden.json +++ /dev/null @@ -1 +0,0 @@ -{"homepage":"http://www.cnn.com","long_int":{"pref":"214748364842"},"some_directory":"/usr/sbin/","tabs":{"max_tabs":10,"new_windows_in_tabs":false}}
\ No newline at end of file diff --git a/chrome/chrome_common.gypi b/chrome/chrome_common.gypi index 75a8e2a..3941486 100644 --- a/chrome/chrome_common.gypi +++ b/chrome/chrome_common.gypi @@ -317,7 +317,6 @@ 'safe_browsing_proto', '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/base.gyp:base_i18n', - '<(DEPTH)/base/base.gyp:base_prefs', '<(DEPTH)/base/base.gyp:base_static', '<(DEPTH)/chrome/chrome_features.gyp:chrome_common_features', '<(DEPTH)/chrome/chrome_resources.gyp:chrome_resources', @@ -342,6 +341,7 @@ '<(DEPTH)/components/components.gyp:variations', '<(DEPTH)/components/components.gyp:version_info', '<(DEPTH)/components/components_strings.gyp:components_strings', + '<(DEPTH)/components/prefs/prefs.gyp:prefs', '<(DEPTH)/components/url_formatter/url_formatter.gyp:url_formatter', '<(DEPTH)/content/content.gyp:content_common', '<(DEPTH)/crypto/crypto.gyp:crypto', diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi index d0e2f5d..ec1344f 100644 --- a/chrome/chrome_tests_unit.gypi +++ b/chrome/chrome_tests_unit.gypi @@ -1677,7 +1677,6 @@ 'chrome_resources.gyp:chrome_strings', 'chrome_resources.gyp:theme_resources', 'common', - '../base/base.gyp:base_prefs_test_support', '../base/base.gyp:test_support_base', '../components/components.gyp:bookmarks_test_support', '../components/components.gyp:browser_sync_browser_test_support', @@ -1700,6 +1699,7 @@ '../components/components.gyp:toolbar_test_support', '../components/components.gyp:update_client_test_support', '../components/components.gyp:user_prefs_tracked_test_support', + '../components/prefs/prefs.gyp:prefs_test_support', '../content/content.gyp:content_app_both', '../content/content_shell_and_tests.gyp:test_support_content', '../net/net.gyp:net', diff --git a/chromeos/chromeos.gyp b/chromeos/chromeos.gyp index 2aeeec8..c0f9ab5 100644 --- a/chromeos/chromeos.gyp +++ b/chromeos/chromeos.gyp @@ -511,7 +511,6 @@ 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', - '../base/base.gyp:base_prefs', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../build/linux/system.gyp:dbus', '../build/linux/system.gyp:ssl', @@ -520,6 +519,7 @@ '../components/components.gyp:onc_component', '../components/components.gyp:proxy_config', '../components/components.gyp:signin_core_account_id', + '../components/prefs/prefs.gyp:prefs', '../crypto/crypto.gyp:crypto', '../dbus/dbus.gyp:dbus', '../google_apis/google_apis.gyp:google_apis', @@ -644,13 +644,13 @@ 'target_name': 'chromeos_unittests', 'type': 'executable', 'dependencies': [ - '../base/base.gyp:base_prefs_test_support', '../base/base.gyp:run_all_unittests', '../base/base.gyp:test_support_base', '../build/linux/system.gyp:dbus', '../build/linux/system.gyp:ssl', '../components/components.gyp:onc_component', '../components/components.gyp:proxy_config', + '../components/prefs/prefs.gyp:prefs_test_support', '../crypto/crypto.gyp:crypto', '../crypto/crypto.gyp:crypto_test_support', '../dbus/dbus.gyp:dbus_test_support', diff --git a/components/BUILD.gn b/components/BUILD.gn index ad3fab2..0a6c5bf 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn @@ -63,6 +63,7 @@ test("components_unittests") { "//components/network_time:unit_tests", "//components/open_from_clipboard:unit_tests", "//components/os_crypt:unit_tests", + "//components/prefs:unit_tests", "//components/proxy_config:unit_tests", "//components/security_state:unit_tests", "//components/sessions:unit_tests", diff --git a/components/autofill.gypi b/components/autofill.gypi index 93d634f..ca9e8e0 100644 --- a/components/autofill.gypi +++ b/components/autofill.gypi @@ -65,7 +65,6 @@ 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', - '../base/base.gyp:base_prefs', '../google_apis/google_apis.gyp:google_apis', '../net/net.gyp:net', '../skia/skia.gyp:skia', @@ -91,6 +90,7 @@ 'keyed_service_core', 'os_crypt', 'pref_registry', + 'prefs/prefs.gyp:prefs', 'rappor', 'signin_core_browser', 'signin_core_common', @@ -277,7 +277,6 @@ 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../base/base.gyp:test_support_base', '../skia/skia.gyp:skia', '../testing/gtest.gyp:gtest', @@ -285,6 +284,7 @@ 'autofill_core_browser', 'os_crypt', 'pref_registry', + 'prefs/prefs.gyp:prefs', 'rappor', 'signin_core_browser_test_support', ], @@ -380,7 +380,6 @@ 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', - '../base/base.gyp:base_prefs', '../content/content.gyp:content_browser', '../content/content.gyp:content_common', '../google_apis/google_apis.gyp:google_apis', @@ -403,6 +402,7 @@ 'components_resources.gyp:components_resources', 'components_strings.gyp:components_strings', 'os_crypt', + 'prefs/prefs.gyp:prefs', 'user_prefs', 'webdata_common', ], diff --git a/components/components_tests.gyp b/components/components_tests.gyp index e004816..22e2568 100644 --- a/components/components_tests.gyp +++ b/components/components_tests.gyp @@ -586,6 +586,18 @@ 'proxy_config/proxy_config_dictionary_unittest.cc', 'proxy_config/proxy_prefs_unittest.cc', ], + 'prefs_unittest_sources': [ + 'prefs/default_pref_store_unittest.cc', + 'prefs/json_pref_store_unittest.cc', + 'prefs/overlay_user_pref_store_unittest.cc', + 'prefs/pref_change_registrar_unittest.cc', + 'prefs/pref_member_unittest.cc', + 'prefs/pref_notifier_impl_unittest.cc', + 'prefs/pref_service_unittest.cc', + 'prefs/pref_value_map_unittest.cc', + 'prefs/pref_value_store_unittest.cc', + 'prefs/scoped_user_pref_update_unittest.cc', + ], 'query_parser_unittest_sources': [ 'query_parser/query_parser_unittest.cc', 'query_parser/snippet_unittest.cc', @@ -939,6 +951,7 @@ '<@(password_manager_unittest_sources)', '<@(precache_unittest_sources)', '<@(proxy_config_unittest_sources)', + '<@(prefs_unittest_sources)', '<@(query_parser_unittest_sources)', '<@(rappor_unittest_sources)', '<@(search_engines_unittest_sources)', @@ -971,7 +984,6 @@ ], 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs_test_support', '../base/base.gyp:test_support_base', '../google_apis/google_apis.gyp:google_apis_test_support', '../jingle/jingle.gyp:notifier_test_util', @@ -1106,6 +1118,8 @@ 'components_strings.gyp:components_strings', 'components_tests_pak', 'mime_util/mime_util.gyp:mime_util', + 'prefs/prefs.gyp:prefs', + 'prefs/prefs.gyp:prefs_test_support', 'url_formatter/url_formatter.gyp:url_formatter', ], 'conditions': [ diff --git a/components/content_settings.gypi b/components/content_settings.gypi index fdca4ba..c547bad 100644 --- a/components/content_settings.gypi +++ b/components/content_settings.gypi @@ -10,11 +10,11 @@ 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../net/net.gyp:net', '../url/url.gyp:url_lib', 'content_settings_core_common', 'pref_registry', + 'prefs/prefs.gyp:prefs', 'url_formatter/url_formatter.gyp:url_formatter', ], 'variables': { 'enable_wexit_time_destructors': 1, }, diff --git a/components/dom_distiller.gypi b/components/dom_distiller.gypi index 9b74614..5156269 100644 --- a/components/dom_distiller.gypi +++ b/components/dom_distiller.gypi @@ -54,7 +54,6 @@ 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../skia/skia.gyp:skia', '../sync/sync.gyp:sync', '../third_party/dom_distiller_js/dom_distiller_js.gyp:dom_distiller_js_proto', @@ -63,6 +62,7 @@ 'components_resources.gyp:components_resources', 'components_strings.gyp:components_strings', 'dom_distiller_protos', + 'prefs/prefs.gyp:prefs', 'pref_registry', 'variations', ], diff --git a/components/domain_reliability.gypi b/components/domain_reliability.gypi index eae16ab..3a6155a 100644 --- a/components/domain_reliability.gypi +++ b/components/domain_reliability.gypi @@ -13,9 +13,9 @@ 'type': '<(component)', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../components/components.gyp:data_use_measurement_core', '../components/components.gyp:keyed_service_core', + '../components/prefs/prefs.gyp:prefs', '../content/content.gyp:content_browser', '../net/net.gyp:net', '../url/url.gyp:url_lib', diff --git a/components/flags_ui.gypi b/components/flags_ui.gypi index f4c6275..31e3653 100644 --- a/components/flags_ui.gypi +++ b/components/flags_ui.gypi @@ -13,8 +13,8 @@ ], 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../components/components_strings.gyp:components_strings', + '../components/prefs/prefs.gyp:prefs', '../ui/base/ui_base.gyp:ui_base', 'flags_ui_switches', 'pref_registry', diff --git a/components/history.gypi b/components/history.gypi index a8c5091..20f647c 100644 --- a/components/history.gypi +++ b/components/history.gypi @@ -14,7 +14,6 @@ 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', - '../base/base.gyp:base_prefs', '../google_apis/google_apis.gyp:google_apis', '../net/net.gyp:net', '../skia/skia.gyp:skia', @@ -27,6 +26,7 @@ 'favicon_base', 'history_core_common', 'keyed_service_core', + 'prefs/prefs.gyp:prefs', 'query_parser', 'signin_core_browser', 'sync_driver', diff --git a/components/invalidation.gypi b/components/invalidation.gypi index 662a077..0ab96ae 100644 --- a/components/invalidation.gypi +++ b/components/invalidation.gypi @@ -50,7 +50,6 @@ 'invalidation_public', '../base/base.gyp:base', '../base/base.gyp:base_i18n', - '../base/base.gyp:base_prefs', '../google_apis/google_apis.gyp:google_apis', '../jingle/jingle.gyp:notifier', '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_proto_cpp', @@ -58,6 +57,7 @@ 'gcm_driver', 'keyed_service_core', 'pref_registry', + 'prefs/prefs.gyp:prefs', 'signin_core_browser', ], 'export_dependent_settings': [ diff --git a/components/keyed_service.gypi b/components/keyed_service.gypi index 26bfc05..5bfef70 100644 --- a/components/keyed_service.gypi +++ b/components/keyed_service.gypi @@ -18,7 +18,7 @@ 'msvs_disabled_warnings': [ 4267, ], 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', + 'prefs/prefs.gyp:prefs', 'user_prefs', ], 'sources': [ diff --git a/components/metrics.gypi b/components/metrics.gypi index 643c9df..b90ebc6 100644 --- a/components/metrics.gypi +++ b/components/metrics.gypi @@ -14,9 +14,9 @@ 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', - '../base/base.gyp:base_prefs', '../third_party/zlib/google/zip.gyp:compression_utils', 'component_metrics_proto', + 'prefs/prefs.gyp:prefs', 'variations', ], 'export_dependent_settings': [ diff --git a/components/policy/policy_browser.gypi b/components/policy/policy_browser.gypi index 9012fbc..6b2b6c0 100644 --- a/components/policy/policy_browser.gypi +++ b/components/policy/policy_browser.gypi @@ -5,7 +5,6 @@ { 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../net/net.gyp:net', '../ui/base/ui_base.gyp:ui_base', @@ -15,6 +14,7 @@ 'components_strings.gyp:components_strings', 'keyed_service_core', 'pref_registry', + 'prefs/prefs.gyp:prefs', 'url_matcher', ], 'defines': [ diff --git a/components/policy/policy_common.gypi b/components/policy/policy_common.gypi index 55573e6..e9c7cb5 100644 --- a/components/policy/policy_common.gypi +++ b/components/policy/policy_common.gypi @@ -16,7 +16,6 @@ 'conditions': [ ['configuration_policy==1', { 'dependencies': [ - '../base/base.gyp:base_prefs', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../google_apis/google_apis.gyp:google_apis', '../net/net.gyp:net', @@ -26,6 +25,7 @@ 'data_use_measurement_core', 'json_schema', 'policy', + 'prefs/prefs.gyp:prefs', ], 'sources': [ 'core/common/async_policy_loader.cc', diff --git a/components/pref_registry.gypi b/components/pref_registry.gypi index 5ff32c3..0499e19 100644 --- a/components/pref_registry.gypi +++ b/components/pref_registry.gypi @@ -10,8 +10,8 @@ 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', + 'prefs/prefs.gyp:prefs', ], 'include_dirs': [ '..', @@ -27,7 +27,7 @@ 'type': 'static_library', 'dependencies': [ 'pref_registry', - '../base/base.gyp:base_prefs_test_support', + 'prefs/prefs.gyp:prefs_test_support', ], 'include_dirs': [ '..', diff --git a/components/prefs/BUILD.gn b/components/prefs/BUILD.gn new file mode 100644 index 0000000..9b89e32 --- /dev/null +++ b/components/prefs/BUILD.gn @@ -0,0 +1,106 @@ +# Copyright 2015 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. + +component("prefs") { + sources = [ + "default_pref_store.cc", + "default_pref_store.h", + "json_pref_store.cc", + "json_pref_store.h", + "overlay_user_pref_store.cc", + "overlay_user_pref_store.h", + "pref_change_registrar.cc", + "pref_change_registrar.h", + "pref_member.cc", + "pref_member.h", + "pref_notifier_impl.cc", + "pref_notifier_impl.h", + "pref_registry.cc", + "pref_registry.h", + "pref_registry_simple.cc", + "pref_registry_simple.h", + "pref_service.cc", + "pref_service.h", + "pref_service_factory.cc", + "pref_service_factory.h", + "pref_store.cc", + "pref_store.h", + "pref_value_map.cc", + "pref_value_map.h", + "pref_value_store.cc", + "pref_value_store.h", + "scoped_user_pref_update.cc", + "scoped_user_pref_update.h", + "value_map_pref_store.cc", + "value_map_pref_store.h", + ] + if (!is_ios) { + sources += [ + "base_prefs_export.h", + "persistent_pref_store.h", + "pref_filter.h", + "pref_notifier.h", + "pref_observer.h", + "writeable_pref_store.h", + ] + } + + defines = [ "BASE_PREFS_IMPLEMENTATION" ] + + deps = [ + "//base", + ] + + if (!is_debug) { + configs -= [ "//build/config/compiler:default_optimization" ] + configs += [ "//build/config/compiler:optimize_max" ] + } +} + +source_set("test_support") { + testonly = true + sources = [ + "mock_pref_change_callback.cc", + "mock_pref_change_callback.h", + "pref_store_observer_mock.cc", + "pref_store_observer_mock.h", + "testing_pref_service.cc", + "testing_pref_service.h", + "testing_pref_store.cc", + "testing_pref_store.h", + ] + + public_deps = [ + ":prefs", + ] + deps = [ + "//base", + "//testing/gmock", + "//testing/gtest", + ] +} + +source_set("unit_tests") { + testonly = true + sources = [ + "default_pref_store_unittest.cc", + "json_pref_store_unittest.cc", + "overlay_user_pref_store_unittest.cc", + "pref_change_registrar_unittest.cc", + "pref_member_unittest.cc", + "pref_notifier_impl_unittest.cc", + "pref_service_unittest.cc", + "pref_value_map_unittest.cc", + "pref_value_store_unittest.cc", + "scoped_user_pref_update_unittest.cc", + ] + + deps = [ + ":test_support", + "//base", + "//base/test:test_support", + "//testing/gmock", + "//testing/gtest", + ] +} diff --git a/base/prefs/OWNERS b/components/prefs/OWNERS index 2d87038..2d87038 100644 --- a/base/prefs/OWNERS +++ b/components/prefs/OWNERS diff --git a/components/prefs/base_prefs_export.h b/components/prefs/base_prefs_export.h new file mode 100644 index 0000000..3d207db --- /dev/null +++ b/components/prefs/base_prefs_export.h @@ -0,0 +1,29 @@ +// 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 BASE_PREFS_BASE_PREFS_EXPORT_H_ +#define BASE_PREFS_BASE_PREFS_EXPORT_H_ + +#if defined(COMPONENT_BUILD) +#if defined(WIN32) + +#if defined(BASE_PREFS_IMPLEMENTATION) +#define BASE_PREFS_EXPORT __declspec(dllexport) +#else +#define BASE_PREFS_EXPORT __declspec(dllimport) +#endif // defined(BASE_PREFS_IMPLEMENTATION) + +#else // defined(WIN32) +#if defined(BASE_PREFS_IMPLEMENTATION) +#define BASE_PREFS_EXPORT __attribute__((visibility("default"))) +#else +#define BASE_PREFS_EXPORT +#endif +#endif + +#else // defined(COMPONENT_BUILD) +#define BASE_PREFS_EXPORT +#endif + +#endif // BASE_PREFS_BASE_PREFS_EXPORT_H_ diff --git a/base/prefs/default_pref_store.cc b/components/prefs/default_pref_store.cc index b08ef7a..b08ef7a 100644 --- a/base/prefs/default_pref_store.cc +++ b/components/prefs/default_pref_store.cc diff --git a/components/prefs/default_pref_store.h b/components/prefs/default_pref_store.h new file mode 100644 index 0000000..ac5364d --- /dev/null +++ b/components/prefs/default_pref_store.h @@ -0,0 +1,53 @@ +// 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 BASE_PREFS_DEFAULT_PREF_STORE_H_ +#define BASE_PREFS_DEFAULT_PREF_STORE_H_ + +#include <string> + +#include "base/macros.h" +#include "base/observer_list.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/pref_store.h" +#include "base/prefs/pref_value_map.h" +#include "base/values.h" + +// Used within a PrefRegistry to keep track of default preference values. +class BASE_PREFS_EXPORT DefaultPrefStore : public PrefStore { + public: + typedef PrefValueMap::const_iterator const_iterator; + + DefaultPrefStore(); + + // PrefStore implementation: + bool GetValue(const std::string& key, + const base::Value** result) const override; + void AddObserver(PrefStore::Observer* observer) override; + void RemoveObserver(PrefStore::Observer* observer) override; + bool HasObservers() const override; + + // Sets a |value| for |key|. Should only be called if a value has not been + // set yet; otherwise call ReplaceDefaultValue(). + void SetDefaultValue(const std::string& key, scoped_ptr<base::Value> value); + + // Replaces the the value for |key| with a new value. Should only be called + // if a value has alreday been set; otherwise call SetDefaultValue(). + void ReplaceDefaultValue(const std::string& key, + scoped_ptr<base::Value> value); + + const_iterator begin() const; + const_iterator end() const; + + private: + ~DefaultPrefStore() override; + + PrefValueMap prefs_; + + base::ObserverList<PrefStore::Observer, true> observers_; + + DISALLOW_COPY_AND_ASSIGN(DefaultPrefStore); +}; + +#endif // BASE_PREFS_DEFAULT_PREF_STORE_H_ diff --git a/base/prefs/default_pref_store_unittest.cc b/components/prefs/default_pref_store_unittest.cc index 597ca55..597ca55 100644 --- a/base/prefs/default_pref_store_unittest.cc +++ b/components/prefs/default_pref_store_unittest.cc diff --git a/base/prefs/json_pref_store.cc b/components/prefs/json_pref_store.cc index ffc750e..ffc750e 100644 --- a/base/prefs/json_pref_store.cc +++ b/components/prefs/json_pref_store.cc diff --git a/components/prefs/json_pref_store.h b/components/prefs/json_pref_store.h new file mode 100644 index 0000000..6342977 --- /dev/null +++ b/components/prefs/json_pref_store.h @@ -0,0 +1,229 @@ +// 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 BASE_PREFS_JSON_PREF_STORE_H_ +#define BASE_PREFS_JSON_PREF_STORE_H_ + +#include <stdint.h> + +#include <set> +#include <string> + +#include "base/callback_forward.h" +#include "base/compiler_specific.h" +#include "base/files/file_path.h" +#include "base/files/important_file_writer.h" +#include "base/gtest_prod_util.h" +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/observer_list.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/persistent_pref_store.h" +#include "base/threading/non_thread_safe.h" + +class PrefFilter; + +namespace base { +class Clock; +class DictionaryValue; +class FilePath; +class HistogramBase; +class JsonPrefStoreLossyWriteTest; +class SequencedTaskRunner; +class SequencedWorkerPool; +class Value; +FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestBasic); +FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestSinglePeriod); +FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestMultiplePeriods); +FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestPeriodWithGaps); +} + +// A writable PrefStore implementation that is used for user preferences. +class BASE_PREFS_EXPORT JsonPrefStore + : public PersistentPrefStore, + public base::ImportantFileWriter::DataSerializer, + public base::SupportsWeakPtr<JsonPrefStore>, + public base::NonThreadSafe { + public: + struct ReadResult; + + // Returns instance of SequencedTaskRunner which guarantees that file + // operations on the same file will be executed in sequenced order. + static scoped_refptr<base::SequencedTaskRunner> GetTaskRunnerForFile( + const base::FilePath& pref_filename, + base::SequencedWorkerPool* worker_pool); + + // Same as the constructor below with no alternate filename. + JsonPrefStore( + const base::FilePath& pref_filename, + const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner, + scoped_ptr<PrefFilter> pref_filter); + + // |sequenced_task_runner| must be a shutdown-blocking task runner, ideally + // created by the GetTaskRunnerForFile() method above. + // |pref_filename| is the path to the file to read prefs from. + // |pref_alternate_filename| is the path to an alternate file which the + // desired prefs may have previously been written to. If |pref_filename| + // doesn't exist and |pref_alternate_filename| does, |pref_alternate_filename| + // will be moved to |pref_filename| before the read occurs. + JsonPrefStore( + const base::FilePath& pref_filename, + const base::FilePath& pref_alternate_filename, + const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner, + scoped_ptr<PrefFilter> pref_filter); + + // PrefStore overrides: + bool GetValue(const std::string& key, + const base::Value** result) const override; + void AddObserver(PrefStore::Observer* observer) override; + void RemoveObserver(PrefStore::Observer* observer) override; + bool HasObservers() const override; + bool IsInitializationComplete() const override; + + // PersistentPrefStore overrides: + bool GetMutableValue(const std::string& key, base::Value** result) override; + void SetValue(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) override; + void SetValueSilently(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) override; + void RemoveValue(const std::string& key, uint32_t flags) override; + bool ReadOnly() const override; + PrefReadError GetReadError() const override; + // Note this method may be asynchronous if this instance has a |pref_filter_| + // in which case it will return PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE. + // See details in pref_filter.h. + PrefReadError ReadPrefs() override; + void ReadPrefsAsync(ReadErrorDelegate* error_delegate) override; + void CommitPendingWrite() override; + void SchedulePendingLossyWrites() override; + void ReportValueChanged(const std::string& key, uint32_t flags) override; + + // Just like RemoveValue(), but doesn't notify observers. Used when doing some + // cleanup that shouldn't otherwise alert observers. + void RemoveValueSilently(const std::string& key, uint32_t flags); + + // Registers |on_next_successful_write| to be called once, on the next + // successful write event of |writer_|. + void RegisterOnNextSuccessfulWriteCallback( + const base::Closure& on_next_successful_write); + + private: + // Represents a histogram for recording the number of writes to the pref file + // that occur every kHistogramWriteReportIntervalInMins minutes. + class BASE_PREFS_EXPORT WriteCountHistogram { + public: + static const int32_t kHistogramWriteReportIntervalMins; + + WriteCountHistogram(const base::TimeDelta& commit_interval, + const base::FilePath& path); + // Constructor for testing. |clock| is a test Clock that is used to retrieve + // the time. + WriteCountHistogram(const base::TimeDelta& commit_interval, + const base::FilePath& path, + scoped_ptr<base::Clock> clock); + ~WriteCountHistogram(); + + // Record that a write has occured. + void RecordWriteOccured(); + + // Reports writes (that have not yet been reported) in all of the recorded + // intervals that have elapsed up until current time. + void ReportOutstandingWrites(); + + base::HistogramBase* GetHistogram(); + + private: + // The minimum interval at which writes can occur. + const base::TimeDelta commit_interval_; + + // The path to the file. + const base::FilePath path_; + + // Clock which is used to retrieve the current time. + scoped_ptr<base::Clock> clock_; + + // The interval at which to report write counts. + const base::TimeDelta report_interval_; + + // The time at which the last histogram value was reported for the number + // of write counts. + base::Time last_report_time_; + + // The number of writes that have occured since the last write count was + // reported. + uint32_t writes_since_last_report_; + + DISALLOW_COPY_AND_ASSIGN(WriteCountHistogram); + }; + + FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest, + WriteCountHistogramTestBasic); + FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest, + WriteCountHistogramTestSinglePeriod); + FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest, + WriteCountHistogramTestMultiplePeriods); + FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest, + WriteCountHistogramTestPeriodWithGaps); + friend class base::JsonPrefStoreLossyWriteTest; + + ~JsonPrefStore() override; + + // This method is called after the JSON file has been read. It then hands + // |value| (or an empty dictionary in some read error cases) to the + // |pref_filter| if one is set. It also gives a callback pointing at + // FinalizeFileRead() to that |pref_filter_| which is then responsible for + // invoking it when done. If there is no |pref_filter_|, FinalizeFileRead() + // is invoked directly. + void OnFileRead(scoped_ptr<ReadResult> read_result); + + // ImportantFileWriter::DataSerializer overrides: + bool SerializeData(std::string* output) override; + + // This method is called after the JSON file has been read and the result has + // potentially been intercepted and modified by |pref_filter_|. + // |initialization_successful| is pre-determined by OnFileRead() and should + // be used when reporting OnInitializationCompleted(). + // |schedule_write| indicates whether a write should be immediately scheduled + // (typically because the |pref_filter_| has already altered the |prefs|) -- + // this will be ignored if this store is read-only. + void FinalizeFileRead(bool initialization_successful, + scoped_ptr<base::DictionaryValue> prefs, + bool schedule_write); + + // Schedule a write with the file writer as long as |flags| doesn't contain + // WriteablePrefStore::LOSSY_PREF_WRITE_FLAG. + void ScheduleWrite(uint32_t flags); + + const base::FilePath path_; + const base::FilePath alternate_path_; + const scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_; + + scoped_ptr<base::DictionaryValue> prefs_; + + bool read_only_; + + // Helper for safely writing pref data. + base::ImportantFileWriter writer_; + + scoped_ptr<PrefFilter> pref_filter_; + base::ObserverList<PrefStore::Observer, true> observers_; + + scoped_ptr<ReadErrorDelegate> error_delegate_; + + bool initialized_; + bool filtering_in_progress_; + bool pending_lossy_write_; + PrefReadError read_error_; + + std::set<std::string> keys_need_empty_value_; + + WriteCountHistogram write_count_histogram_; + + DISALLOW_COPY_AND_ASSIGN(JsonPrefStore); +}; + +#endif // BASE_PREFS_JSON_PREF_STORE_H_ diff --git a/base/prefs/json_pref_store_unittest.cc b/components/prefs/json_pref_store_unittest.cc index 41cad89..bc9eeca 100644 --- a/base/prefs/json_pref_store_unittest.cc +++ b/components/prefs/json_pref_store_unittest.cc @@ -17,7 +17,6 @@ #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram_samples.h" -#include "base/metrics/statistics_recorder.h" #include "base/path_service.h" #include "base/prefs/pref_filter.h" #include "base/run_loop.h" @@ -25,6 +24,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/histogram_tester.h" #include "base/test/simple_test_clock.h" #include "base/threading/sequenced_worker_pool.h" #include "base/threading/thread.h" @@ -37,6 +37,25 @@ namespace { const char kHomePage[] = "homepage"; +const char kReadJson[] = + "{\n" + " \"homepage\": \"http://www.cnn.com\",\n" + " \"some_directory\": \"/usr/local/\",\n" + " \"tabs\": {\n" + " \"new_windows_in_tabs\": true,\n" + " \"max_tabs\": 20\n" + " }\n" + "}"; + +const char kInvalidJson[] = "!@#$%^&"; + +// Expected output for tests using RunBasicJsonPrefStoreTest(). +const char kWriteGolden[] = + "{\"homepage\":\"http://www.cnn.com\"," + "\"long_int\":{\"pref\":\"214748364842\"}," + "\"some_directory\":\"/usr/sbin/\"," + "\"tabs\":{\"max_tabs\":10,\"new_windows_in_tabs\":false}}"; + // Set the time on the given SimpleTestClock to the given time in minutes. void SetCurrentTimeInMinutes(double minutes, base::SimpleTestClock* clock) { const int32_t kBaseTimeMins = 100; @@ -104,10 +123,6 @@ class JsonPrefStoreTest : public testing::Test { protected: void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - - ASSERT_TRUE(PathService::Get(base::DIR_TEST_DATA, &data_dir_)); - data_dir_ = data_dir_.AppendASCII("prefs"); - ASSERT_TRUE(PathExists(data_dir_)); } void TearDown() override { @@ -118,14 +133,8 @@ class JsonPrefStoreTest : public testing::Test { // The path to temporary directory used to contain the test operations. base::ScopedTempDir temp_dir_; - // The path to the directory where the test data is stored. - base::FilePath data_dir_; // A message loop that we can use as the file thread message loop. MessageLoop message_loop_; - - private: - // Ensure histograms are reset for each test. - StatisticsRecorder statistics_recorder_; }; // Test fallback behavior for a nonexistent file. @@ -156,9 +165,10 @@ TEST_F(JsonPrefStoreTest, NonExistentFileAndAlternateFile) { // Test fallback behavior for an invalid file. TEST_F(JsonPrefStoreTest, InvalidFile) { - base::FilePath invalid_file_original = data_dir_.AppendASCII("invalid.json"); base::FilePath invalid_file = temp_dir_.path().AppendASCII("invalid.json"); - ASSERT_TRUE(base::CopyFile(invalid_file_original, invalid_file)); + ASSERT_LT(0, base::WriteFile(invalid_file, + kInvalidJson, arraysize(kInvalidJson) - 1)); + scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( invalid_file, message_loop_.task_runner(), scoped_ptr<PrefFilter>()); EXPECT_EQ(PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE, @@ -169,14 +179,17 @@ TEST_F(JsonPrefStoreTest, InvalidFile) { EXPECT_FALSE(PathExists(invalid_file)); base::FilePath moved_aside = temp_dir_.path().AppendASCII("invalid.bad"); EXPECT_TRUE(PathExists(moved_aside)); - EXPECT_TRUE(TextContentsEqual(invalid_file_original, moved_aside)); + + std::string moved_aside_contents; + ASSERT_TRUE(base::ReadFileToString(moved_aside, &moved_aside_contents)); + EXPECT_EQ(kInvalidJson, moved_aside_contents); } -// This function is used to avoid code duplication while testing synchronous and -// asynchronous version of the JsonPrefStore loading. +// This function is used to avoid code duplication while testing synchronous +// and asynchronous version of the JsonPrefStore loading. It validates that the +// given output file's contents matches kWriteGolden. void RunBasicJsonPrefStoreTest(JsonPrefStore* pref_store, - const base::FilePath& output_file, - const base::FilePath& golden_output_file) { + const base::FilePath& output_file) { const char kNewWindowsInTabs[] = "tabs.new_windows_in_tabs"; const char kMaxTabs[] = "tabs.max_tabs"; const char kLongIntPref[] = "long_int.pref"; @@ -238,19 +251,21 @@ void RunBasicJsonPrefStoreTest(JsonPrefStore* pref_store, EXPECT_EQ(214748364842LL, value); // Serialize and compare to expected output. - ASSERT_TRUE(PathExists(golden_output_file)); pref_store->CommitPendingWrite(); RunLoop().RunUntilIdle(); - EXPECT_TRUE(TextContentsEqual(golden_output_file, output_file)); + + std::string output_contents; + ASSERT_TRUE(base::ReadFileToString(output_file, &output_contents)); + EXPECT_EQ(kWriteGolden, output_contents); ASSERT_TRUE(base::DeleteFile(output_file, false)); } TEST_F(JsonPrefStoreTest, Basic) { - ASSERT_TRUE(base::CopyFile(data_dir_.AppendASCII("read.json"), - temp_dir_.path().AppendASCII("write.json"))); + base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); + ASSERT_LT(0, base::WriteFile(input_file, + kReadJson, arraysize(kReadJson) - 1)); // Test that the persistent value can be loaded. - base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); ASSERT_TRUE(PathExists(input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( input_file, message_loop_.task_runner(), scoped_ptr<PrefFilter>()); @@ -268,17 +283,15 @@ TEST_F(JsonPrefStoreTest, Basic) { // } // } - RunBasicJsonPrefStoreTest( - pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); + RunBasicJsonPrefStoreTest(pref_store.get(), input_file); } TEST_F(JsonPrefStoreTest, BasicAsync) { - ASSERT_TRUE(base::CopyFile(data_dir_.AppendASCII("read.json"), - temp_dir_.path().AppendASCII("write.json"))); + base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); + ASSERT_LT(0, base::WriteFile(input_file, + kReadJson, arraysize(kReadJson) - 1)); // Test that the persistent value can be loaded. - base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); - ASSERT_TRUE(PathExists(input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore( input_file, message_loop_.task_runner(), scoped_ptr<PrefFilter>()); @@ -309,8 +322,7 @@ TEST_F(JsonPrefStoreTest, BasicAsync) { // } // } - RunBasicJsonPrefStoreTest( - pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); + RunBasicJsonPrefStoreTest(pref_store.get(), input_file); } TEST_F(JsonPrefStoreTest, PreserveEmptyValues) { @@ -386,12 +398,9 @@ TEST_F(JsonPrefStoreTest, AsyncNonExistingFile) { } TEST_F(JsonPrefStoreTest, ReadWithInterceptor) { - ASSERT_TRUE(base::CopyFile(data_dir_.AppendASCII("read.json"), - temp_dir_.path().AppendASCII("write.json"))); - - // Test that the persistent value can be loaded. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); - ASSERT_TRUE(PathExists(input_file)); + ASSERT_LT(0, base::WriteFile(input_file, + kReadJson, arraysize(kReadJson) - 1)); scoped_ptr<InterceptingPrefFilter> intercepting_pref_filter( new InterceptingPrefFilter()); @@ -427,17 +436,13 @@ TEST_F(JsonPrefStoreTest, ReadWithInterceptor) { // } // } - RunBasicJsonPrefStoreTest( - pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); + RunBasicJsonPrefStoreTest(pref_store.get(), input_file); } TEST_F(JsonPrefStoreTest, ReadAsyncWithInterceptor) { - ASSERT_TRUE(base::CopyFile(data_dir_.AppendASCII("read.json"), - temp_dir_.path().AppendASCII("write.json"))); - - // Test that the persistent value can be loaded. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); - ASSERT_TRUE(PathExists(input_file)); + ASSERT_LT(0, base::WriteFile(input_file, + kReadJson, arraysize(kReadJson) - 1)); scoped_ptr<InterceptingPrefFilter> intercepting_pref_filter( new InterceptingPrefFilter()); @@ -492,20 +497,18 @@ TEST_F(JsonPrefStoreTest, ReadAsyncWithInterceptor) { // } // } - RunBasicJsonPrefStoreTest( - pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); + RunBasicJsonPrefStoreTest(pref_store.get(), input_file); } TEST_F(JsonPrefStoreTest, AlternateFile) { - ASSERT_TRUE( - base::CopyFile(data_dir_.AppendASCII("read.json"), - temp_dir_.path().AppendASCII("alternate.json"))); + base::FilePath alternate_input_file = + temp_dir_.path().AppendASCII("alternate.json"); + ASSERT_LT(0, base::WriteFile(alternate_input_file, + kReadJson, arraysize(kReadJson) - 1)); // Test that the alternate file is moved to the main file and read as-is from // there. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); - base::FilePath alternate_input_file = - temp_dir_.path().AppendASCII("alternate.json"); ASSERT_FALSE(PathExists(input_file)); ASSERT_TRUE(PathExists(alternate_input_file)); scoped_refptr<JsonPrefStore> pref_store = @@ -532,26 +535,22 @@ TEST_F(JsonPrefStoreTest, AlternateFile) { // } // } - RunBasicJsonPrefStoreTest( - pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); + RunBasicJsonPrefStoreTest(pref_store.get(), input_file); } TEST_F(JsonPrefStoreTest, AlternateFileIgnoredWhenMainFileExists) { - ASSERT_TRUE( - base::CopyFile(data_dir_.AppendASCII("read.json"), - temp_dir_.path().AppendASCII("write.json"))); - ASSERT_TRUE( - base::CopyFile(data_dir_.AppendASCII("invalid.json"), - temp_dir_.path().AppendASCII("alternate.json"))); + base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); + ASSERT_LT(0, base::WriteFile(input_file, + kReadJson, arraysize(kReadJson) - 1)); + + base::FilePath alternate_input_file = + temp_dir_.path().AppendASCII("alternate.json"); + ASSERT_LT(0, base::WriteFile(alternate_input_file, + kInvalidJson, arraysize(kInvalidJson) - 1)); // Test that the alternate file is ignored and that the read occurs from the // existing main file. There is no attempt at even deleting the alternate // file as this scenario should never happen in normal user-data-dirs. - base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); - base::FilePath alternate_input_file = - temp_dir_.path().AppendASCII("alternate.json"); - ASSERT_TRUE(PathExists(input_file)); - ASSERT_TRUE(PathExists(alternate_input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore(input_file, alternate_input_file, message_loop_.task_runner(), scoped_ptr<PrefFilter>()); @@ -576,18 +575,16 @@ TEST_F(JsonPrefStoreTest, AlternateFileIgnoredWhenMainFileExists) { // } // } - RunBasicJsonPrefStoreTest( - pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); + RunBasicJsonPrefStoreTest(pref_store.get(), input_file); } TEST_F(JsonPrefStoreTest, AlternateFileDNE) { - ASSERT_TRUE( - base::CopyFile(data_dir_.AppendASCII("read.json"), - temp_dir_.path().AppendASCII("write.json"))); + base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); + ASSERT_LT(0, base::WriteFile(input_file, + kReadJson, arraysize(kReadJson) - 1)); // Test that the basic read works fine when an alternate file is specified but // does not exist. - base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); base::FilePath alternate_input_file = temp_dir_.path().AppendASCII("alternate.json"); ASSERT_TRUE(PathExists(input_file)); @@ -616,22 +613,18 @@ TEST_F(JsonPrefStoreTest, AlternateFileDNE) { // } // } - RunBasicJsonPrefStoreTest( - pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); + RunBasicJsonPrefStoreTest(pref_store.get(), input_file); } TEST_F(JsonPrefStoreTest, BasicAsyncWithAlternateFile) { - ASSERT_TRUE( - base::CopyFile(data_dir_.AppendASCII("read.json"), - temp_dir_.path().AppendASCII("alternate.json"))); + base::FilePath alternate_input_file = + temp_dir_.path().AppendASCII("alternate.json"); + ASSERT_LT(0, base::WriteFile(alternate_input_file, + kReadJson, arraysize(kReadJson) - 1)); // Test that the alternate file is moved to the main file and read as-is from // there even when the read is made asynchronously. base::FilePath input_file = temp_dir_.path().AppendASCII("write.json"); - base::FilePath alternate_input_file = - temp_dir_.path().AppendASCII("alternate.json"); - ASSERT_FALSE(PathExists(input_file)); - ASSERT_TRUE(PathExists(alternate_input_file)); scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore(input_file, alternate_input_file, message_loop_.task_runner(), scoped_ptr<PrefFilter>()); @@ -669,11 +662,12 @@ TEST_F(JsonPrefStoreTest, BasicAsyncWithAlternateFile) { // } // } - RunBasicJsonPrefStoreTest( - pref_store.get(), input_file, data_dir_.AppendASCII("write.golden.json")); + RunBasicJsonPrefStoreTest(pref_store.get(), input_file); } TEST_F(JsonPrefStoreTest, WriteCountHistogramTestBasic) { + base::HistogramTester histogram_tester; + SimpleTestClock* test_clock = new SimpleTestClock; SetCurrentTimeInMinutes(0, test_clock); JsonPrefStore::WriteCountHistogram histogram( @@ -689,8 +683,10 @@ TEST_F(JsonPrefStoreTest, WriteCountHistogramTestBasic) { histogram.ReportOutstandingWrites(); scoped_ptr<HistogramSamples> samples = histogram.GetHistogram()->SnapshotSamples(); - ASSERT_EQ(1, samples->GetCount(1)); - ASSERT_EQ(1, samples->TotalCount()); + + std::string histogram_name = histogram.GetHistogram()->histogram_name(); + histogram_tester.ExpectBucketCount(histogram_name, 1, 1); + histogram_tester.ExpectTotalCount(histogram_name, 1); ASSERT_EQ("Settings.JsonDataWriteCount.Local_State", histogram.GetHistogram()->histogram_name()); @@ -698,6 +694,8 @@ TEST_F(JsonPrefStoreTest, WriteCountHistogramTestBasic) { } TEST_F(JsonPrefStoreTest, WriteCountHistogramTestSinglePeriod) { + base::HistogramTester histogram_tester; + SimpleTestClock* test_clock = new SimpleTestClock; SetCurrentTimeInMinutes(0, test_clock); JsonPrefStore::WriteCountHistogram histogram( @@ -714,29 +712,28 @@ TEST_F(JsonPrefStoreTest, WriteCountHistogramTestSinglePeriod) { histogram.RecordWriteOccured(); // Nothing should be recorded until the report period has elapsed. - scoped_ptr<HistogramSamples> samples = - histogram.GetHistogram()->SnapshotSamples(); - ASSERT_EQ(0, samples->TotalCount()); + std::string histogram_name = histogram.GetHistogram()->histogram_name(); + histogram_tester.ExpectTotalCount(histogram_name, 0); SetCurrentTimeInMinutes(1.3 * report_interval, test_clock); histogram.RecordWriteOccured(); // Now the report period has elapsed. - samples = histogram.GetHistogram()->SnapshotSamples(); - ASSERT_EQ(1, samples->GetCount(3)); - ASSERT_EQ(1, samples->TotalCount()); + histogram_tester.ExpectBucketCount(histogram_name, 3, 1); + histogram_tester.ExpectTotalCount(histogram_name, 1); // The last write won't be recorded because the second count period hasn't // fully elapsed. SetCurrentTimeInMinutes(1.5 * report_interval, test_clock); histogram.ReportOutstandingWrites(); - samples = histogram.GetHistogram()->SnapshotSamples(); - ASSERT_EQ(1, samples->GetCount(3)); - ASSERT_EQ(1, samples->TotalCount()); + histogram_tester.ExpectBucketCount(histogram_name, 3, 1); + histogram_tester.ExpectTotalCount(histogram_name, 1); } TEST_F(JsonPrefStoreTest, WriteCountHistogramTestMultiplePeriods) { + base::HistogramTester histogram_tester; + SimpleTestClock* test_clock = new SimpleTestClock; SetCurrentTimeInMinutes(0, test_clock); JsonPrefStore::WriteCountHistogram histogram( @@ -768,14 +765,15 @@ TEST_F(JsonPrefStoreTest, WriteCountHistogramTestMultiplePeriods) { // fully elapsed SetCurrentTimeInMinutes(3.5 * report_interval, test_clock); histogram.ReportOutstandingWrites(); - scoped_ptr<HistogramSamples> samples = - histogram.GetHistogram()->SnapshotSamples(); - ASSERT_EQ(2, samples->GetCount(3)); - ASSERT_EQ(1, samples->GetCount(2)); - ASSERT_EQ(3, samples->TotalCount()); + std::string histogram_name = histogram.GetHistogram()->histogram_name(); + histogram_tester.ExpectBucketCount(histogram_name, 3, 2); + histogram_tester.ExpectBucketCount(histogram_name, 2, 1); + histogram_tester.ExpectTotalCount(histogram_name, 3); } TEST_F(JsonPrefStoreTest, WriteCountHistogramTestPeriodWithGaps) { + base::HistogramTester histogram_tester; + SimpleTestClock* test_clock = new SimpleTestClock; SetCurrentTimeInMinutes(0, test_clock); JsonPrefStore::WriteCountHistogram histogram( @@ -808,13 +806,12 @@ TEST_F(JsonPrefStoreTest, WriteCountHistogramTestPeriodWithGaps) { SetCurrentTimeInMinutes(6.1 * report_interval, test_clock); histogram.ReportOutstandingWrites(); - scoped_ptr<HistogramSamples> samples = - histogram.GetHistogram()->SnapshotSamples(); - ASSERT_EQ(3, samples->GetCount(0)); - ASSERT_EQ(1, samples->GetCount(1)); - ASSERT_EQ(1, samples->GetCount(2)); - ASSERT_EQ(1, samples->GetCount(3)); - ASSERT_EQ(6, samples->TotalCount()); + std::string histogram_name = histogram.GetHistogram()->histogram_name(); + histogram_tester.ExpectBucketCount(histogram_name, 0, 3); + histogram_tester.ExpectBucketCount(histogram_name, 1, 1); + histogram_tester.ExpectBucketCount(histogram_name, 2, 1); + histogram_tester.ExpectBucketCount(histogram_name, 3, 1); + histogram_tester.ExpectTotalCount(histogram_name, 6); } class JsonPrefStoreLossyWriteTest : public JsonPrefStoreTest { diff --git a/base/prefs/mock_pref_change_callback.cc b/components/prefs/mock_pref_change_callback.cc index 96b7197..96b7197 100644 --- a/base/prefs/mock_pref_change_callback.cc +++ b/components/prefs/mock_pref_change_callback.cc diff --git a/components/prefs/mock_pref_change_callback.h b/components/prefs/mock_pref_change_callback.h new file mode 100644 index 0000000..3030fab --- /dev/null +++ b/components/prefs/mock_pref_change_callback.h @@ -0,0 +1,51 @@ +// 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 BASE_PREFS_MOCK_PREF_CHANGE_CALLBACK_H_ +#define BASE_PREFS_MOCK_PREF_CHANGE_CALLBACK_H_ + +#include <string> + +#include "base/prefs/pref_change_registrar.h" +#include "base/prefs/pref_service.h" +#include "testing/gmock/include/gmock/gmock.h" + +using testing::Pointee; +using testing::Property; +using testing::Truly; + +// Matcher that checks whether the current value of the preference named +// |pref_name| in |prefs| matches |value|. If |value| is NULL, the matcher +// checks that the value is not set. +MATCHER_P3(PrefValueMatches, prefs, pref_name, value, "") { + const PrefService::Preference* pref = prefs->FindPreference(pref_name); + if (!pref) + return false; + + const base::Value* actual_value = pref->GetValue(); + if (!actual_value) + return value == NULL; + if (!value) + return actual_value == NULL; + return value->Equals(actual_value); +} + +// A mock for testing preference notifications and easy setup of expectations. +class MockPrefChangeCallback { + public: + explicit MockPrefChangeCallback(PrefService* prefs); + virtual ~MockPrefChangeCallback(); + + PrefChangeRegistrar::NamedChangeCallback GetCallback(); + + MOCK_METHOD1(OnPreferenceChanged, void(const std::string&)); + + void Expect(const std::string& pref_name, + const base::Value* value); + + private: + PrefService* prefs_; +}; + +#endif // BASE_PREFS_MOCK_PREF_CHANGE_CALLBACK_H_ diff --git a/base/prefs/overlay_user_pref_store.cc b/components/prefs/overlay_user_pref_store.cc index dd5b68e..dd5b68e 100644 --- a/base/prefs/overlay_user_pref_store.cc +++ b/components/prefs/overlay_user_pref_store.cc diff --git a/components/prefs/overlay_user_pref_store.h b/components/prefs/overlay_user_pref_store.h new file mode 100644 index 0000000..35ada57 --- /dev/null +++ b/components/prefs/overlay_user_pref_store.h @@ -0,0 +1,89 @@ +// 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 BASE_PREFS_OVERLAY_USER_PREF_STORE_H_ +#define BASE_PREFS_OVERLAY_USER_PREF_STORE_H_ + +#include <stdint.h> + +#include <map> +#include <string> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/observer_list.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/persistent_pref_store.h" +#include "base/prefs/pref_value_map.h" + +// PersistentPrefStore that directs all write operations into an in-memory +// PrefValueMap. Read operations are first answered by the PrefValueMap. +// If the PrefValueMap does not contain a value for the requested key, +// the look-up is passed on to an underlying PersistentPrefStore |underlay_|. +class BASE_PREFS_EXPORT OverlayUserPrefStore : public PersistentPrefStore, + public PrefStore::Observer { + public: + explicit OverlayUserPrefStore(PersistentPrefStore* underlay); + + // Returns true if a value has been set for the |key| in this + // OverlayUserPrefStore, i.e. if it potentially overrides a value + // from the |underlay_|. + virtual bool IsSetInOverlay(const std::string& key) const; + + // Methods of PrefStore. + void AddObserver(PrefStore::Observer* observer) override; + void RemoveObserver(PrefStore::Observer* observer) override; + bool HasObservers() const override; + bool IsInitializationComplete() const override; + bool GetValue(const std::string& key, + const base::Value** result) const override; + + // Methods of PersistentPrefStore. + bool GetMutableValue(const std::string& key, base::Value** result) override; + void SetValue(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) override; + void SetValueSilently(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) override; + void RemoveValue(const std::string& key, uint32_t flags) override; + bool ReadOnly() const override; + PrefReadError GetReadError() const override; + PrefReadError ReadPrefs() override; + void ReadPrefsAsync(ReadErrorDelegate* delegate) override; + void CommitPendingWrite() override; + void SchedulePendingLossyWrites() override; + void ReportValueChanged(const std::string& key, uint32_t flags) override; + + // Methods of PrefStore::Observer. + void OnPrefValueChanged(const std::string& key) override; + void OnInitializationCompleted(bool succeeded) override; + + void RegisterOverlayPref(const std::string& key); + void RegisterOverlayPref(const std::string& overlay_key, + const std::string& underlay_key); + + protected: + ~OverlayUserPrefStore() override; + + private: + typedef std::map<std::string, std::string> NamesMap; + + const std::string& GetOverlayKey(const std::string& underlay_key) const; + const std::string& GetUnderlayKey(const std::string& overlay_key) const; + + // Returns true if |key| corresponds to a preference that shall be stored in + // an in-memory PrefStore that is not persisted to disk. + bool ShallBeStoredInOverlay(const std::string& key) const; + + base::ObserverList<PrefStore::Observer, true> observers_; + PrefValueMap overlay_; + scoped_refptr<PersistentPrefStore> underlay_; + NamesMap overlay_to_underlay_names_map_; + NamesMap underlay_to_overlay_names_map_; + + DISALLOW_COPY_AND_ASSIGN(OverlayUserPrefStore); +}; + +#endif // BASE_PREFS_OVERLAY_USER_PREF_STORE_H_ diff --git a/base/prefs/overlay_user_pref_store_unittest.cc b/components/prefs/overlay_user_pref_store_unittest.cc index bf5e6a5..bf5e6a5 100644 --- a/base/prefs/overlay_user_pref_store_unittest.cc +++ b/components/prefs/overlay_user_pref_store_unittest.cc diff --git a/components/prefs/persistent_pref_store.h b/components/prefs/persistent_pref_store.h new file mode 100644 index 0000000..89c7a71 --- /dev/null +++ b/components/prefs/persistent_pref_store.h @@ -0,0 +1,77 @@ +// 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 BASE_PREFS_PERSISTENT_PREF_STORE_H_ +#define BASE_PREFS_PERSISTENT_PREF_STORE_H_ + +#include <string> + +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/writeable_pref_store.h" + +// This interface is complementary to the PrefStore interface, declaring +// additional functionality that adds support for setting values and persisting +// the data to some backing store. +class BASE_PREFS_EXPORT PersistentPrefStore : public WriteablePrefStore { + public: + // Unique integer code for each type of error so we can report them + // distinctly in a histogram. + // NOTE: Don't change the explicit values of the enums as it will change the + // server's meaning of the histogram. + enum PrefReadError { + PREF_READ_ERROR_NONE = 0, + PREF_READ_ERROR_JSON_PARSE = 1, + PREF_READ_ERROR_JSON_TYPE = 2, + PREF_READ_ERROR_ACCESS_DENIED = 3, + PREF_READ_ERROR_FILE_OTHER = 4, + PREF_READ_ERROR_FILE_LOCKED = 5, + PREF_READ_ERROR_NO_FILE = 6, + PREF_READ_ERROR_JSON_REPEAT = 7, + // PREF_READ_ERROR_OTHER = 8, // Deprecated. + PREF_READ_ERROR_FILE_NOT_SPECIFIED = 9, + // Indicates that ReadPrefs() couldn't complete synchronously and is waiting + // for an asynchronous task to complete first. + PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE = 10, + PREF_READ_ERROR_MAX_ENUM + }; + + class ReadErrorDelegate { + public: + virtual ~ReadErrorDelegate() {} + + virtual void OnError(PrefReadError error) = 0; + }; + + // Whether the store is in a pseudo-read-only mode where changes are not + // actually persisted to disk. This happens in some cases when there are + // read errors during startup. + virtual bool ReadOnly() const = 0; + + // Gets the read error. Only valid if IsInitializationComplete() returns true. + virtual PrefReadError GetReadError() const = 0; + + // Reads the preferences from disk. Notifies observers via + // "PrefStore::OnInitializationCompleted" when done. + virtual PrefReadError ReadPrefs() = 0; + + // Reads the preferences from disk asynchronously. Notifies observers via + // "PrefStore::OnInitializationCompleted" when done. Also it fires + // |error_delegate| if it is not NULL and reading error has occurred. + // Owns |error_delegate|. + virtual void ReadPrefsAsync(ReadErrorDelegate* error_delegate) = 0; + + // Lands any pending writes to disk. + virtual void CommitPendingWrite() = 0; + + // Schedule a write if there is any lossy data pending. Unlike + // CommitPendingWrite() this does not immediately sync to disk, instead it + // triggers an eventual write if there is lossy data pending and if there + // isn't one scheduled already. + virtual void SchedulePendingLossyWrites() = 0; + + protected: + ~PersistentPrefStore() override {} +}; + +#endif // BASE_PREFS_PERSISTENT_PREF_STORE_H_ diff --git a/base/prefs/pref_change_registrar.cc b/components/prefs/pref_change_registrar.cc index 13193484..13193484 100644 --- a/base/prefs/pref_change_registrar.cc +++ b/components/prefs/pref_change_registrar.cc diff --git a/components/prefs/pref_change_registrar.h b/components/prefs/pref_change_registrar.h new file mode 100644 index 0000000..cd5a233 --- /dev/null +++ b/components/prefs/pref_change_registrar.h @@ -0,0 +1,81 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_PREFS_PREF_CHANGE_REGISTRAR_H_ +#define BASE_PREFS_PREF_CHANGE_REGISTRAR_H_ + +#include <map> +#include <string> + +#include "base/callback.h" +#include "base/macros.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/pref_observer.h" + +class PrefService; + +// Automatically manages the registration of one or more pref change observers +// with a PrefStore. Functions much like NotificationRegistrar, but specifically +// manages observers of preference changes. When the Registrar is destroyed, +// all registered observers are automatically unregistered with the PrefStore. +class BASE_PREFS_EXPORT PrefChangeRegistrar : public PrefObserver { + public: + // You can register this type of callback if you need to know the + // path of the preference that is changing. + typedef base::Callback<void(const std::string&)> NamedChangeCallback; + + PrefChangeRegistrar(); + virtual ~PrefChangeRegistrar(); + + // Must be called before adding or removing observers. Can be called more + // than once as long as the value of |service| doesn't change. + void Init(PrefService* service); + + // Adds a pref observer for the specified pref |path| and |obs| observer + // object. All registered observers will be automatically unregistered + // when the registrar's destructor is called. + // + // The second version binds a callback that will receive the path of + // the preference that is changing as its parameter. + // + // Only one observer may be registered per path. + void Add(const std::string& path, const base::Closure& obs); + void Add(const std::string& path, const NamedChangeCallback& obs); + + // Removes the pref observer registered for |path|. + void Remove(const std::string& path); + + // Removes all observers that have been previously added with a call to Add. + void RemoveAll(); + + // Returns true if no pref observers are registered. + bool IsEmpty() const; + + // Check whether |pref| is in the set of preferences being observed. + bool IsObserved(const std::string& pref); + + // Check whether any of the observed preferences has the managed bit set. + bool IsManaged(); + + // Return the PrefService for this registrar. + PrefService* prefs(); + const PrefService* prefs() const; + + private: + // PrefObserver: + void OnPreferenceChanged(PrefService* service, + const std::string& pref_name) override; + + static void InvokeUnnamedCallback(const base::Closure& callback, + const std::string& pref_name); + + typedef std::map<std::string, NamedChangeCallback> ObserverMap; + + ObserverMap observers_; + PrefService* service_; + + DISALLOW_COPY_AND_ASSIGN(PrefChangeRegistrar); +}; + +#endif // BASE_PREFS_PREF_CHANGE_REGISTRAR_H_ diff --git a/base/prefs/pref_change_registrar_unittest.cc b/components/prefs/pref_change_registrar_unittest.cc index da425cf..da425cf 100644 --- a/base/prefs/pref_change_registrar_unittest.cc +++ b/components/prefs/pref_change_registrar_unittest.cc diff --git a/components/prefs/pref_filter.h b/components/prefs/pref_filter.h new file mode 100644 index 0000000..82a44c6 --- /dev/null +++ b/components/prefs/pref_filter.h @@ -0,0 +1,55 @@ +// Copyright 2013 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 BASE_PREFS_PREF_FILTER_H_ +#define BASE_PREFS_PREF_FILTER_H_ + +#include <string> + +#include "base/callback_forward.h" +#include "base/memory/scoped_ptr.h" +#include "base/prefs/base_prefs_export.h" + +namespace base { +class DictionaryValue; +class Value; +} // namespace base + +// Filters preferences as they are loaded from disk or updated at runtime. +// Currently supported only by JsonPrefStore. +class BASE_PREFS_EXPORT PrefFilter { + public: + // A callback to be invoked when |prefs| have been read (and possibly + // pre-modified) and are now ready to be handed back to this callback's + // builder. |schedule_write| indicates whether a write should be immediately + // scheduled (typically because the |prefs| were pre-modified). + typedef base::Callback<void(scoped_ptr<base::DictionaryValue> prefs, + bool schedule_write)> PostFilterOnLoadCallback; + + virtual ~PrefFilter() {} + + // This method is given ownership of the |pref_store_contents| read from disk + // before the underlying PersistentPrefStore gets to use them. It must hand + // them back via |post_filter_on_load_callback|, but may modify them first. + // Note: This method is asynchronous, which may make calls like + // PersistentPrefStore::ReadPrefs() asynchronous. The owner of filtered + // PersistentPrefStores should handle this to make the reads look synchronous + // to external users (see SegregatedPrefStore::ReadPrefs() for an example). + virtual void FilterOnLoad( + const PostFilterOnLoadCallback& post_filter_on_load_callback, + scoped_ptr<base::DictionaryValue> pref_store_contents) = 0; + + // Receives notification when a pref store value is changed, before Observers + // are notified. + virtual void FilterUpdate(const std::string& path) = 0; + + // Receives notification when the pref store is about to serialize data + // contained in |pref_store_contents| to a string. Modifications to + // |pref_store_contents| will be persisted to disk and also affect the + // in-memory state. + virtual void FilterSerializeData( + base::DictionaryValue* pref_store_contents) = 0; +}; + +#endif // BASE_PREFS_PREF_FILTER_H_ diff --git a/base/prefs/pref_member.cc b/components/prefs/pref_member.cc index 934237d..934237d 100644 --- a/base/prefs/pref_member.cc +++ b/components/prefs/pref_member.cc diff --git a/components/prefs/pref_member.h b/components/prefs/pref_member.h new file mode 100644 index 0000000..4290c0d --- /dev/null +++ b/components/prefs/pref_member.h @@ -0,0 +1,355 @@ +// 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. +// +// A helper class that stays in sync with a preference (bool, int, real, +// string or filepath). For example: +// +// class MyClass { +// public: +// MyClass(PrefService* prefs) { +// my_string_.Init(prefs::kHomePage, prefs); +// } +// private: +// StringPrefMember my_string_; +// }; +// +// my_string_ should stay in sync with the prefs::kHomePage pref and will +// update if either the pref changes or if my_string_.SetValue is called. +// +// An optional observer can be passed into the Init method which can be used to +// notify MyClass of changes. Note that if you use SetValue(), the observer +// will not be notified. + +#ifndef BASE_PREFS_PREF_MEMBER_H_ +#define BASE_PREFS_PREF_MEMBER_H_ + +#include <string> +#include <vector> + +#include "base/bind.h" +#include "base/callback_forward.h" +#include "base/files/file_path.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/pref_observer.h" +#include "base/single_thread_task_runner.h" +#include "base/values.h" + +class PrefService; + +namespace subtle { + +class BASE_PREFS_EXPORT PrefMemberBase : public PrefObserver { + public: + // Type of callback you can register if you need to know the name of + // the pref that is changing. + typedef base::Callback<void(const std::string&)> NamedChangeCallback; + + PrefService* prefs() { return prefs_; } + const PrefService* prefs() const { return prefs_; } + + protected: + class BASE_PREFS_EXPORT Internal + : public base::RefCountedThreadSafe<Internal> { + public: + Internal(); + + // Update the value, either by calling |UpdateValueInternal| directly + // or by dispatching to the right thread. + // Takes ownership of |value|. + void UpdateValue(base::Value* value, + bool is_managed, + bool is_user_modifiable, + const base::Closure& callback) const; + + void MoveToThread(scoped_refptr<base::SingleThreadTaskRunner> task_runner); + + // See PrefMember<> for description. + bool IsManaged() const { + return is_managed_; + } + + bool IsUserModifiable() const { + return is_user_modifiable_; + } + + protected: + friend class base::RefCountedThreadSafe<Internal>; + virtual ~Internal(); + + void CheckOnCorrectThread() const { + DCHECK(IsOnCorrectThread()); + } + + private: + // This method actually updates the value. It should only be called from + // the thread the PrefMember is on. + virtual bool UpdateValueInternal(const base::Value& value) const = 0; + + bool IsOnCorrectThread() const; + + scoped_refptr<base::SingleThreadTaskRunner> thread_task_runner_; + mutable bool is_managed_; + mutable bool is_user_modifiable_; + + DISALLOW_COPY_AND_ASSIGN(Internal); + }; + + PrefMemberBase(); + virtual ~PrefMemberBase(); + + // See PrefMember<> for description. + void Init(const std::string& pref_name, + PrefService* prefs, + const NamedChangeCallback& observer); + void Init(const std::string& pref_name, PrefService* prefs); + + virtual void CreateInternal() const = 0; + + // See PrefMember<> for description. + void Destroy(); + + void MoveToThread(scoped_refptr<base::SingleThreadTaskRunner> task_runner); + + // PrefObserver + void OnPreferenceChanged(PrefService* service, + const std::string& pref_name) override; + + void VerifyValuePrefName() const { + DCHECK(!pref_name_.empty()); + } + + // This method is used to do the actual sync with the preference. + // Note: it is logically const, because it doesn't modify the state + // seen by the outside world. It is just doing a lazy load behind the scenes. + void UpdateValueFromPref(const base::Closure& callback) const; + + // Verifies the preference name, and lazily loads the preference value if + // it hasn't been loaded yet. + void VerifyPref() const; + + const std::string& pref_name() const { return pref_name_; } + + virtual Internal* internal() const = 0; + + // Used to allow registering plain base::Closure callbacks. + static void InvokeUnnamedCallback(const base::Closure& callback, + const std::string& pref_name); + + private: + // Ordered the members to compact the class instance. + std::string pref_name_; + NamedChangeCallback observer_; + PrefService* prefs_; + + protected: + bool setting_value_; +}; + +// This function implements StringListPrefMember::UpdateValue(). +// It is exposed here for testing purposes. +bool BASE_PREFS_EXPORT PrefMemberVectorStringUpdate( + const base::Value& value, + std::vector<std::string>* string_vector); + +} // namespace subtle + +template <typename ValueType> +class PrefMember : public subtle::PrefMemberBase { + public: + // Defer initialization to an Init method so it's easy to make this class be + // a member variable. + PrefMember() {} + virtual ~PrefMember() {} + + // Do the actual initialization of the class. Use the two-parameter + // version if you don't want any notifications of changes. This + // method should only be called on the UI thread. + void Init(const std::string& pref_name, + PrefService* prefs, + const NamedChangeCallback& observer) { + subtle::PrefMemberBase::Init(pref_name, prefs, observer); + } + void Init(const std::string& pref_name, + PrefService* prefs, + const base::Closure& observer) { + subtle::PrefMemberBase::Init( + pref_name, prefs, + base::Bind(&PrefMemberBase::InvokeUnnamedCallback, observer)); + } + void Init(const std::string& pref_name, PrefService* prefs) { + subtle::PrefMemberBase::Init(pref_name, prefs); + } + + // Unsubscribes the PrefMember from the PrefService. After calling this + // function, the PrefMember may not be used any more on the UI thread. + // Assuming |MoveToThread| was previously called, |GetValue|, |IsManaged|, + // and |IsUserModifiable| can still be called from the other thread but + // the results will no longer update from the PrefService. + // This method should only be called on the UI thread. + void Destroy() { + subtle::PrefMemberBase::Destroy(); + } + + // Moves the PrefMember to another thread, allowing read accesses from there. + // Changes from the PrefService will be propagated asynchronously + // via PostTask. + // This method should only be used from the thread the PrefMember is currently + // on, which is the UI thread by default. + void MoveToThread(scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + subtle::PrefMemberBase::MoveToThread(task_runner); + } + + // Check whether the pref is managed, i.e. controlled externally through + // enterprise configuration management (e.g. windows group policy). Returns + // false for unknown prefs. + // This method should only be used from the thread the PrefMember is currently + // on, which is the UI thread unless changed by |MoveToThread|. + bool IsManaged() const { + VerifyPref(); + return internal_->IsManaged(); + } + + // Checks whether the pref can be modified by the user. This returns false + // when the pref is managed by a policy or an extension, and when a command + // line flag overrides the pref. + // This method should only be used from the thread the PrefMember is currently + // on, which is the UI thread unless changed by |MoveToThread|. + bool IsUserModifiable() const { + VerifyPref(); + return internal_->IsUserModifiable(); + } + + // Retrieve the value of the member variable. + // This method should only be used from the thread the PrefMember is currently + // on, which is the UI thread unless changed by |MoveToThread|. + ValueType GetValue() const { + VerifyPref(); + return internal_->value(); + } + + // Provided as a convenience. + ValueType operator*() const { + return GetValue(); + } + + // Set the value of the member variable. + // This method should only be called on the UI thread. + void SetValue(const ValueType& value) { + VerifyValuePrefName(); + setting_value_ = true; + UpdatePref(value); + setting_value_ = false; + } + + // Returns the pref name. + const std::string& GetPrefName() const { + return pref_name(); + } + + private: + class Internal : public subtle::PrefMemberBase::Internal { + public: + Internal() : value_(ValueType()) {} + + ValueType value() { + CheckOnCorrectThread(); + return value_; + } + + protected: + ~Internal() override {} + + BASE_PREFS_EXPORT bool UpdateValueInternal( + const base::Value& value) const override; + + // We cache the value of the pref so we don't have to keep walking the pref + // tree. + mutable ValueType value_; + + private: + DISALLOW_COPY_AND_ASSIGN(Internal); + }; + + Internal* internal() const override { return internal_.get(); } + void CreateInternal() const override { internal_ = new Internal(); } + + // This method is used to do the actual sync with pref of the specified type. + void BASE_PREFS_EXPORT UpdatePref(const ValueType& value); + + mutable scoped_refptr<Internal> internal_; + + DISALLOW_COPY_AND_ASSIGN(PrefMember); +}; + +// Declaration of template specialization need to be repeated here +// specifically for each specialization (rather than just once above) +// or at least one of our compilers won't be happy in all cases. +// Specifically, it was failing on ChromeOS with a complaint about +// PrefMember<FilePath>::UpdateValueInternal not being defined when +// built in a chroot with the following parameters: +// +// FEATURES="noclean nostrip" USE="-chrome_debug -chrome_remoting +// -chrome_internal -chrome_pdf component_build" +// ~/trunk/goma/goma-wrapper cros_chrome_make --board=${BOARD} +// --install --runhooks + +template <> +BASE_PREFS_EXPORT void PrefMember<bool>::UpdatePref(const bool& value); + +template <> +BASE_PREFS_EXPORT bool PrefMember<bool>::Internal::UpdateValueInternal( + const base::Value& value) const; + +template <> +BASE_PREFS_EXPORT void PrefMember<int>::UpdatePref(const int& value); + +template <> +BASE_PREFS_EXPORT bool PrefMember<int>::Internal::UpdateValueInternal( + const base::Value& value) const; + +template <> +BASE_PREFS_EXPORT void PrefMember<double>::UpdatePref(const double& value); + +template <> +BASE_PREFS_EXPORT bool PrefMember<double>::Internal::UpdateValueInternal( + const base::Value& value) const; + +template <> +BASE_PREFS_EXPORT void PrefMember<std::string>::UpdatePref( + const std::string& value); + +template <> +BASE_PREFS_EXPORT bool PrefMember<std::string>::Internal::UpdateValueInternal( + const base::Value& value) const; + +template <> +BASE_PREFS_EXPORT void PrefMember<base::FilePath>::UpdatePref( + const base::FilePath& value); + +template <> +BASE_PREFS_EXPORT bool +PrefMember<base::FilePath>::Internal::UpdateValueInternal( + const base::Value& value) const; + +template <> +BASE_PREFS_EXPORT void PrefMember<std::vector<std::string> >::UpdatePref( + const std::vector<std::string>& value); + +template <> +BASE_PREFS_EXPORT bool +PrefMember<std::vector<std::string> >::Internal::UpdateValueInternal( + const base::Value& value) const; + +typedef PrefMember<bool> BooleanPrefMember; +typedef PrefMember<int> IntegerPrefMember; +typedef PrefMember<double> DoublePrefMember; +typedef PrefMember<std::string> StringPrefMember; +typedef PrefMember<base::FilePath> FilePathPrefMember; +// This preference member is expensive for large string arrays. +typedef PrefMember<std::vector<std::string> > StringListPrefMember; + +#endif // BASE_PREFS_PREF_MEMBER_H_ diff --git a/base/prefs/pref_member_unittest.cc b/components/prefs/pref_member_unittest.cc index a776e2c..a776e2c 100644 --- a/base/prefs/pref_member_unittest.cc +++ b/components/prefs/pref_member_unittest.cc diff --git a/components/prefs/pref_notifier.h b/components/prefs/pref_notifier.h new file mode 100644 index 0000000..e0df260 --- /dev/null +++ b/components/prefs/pref_notifier.h @@ -0,0 +1,26 @@ +// 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 BASE_PREFS_PREF_NOTIFIER_H_ +#define BASE_PREFS_PREF_NOTIFIER_H_ + +#include <string> + +// Delegate interface used by PrefValueStore to notify its owner about changes +// to the preference values. +// TODO(mnissler, danno): Move this declaration to pref_value_store.h once we've +// cleaned up all public uses of this interface. +class PrefNotifier { + public: + virtual ~PrefNotifier() {} + + // Sends out a change notification for the preference identified by + // |pref_name|. + virtual void OnPreferenceChanged(const std::string& pref_name) = 0; + + // Broadcasts the intialization completed notification. + virtual void OnInitializationCompleted(bool succeeded) = 0; +}; + +#endif // BASE_PREFS_PREF_NOTIFIER_H_ diff --git a/base/prefs/pref_notifier_impl.cc b/components/prefs/pref_notifier_impl.cc index 7ae5fe6..7ae5fe6 100644 --- a/base/prefs/pref_notifier_impl.cc +++ b/components/prefs/pref_notifier_impl.cc diff --git a/components/prefs/pref_notifier_impl.h b/components/prefs/pref_notifier_impl.h new file mode 100644 index 0000000..6e62e23 --- /dev/null +++ b/components/prefs/pref_notifier_impl.h @@ -0,0 +1,74 @@ +// 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 BASE_PREFS_PREF_NOTIFIER_IMPL_H_ +#define BASE_PREFS_PREF_NOTIFIER_IMPL_H_ + +#include <list> +#include <string> + +#include "base/callback.h" +#include "base/compiler_specific.h" +#include "base/containers/hash_tables.h" +#include "base/macros.h" +#include "base/observer_list.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/pref_notifier.h" +#include "base/prefs/pref_observer.h" +#include "base/threading/thread_checker.h" + +class PrefService; + +// The PrefNotifier implementation used by the PrefService. +class BASE_PREFS_EXPORT PrefNotifierImpl + : public NON_EXPORTED_BASE(PrefNotifier) { + public: + PrefNotifierImpl(); + explicit PrefNotifierImpl(PrefService* pref_service); + ~PrefNotifierImpl() override; + + // If the pref at the given path changes, we call the observer's + // OnPreferenceChanged method. + void AddPrefObserver(const std::string& path, PrefObserver* observer); + void RemovePrefObserver(const std::string& path, PrefObserver* observer); + + // We run the callback once, when initialization completes. The bool + // parameter will be set to true for successful initialization, + // false for unsuccessful. + void AddInitObserver(base::Callback<void(bool)> observer); + + void SetPrefService(PrefService* pref_service); + + protected: + // PrefNotifier overrides. + void OnPreferenceChanged(const std::string& pref_name) override; + void OnInitializationCompleted(bool succeeded) override; + + // A map from pref names to a list of observers. Observers get fired in the + // order they are added. These should only be accessed externally for unit + // testing. + typedef base::ObserverList<PrefObserver> PrefObserverList; + typedef base::hash_map<std::string, PrefObserverList*> PrefObserverMap; + + typedef std::list<base::Callback<void(bool)>> PrefInitObserverList; + + const PrefObserverMap* pref_observers() const { return &pref_observers_; } + + private: + // For the given pref_name, fire any observer of the pref. Virtual so it can + // be mocked for unit testing. + virtual void FireObservers(const std::string& path); + + // Weak reference; the notifier is owned by the PrefService. + PrefService* pref_service_; + + PrefObserverMap pref_observers_; + PrefInitObserverList init_observers_; + + base::ThreadChecker thread_checker_; + + DISALLOW_COPY_AND_ASSIGN(PrefNotifierImpl); +}; + +#endif // BASE_PREFS_PREF_NOTIFIER_IMPL_H_ diff --git a/base/prefs/pref_notifier_impl_unittest.cc b/components/prefs/pref_notifier_impl_unittest.cc index cb3c3b5..cb3c3b5 100644 --- a/base/prefs/pref_notifier_impl_unittest.cc +++ b/components/prefs/pref_notifier_impl_unittest.cc diff --git a/components/prefs/pref_observer.h b/components/prefs/pref_observer.h new file mode 100644 index 0000000..5d8f5b6 --- /dev/null +++ b/components/prefs/pref_observer.h @@ -0,0 +1,21 @@ +// 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 BASE_PREFS_PREF_OBSERVER_H_ +#define BASE_PREFS_PREF_OBSERVER_H_ + +#include <string> + +class PrefService; + +// Used internally to the Prefs subsystem to pass preference change +// notifications between PrefService, PrefNotifierImpl and +// PrefChangeRegistrar. +class PrefObserver { + public: + virtual void OnPreferenceChanged(PrefService* service, + const std::string& pref_name) = 0; +}; + +#endif // BASE_PREFS_PREF_OBSERVER_H_ diff --git a/base/prefs/pref_registry.cc b/components/prefs/pref_registry.cc index 77fb9a5..77fb9a5 100644 --- a/base/prefs/pref_registry.cc +++ b/components/prefs/pref_registry.cc diff --git a/components/prefs/pref_registry.h b/components/prefs/pref_registry.h new file mode 100644 index 0000000..7e141d8 --- /dev/null +++ b/components/prefs/pref_registry.h @@ -0,0 +1,89 @@ +// 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 BASE_PREFS_PREF_REGISTRY_H_ +#define BASE_PREFS_PREF_REGISTRY_H_ + +#include <stdint.h> + +#include "base/containers/hash_tables.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/pref_value_map.h" + +namespace base { +class Value; +} + +class DefaultPrefStore; +class PrefStore; + +// Preferences need to be registered with a type and default value +// before they are used. +// +// The way you use a PrefRegistry is that you register all required +// preferences on it (via one of its subclasses), then pass it as a +// construction parameter to PrefService. +// +// Currently, registrations after constructing the PrefService will +// also work, but this is being deprecated. +class BASE_PREFS_EXPORT PrefRegistry : public base::RefCounted<PrefRegistry> { + public: + // Registration flags that can be specified which impact how the pref will + // behave or be stored. This will be passed in a bitmask when the pref is + // registered. Subclasses of PrefRegistry can specify their own flags. Care + // must be taken to ensure none of these overlap with the flags below. + enum PrefRegistrationFlags : uint32_t { + // No flags are specified. + NO_REGISTRATION_FLAGS = 0, + + // The first 8 bits are reserved for subclasses of PrefRegistry to use. + + // This marks the pref as "lossy". There is no strict time guarantee on when + // a lossy pref will be persisted to permanent storage when it is modified. + LOSSY_PREF = 1 << 8, + }; + + typedef PrefValueMap::const_iterator const_iterator; + typedef base::hash_map<std::string, uint32_t> PrefRegistrationFlagsMap; + + PrefRegistry(); + + // Retrieve the set of registration flags for the given preference. The return + // value is a bitmask of PrefRegistrationFlags. + uint32_t GetRegistrationFlags(const std::string& pref_name) const; + + // Gets the registered defaults. + scoped_refptr<PrefStore> defaults(); + + // Allows iteration over defaults. + const_iterator begin() const; + const_iterator end() const; + + // Changes the default value for a preference. Takes ownership of |value|. + // + // |pref_name| must be a previously registered preference. + void SetDefaultPrefValue(const std::string& pref_name, base::Value* value); + + protected: + friend class base::RefCounted<PrefRegistry>; + virtual ~PrefRegistry(); + + // Used by subclasses to register a default value and registration flags for + // a preference. |flags| is a bitmask of |PrefRegistrationFlags|. + void RegisterPreference(const std::string& path, + base::Value* default_value, + uint32_t flags); + + scoped_refptr<DefaultPrefStore> defaults_; + + // A map of pref name to a bitmask of PrefRegistrationFlags. + PrefRegistrationFlagsMap registration_flags_; + + private: + DISALLOW_COPY_AND_ASSIGN(PrefRegistry); +}; + +#endif // BASE_PREFS_PREF_REGISTRY_H_ diff --git a/base/prefs/pref_registry_simple.cc b/components/prefs/pref_registry_simple.cc index b5c73e2..b5c73e2 100644 --- a/base/prefs/pref_registry_simple.cc +++ b/components/prefs/pref_registry_simple.cc diff --git a/components/prefs/pref_registry_simple.h b/components/prefs/pref_registry_simple.h new file mode 100644 index 0000000..6afc012 --- /dev/null +++ b/components/prefs/pref_registry_simple.h @@ -0,0 +1,91 @@ +// 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 BASE_PREFS_PREF_REGISTRY_SIMPLE_H_ +#define BASE_PREFS_PREF_REGISTRY_SIMPLE_H_ + +#include <stdint.h> + +#include <string> + +#include "base/macros.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/pref_registry.h" + +namespace base { +class DictionaryValue; +class FilePath; +class ListValue; +} + +// A simple implementation of PrefRegistry. +class BASE_PREFS_EXPORT PrefRegistrySimple : public PrefRegistry { + public: + PrefRegistrySimple(); + + void RegisterBooleanPref(const std::string& path, bool default_value); + void RegisterIntegerPref(const std::string& path, int default_value); + void RegisterDoublePref(const std::string& path, double default_value); + void RegisterStringPref(const std::string& path, + const std::string& default_value); + void RegisterFilePathPref(const std::string& path, + const base::FilePath& default_value); + void RegisterListPref(const std::string& path); + void RegisterDictionaryPref(const std::string& path); + void RegisterListPref(const std::string& path, + base::ListValue* default_value); + void RegisterDictionaryPref(const std::string& path, + base::DictionaryValue* default_value); + void RegisterInt64Pref(const std::string& path, int64_t default_value); + void RegisterUint64Pref(const std::string&, uint64_t default_value); + + // Versions of registration functions that accept PrefRegistrationFlags. + // |flags| is a bitmask of PrefRegistrationFlags. + void RegisterBooleanPref(const std::string&, + bool default_value, + uint32_t flags); + void RegisterIntegerPref(const std::string&, + int default_value, + uint32_t flags); + void RegisterDoublePref(const std::string&, + double default_value, + uint32_t flags); + void RegisterStringPref(const std::string&, + const std::string& default_value, + uint32_t flags); + void RegisterFilePathPref(const std::string&, + const base::FilePath& default_value, + uint32_t flags); + void RegisterListPref(const std::string&, uint32_t flags); + void RegisterDictionaryPref(const std::string&, uint32_t flags); + void RegisterListPref(const std::string&, + base::ListValue* default_value, + uint32_t flags); + void RegisterDictionaryPref(const std::string&, + base::DictionaryValue* default_value, + uint32_t flags); + void RegisterInt64Pref(const std::string&, + int64_t default_value, + uint32_t flags); + void RegisterUint64Pref(const std::string&, + uint64_t default_value, + uint32_t flags); + + protected: + ~PrefRegistrySimple() override; + + // Allows subclasses to hook into pref registration. + virtual void OnPrefRegistered(const std::string&, + base::Value* default_value, + uint32_t flags); + + private: + void RegisterPrefAndNotify(const std::string&, + base::Value* default_value, + uint32_t flags); + + DISALLOW_COPY_AND_ASSIGN(PrefRegistrySimple); +}; + +#endif // BASE_PREFS_PREF_REGISTRY_SIMPLE_H_ diff --git a/base/prefs/pref_service.cc b/components/prefs/pref_service.cc index 077bb1d..077bb1d 100644 --- a/base/prefs/pref_service.cc +++ b/components/prefs/pref_service.cc diff --git a/components/prefs/pref_service.h b/components/prefs/pref_service.h new file mode 100644 index 0000000..bec7830 --- /dev/null +++ b/components/prefs/pref_service.h @@ -0,0 +1,385 @@ +// 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. + +// This provides a way to access the application's current preferences. + +// Chromium settings and storage represent user-selected preferences and +// information and MUST not be extracted, overwritten or modified except +// through Chromium defined APIs. + +#ifndef BASE_PREFS_PREF_SERVICE_H_ +#define BASE_PREFS_PREF_SERVICE_H_ + +#include <stdint.h> + +#include <set> +#include <string> + +#include "base/callback.h" +#include "base/compiler_specific.h" +#include "base/containers/hash_tables.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/observer_list.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/persistent_pref_store.h" +#include "base/threading/non_thread_safe.h" +#include "base/values.h" + +class PrefNotifier; +class PrefNotifierImpl; +class PrefObserver; +class PrefRegistry; +class PrefValueStore; +class PrefStore; + +namespace base { +class FilePath; +} + +namespace subtle { +class PrefMemberBase; +class ScopedUserPrefUpdateBase; +} + +// Base class for PrefServices. You can use the base class to read and +// interact with preferences, but not to register new preferences; for +// that see e.g. PrefRegistrySimple. +// +// Settings and storage accessed through this class represent +// user-selected preferences and information and MUST not be +// extracted, overwritten or modified except through the defined APIs. +class BASE_PREFS_EXPORT PrefService : public base::NonThreadSafe { + public: + enum PrefInitializationStatus { + INITIALIZATION_STATUS_WAITING, + INITIALIZATION_STATUS_SUCCESS, + INITIALIZATION_STATUS_CREATED_NEW_PREF_STORE, + INITIALIZATION_STATUS_ERROR + }; + + // A helper class to store all the information associated with a preference. + class BASE_PREFS_EXPORT Preference { + public: + // The type of the preference is determined by the type with which it is + // registered. This type needs to be a boolean, integer, double, string, + // dictionary (a branch), or list. You shouldn't need to construct this on + // your own; use the PrefService::Register*Pref methods instead. + Preference(const PrefService* service, + const std::string& name, + base::Value::Type type); + ~Preference() {} + + // Returns the name of the Preference (i.e., the key, e.g., + // browser.window_placement). + const std::string name() const; + + // Returns the registered type of the preference. + base::Value::Type GetType() const; + + // Returns the value of the Preference, falling back to the registered + // default value if no other has been set. + const base::Value* GetValue() const; + + // Returns the value recommended by the admin, if any. + const base::Value* GetRecommendedValue() const; + + // Returns true if the Preference is managed, i.e. set by an admin policy. + // Since managed prefs have the highest priority, this also indicates + // whether the pref is actually being controlled by the policy setting. + bool IsManaged() const; + + // Returns true if the Preference is controlled by the custodian of the + // supervised user. Since a supervised user is not expected to have an admin + // policy, this is the controlling pref if set. + bool IsManagedByCustodian() const; + + // Returns true if the Preference is recommended, i.e. set by an admin + // policy but the user is allowed to change it. + bool IsRecommended() const; + + // Returns true if the Preference has a value set by an extension, even if + // that value is being overridden by a higher-priority source. + bool HasExtensionSetting() const; + + // Returns true if the Preference has a user setting, even if that value is + // being overridden by a higher-priority source. + bool HasUserSetting() const; + + // Returns true if the Preference value is currently being controlled by an + // extension, and not by any higher-priority source. + bool IsExtensionControlled() const; + + // Returns true if the Preference value is currently being controlled by a + // user setting, and not by any higher-priority source. + bool IsUserControlled() const; + + // Returns true if the Preference is currently using its default value, + // and has not been set by any higher-priority source (even with the same + // value). + bool IsDefaultValue() const; + + // Returns true if the user can change the Preference value, which is the + // case if no higher-priority source than the user store controls the + // Preference. + bool IsUserModifiable() const; + + // Returns true if an extension can change the Preference value, which is + // the case if no higher-priority source than the extension store controls + // the Preference. + bool IsExtensionModifiable() const; + + // Return the registration flags for this pref as a bitmask of + // PrefRegistry::PrefRegistrationFlags. + uint32_t registration_flags() const { return registration_flags_; } + + private: + friend class PrefService; + + PrefValueStore* pref_value_store() const { + return pref_service_->pref_value_store_.get(); + } + + const std::string name_; + + const base::Value::Type type_; + + uint32_t registration_flags_; + + // Reference to the PrefService in which this pref was created. + const PrefService* pref_service_; + }; + + // You may wish to use PrefServiceFactory or one of its subclasses + // for simplified construction. + PrefService( + PrefNotifierImpl* pref_notifier, + PrefValueStore* pref_value_store, + PersistentPrefStore* user_prefs, + PrefRegistry* pref_registry, + base::Callback<void(PersistentPrefStore::PrefReadError)> + read_error_callback, + bool async); + virtual ~PrefService(); + + // Lands pending writes to disk. This should only be used if we need to save + // immediately (basically, during shutdown). + void CommitPendingWrite(); + + // Schedule a write if there is any lossy data pending. Unlike + // CommitPendingWrite() this does not immediately sync to disk, instead it + // triggers an eventual write if there is lossy data pending and if there + // isn't one scheduled already. + void SchedulePendingLossyWrites(); + + // Returns true if the preference for the given preference name is available + // and is managed. + bool IsManagedPreference(const std::string& pref_name) const; + + // Returns true if the preference for the given preference name is available + // and is controlled by the parent/guardian of the child Account. + bool IsPreferenceManagedByCustodian(const std::string& pref_name) const; + + // Returns |true| if a preference with the given name is available and its + // value can be changed by the user. + bool IsUserModifiablePreference(const std::string& pref_name) const; + + // Look up a preference. Returns NULL if the preference is not + // registered. + const PrefService::Preference* FindPreference(const std::string& path) const; + + // If the path is valid and the value at the end of the path matches the type + // specified, it will return the specified value. Otherwise, the default + // value (set when the pref was registered) will be returned. + bool GetBoolean(const std::string& path) const; + int GetInteger(const std::string& path) const; + double GetDouble(const std::string& path) const; + std::string GetString(const std::string& path) const; + base::FilePath GetFilePath(const std::string& path) const; + + // Returns the branch if it exists, or the registered default value otherwise. + // Note that |path| must point to a registered preference. In that case, these + // functions will never return NULL. + const base::DictionaryValue* GetDictionary(const std::string& path) const; + const base::ListValue* GetList(const std::string& path) const; + + // Removes a user pref and restores the pref to its default value. + void ClearPref(const std::string& path); + + // If the path is valid (i.e., registered), update the pref value in the user + // prefs. + // To set the value of dictionary or list values in the pref tree use + // Set(), but to modify the value of a dictionary or list use either + // ListPrefUpdate or DictionaryPrefUpdate from scoped_user_pref_update.h. + void Set(const std::string& path, const base::Value& value); + void SetBoolean(const std::string& path, bool value); + void SetInteger(const std::string& path, int value); + void SetDouble(const std::string& path, double value); + void SetString(const std::string& path, const std::string& value); + void SetFilePath(const std::string& path, const base::FilePath& value); + + // Int64 helper methods that actually store the given value as a string. + // Note that if obtaining the named value via GetDictionary or GetList, the + // Value type will be TYPE_STRING. + void SetInt64(const std::string& path, int64_t value); + int64_t GetInt64(const std::string& path) const; + + // As above, but for unsigned values. + void SetUint64(const std::string& path, uint64_t value); + uint64_t GetUint64(const std::string& path) const; + + // Returns the value of the given preference, from the user pref store. If + // the preference is not set in the user pref store, returns NULL. + const base::Value* GetUserPrefValue(const std::string& path) const; + + // Changes the default value for a preference. Takes ownership of |value|. + // + // Will cause a pref change notification to be fired if this causes + // the effective value to change. + void SetDefaultPrefValue(const std::string& path, base::Value* value); + + // Returns the default value of the given preference. |path| must point to a + // registered preference. In that case, will never return NULL. + const base::Value* GetDefaultPrefValue(const std::string& path) const; + + // Returns true if a value has been set for the specified path. + // NOTE: this is NOT the same as FindPreference. In particular + // FindPreference returns whether RegisterXXX has been invoked, where as + // this checks if a value exists for the path. + bool HasPrefPath(const std::string& path) const; + + // Returns a dictionary with effective preference values. + scoped_ptr<base::DictionaryValue> GetPreferenceValues() const; + + // Returns a dictionary with effective preference values, omitting prefs that + // are at their default values. + scoped_ptr<base::DictionaryValue> GetPreferenceValuesOmitDefaults() const; + + // Returns a dictionary with effective preference values. Contrary to + // GetPreferenceValues(), the paths of registered preferences are not split on + // '.' characters. If a registered preference stores a dictionary, however, + // the hierarchical structure inside the preference will be preserved. + // For example, if "foo.bar" is a registered preference, the result could look + // like this: + // {"foo.bar": {"a": {"b": true}}}. + scoped_ptr<base::DictionaryValue> GetPreferenceValuesWithoutPathExpansion() + const; + + bool ReadOnly() const; + + PrefInitializationStatus GetInitializationStatus() const; + + // Tell our PrefValueStore to update itself to |command_line_store|. + // Takes ownership of the store. + virtual void UpdateCommandLinePrefStore(PrefStore* command_line_store); + + // We run the callback once, when initialization completes. The bool + // parameter will be set to true for successful initialization, + // false for unsuccessful. + void AddPrefInitObserver(base::Callback<void(bool)> callback); + + // Returns the PrefRegistry object for this service. You should not + // use this; the intent is for no registrations to take place after + // PrefService has been constructed. + // + // Instead of using this method, the recommended approach is to + // register all preferences for a class Xyz up front in a static + // Xyz::RegisterPrefs function, which gets invoked early in the + // application's start-up, before a PrefService is created. + // + // As an example, prefs registration in Chrome is triggered by the + // functions chrome::RegisterPrefs (for global preferences) and + // chrome::RegisterProfilePrefs (for user-specific preferences) + // implemented in chrome/browser/prefs/browser_prefs.cc. + PrefRegistry* DeprecatedGetPrefRegistry(); + + protected: + // The PrefNotifier handles registering and notifying preference observers. + // It is created and owned by this PrefService. Subclasses may access it for + // unit testing. + scoped_ptr<PrefNotifierImpl> pref_notifier_; + + // The PrefValueStore provides prioritized preference values. It is owned by + // this PrefService. Subclasses may access it for unit testing. + scoped_ptr<PrefValueStore> pref_value_store_; + + scoped_refptr<PrefRegistry> pref_registry_; + + // Pref Stores and profile that we passed to the PrefValueStore. + scoped_refptr<PersistentPrefStore> user_pref_store_; + + // Callback to call when a read error occurs. + base::Callback<void(PersistentPrefStore::PrefReadError)> read_error_callback_; + + private: + // Hash map expected to be fastest here since it minimises expensive + // string comparisons. Order is unimportant, and deletions are rare. + // Confirmed on Android where this speeded Chrome startup by roughly 50ms + // vs. std::map, and by roughly 180ms vs. std::set of Preference pointers. + typedef base::hash_map<std::string, Preference> PreferenceMap; + + // Give access to ReportUserPrefChanged() and GetMutableUserPref(). + friend class subtle::ScopedUserPrefUpdateBase; + friend class PrefServiceTest_WriteablePrefStoreFlags_Test; + + // Registration of pref change observers must be done using the + // PrefChangeRegistrar, which is declared as a friend here to grant it + // access to the otherwise protected members Add/RemovePrefObserver. + // PrefMember registers for preferences changes notification directly to + // avoid the storage overhead of the registrar, so its base class must be + // declared as a friend, too. + friend class PrefChangeRegistrar; + friend class subtle::PrefMemberBase; + + // These are protected so they can only be accessed by the friend + // classes listed above. + // + // If the pref at the given path changes, we call the observer's + // OnPreferenceChanged method. Note that observers should not call + // these methods directly but rather use a PrefChangeRegistrar to + // make sure the observer gets cleaned up properly. + // + // Virtual for testing. + virtual void AddPrefObserver(const std::string& path, PrefObserver* obs); + virtual void RemovePrefObserver(const std::string& path, PrefObserver* obs); + + // Sends notification of a changed preference. This needs to be called by + // a ScopedUserPrefUpdate if a DictionaryValue or ListValue is changed. + void ReportUserPrefChanged(const std::string& key); + + // Sets the value for this pref path in the user pref store and informs the + // PrefNotifier of the change. + void SetUserPrefValue(const std::string& path, base::Value* new_value); + + // Load preferences from storage, attempting to diagnose and handle errors. + // This should only be called from the constructor. + void InitFromStorage(bool async); + + // Used to set the value of dictionary or list values in the user pref store. + // This will create a dictionary or list if one does not exist in the user + // pref store. This method returns NULL only if you're requesting an + // unregistered pref or a non-dict/non-list pref. + // |type| may only be Values::TYPE_DICTIONARY or Values::TYPE_LIST and + // |path| must point to a registered preference of type |type|. + // Ownership of the returned value remains at the user pref store. + base::Value* GetMutableUserPref(const std::string& path, + base::Value::Type type); + + // GetPreferenceValue is the equivalent of FindPreference(path)->GetValue(), + // it has been added for performance. If is faster because it does + // not need to find or create a Preference object to get the + // value (GetValue() calls back though the preference service to + // actually get the value.). + const base::Value* GetPreferenceValue(const std::string& path) const; + + // Local cache of registered Preference objects. The pref_registry_ + // is authoritative with respect to what the types and default values + // of registered preferences are. + mutable PreferenceMap prefs_map_; + + DISALLOW_COPY_AND_ASSIGN(PrefService); +}; + +#endif // BASE_PREFS_PREF_SERVICE_H_ diff --git a/base/prefs/pref_service_factory.cc b/components/prefs/pref_service_factory.cc index 2380a86..2380a86 100644 --- a/base/prefs/pref_service_factory.cc +++ b/components/prefs/pref_service_factory.cc diff --git a/components/prefs/pref_service_factory.h b/components/prefs/pref_service_factory.h new file mode 100644 index 0000000..f84e037 --- /dev/null +++ b/components/prefs/pref_service_factory.h @@ -0,0 +1,91 @@ +// Copyright 2013 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 BASE_PREFS_PREF_SERVICE_FACTORY_H_ +#define BASE_PREFS_PREF_SERVICE_FACTORY_H_ + +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/persistent_pref_store.h" +#include "base/prefs/pref_registry.h" +#include "base/prefs/pref_store.h" + +class PrefService; + +namespace base { + +class FilePath; +class SequencedTaskRunner; + +// A class that allows convenient building of PrefService. +class BASE_PREFS_EXPORT PrefServiceFactory { + public: + PrefServiceFactory(); + virtual ~PrefServiceFactory(); + + // Functions for setting the various parameters of the PrefService to build. + void set_managed_prefs(const scoped_refptr<PrefStore>& managed_prefs) { + managed_prefs_ = managed_prefs; + } + void set_supervised_user_prefs( + const scoped_refptr<PrefStore>& supervised_user_prefs) { + supervised_user_prefs_ = supervised_user_prefs; + } + void set_extension_prefs(const scoped_refptr<PrefStore>& extension_prefs) { + extension_prefs_ = extension_prefs; + } + void set_command_line_prefs( + const scoped_refptr<PrefStore>& command_line_prefs) { + command_line_prefs_ = command_line_prefs; + } + void set_user_prefs(const scoped_refptr<PersistentPrefStore>& user_prefs) { + user_prefs_ = user_prefs; + } + void set_recommended_prefs( + const scoped_refptr<PrefStore>& recommended_prefs) { + recommended_prefs_ = recommended_prefs; + } + + // Sets up error callback for the PrefService. A do-nothing default + // is provided if this is not called. + void set_read_error_callback( + const base::Callback<void(PersistentPrefStore::PrefReadError)>& + read_error_callback) { + read_error_callback_ = read_error_callback; + } + + // Specifies to use an actual file-backed user pref store. + void SetUserPrefsFile(const base::FilePath& prefs_file, + base::SequencedTaskRunner* task_runner); + + void set_async(bool async) { + async_ = async; + } + + // Creates a PrefService object initialized with the parameters from + // this factory. + scoped_ptr<PrefService> Create(PrefRegistry* registry); + + protected: + scoped_refptr<PrefStore> managed_prefs_; + scoped_refptr<PrefStore> supervised_user_prefs_; + scoped_refptr<PrefStore> extension_prefs_; + scoped_refptr<PrefStore> command_line_prefs_; + scoped_refptr<PersistentPrefStore> user_prefs_; + scoped_refptr<PrefStore> recommended_prefs_; + + base::Callback<void(PersistentPrefStore::PrefReadError)> read_error_callback_; + + // Defaults to false. + bool async_; + + private: + DISALLOW_COPY_AND_ASSIGN(PrefServiceFactory); +}; + +} // namespace base + +#endif // BASE_PREFS_PREF_SERVICE_FACTORY_H_ diff --git a/base/prefs/pref_service_unittest.cc b/components/prefs/pref_service_unittest.cc index 649c35f..649c35f 100644 --- a/base/prefs/pref_service_unittest.cc +++ b/components/prefs/pref_service_unittest.cc diff --git a/base/prefs/pref_store.cc b/components/prefs/pref_store.cc index f286a33..f286a33 100644 --- a/base/prefs/pref_store.cc +++ b/components/prefs/pref_store.cc diff --git a/components/prefs/pref_store.h b/components/prefs/pref_store.h new file mode 100644 index 0000000..f95c8c4 --- /dev/null +++ b/components/prefs/pref_store.h @@ -0,0 +1,63 @@ +// 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 BASE_PREFS_PREF_STORE_H_ +#define BASE_PREFS_PREF_STORE_H_ + +#include <string> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/prefs/base_prefs_export.h" + +namespace base { +class Value; +} + +// This is an abstract interface for reading and writing from/to a persistent +// preference store, used by PrefService. An implementation using a JSON file +// can be found in JsonPrefStore, while an implementation without any backing +// store for testing can be found in TestingPrefStore. Furthermore, there is +// CommandLinePrefStore, which bridges command line options to preferences and +// ConfigurationPolicyPrefStore, which is used for hooking up configuration +// policy with the preference subsystem. +class BASE_PREFS_EXPORT PrefStore : public base::RefCounted<PrefStore> { + public: + // Observer interface for monitoring PrefStore. + class BASE_PREFS_EXPORT Observer { + public: + // Called when the value for the given |key| in the store changes. + virtual void OnPrefValueChanged(const std::string& key) = 0; + // Notification about the PrefStore being fully initialized. + virtual void OnInitializationCompleted(bool succeeded) = 0; + + protected: + virtual ~Observer() {} + }; + + PrefStore() {} + + // Add and remove observers. + virtual void AddObserver(Observer* observer) {} + virtual void RemoveObserver(Observer* observer) {} + virtual bool HasObservers() const; + + // Whether the store has completed all asynchronous initialization. + virtual bool IsInitializationComplete() const; + + // Get the value for a given preference |key| and stores it in |*result|. + // |*result| is only modified if the return value is true and if |result| + // is not NULL. Ownership of the |*result| value remains with the PrefStore. + virtual bool GetValue(const std::string& key, + const base::Value** result) const = 0; + + protected: + friend class base::RefCounted<PrefStore>; + virtual ~PrefStore() {} + + private: + DISALLOW_COPY_AND_ASSIGN(PrefStore); +}; + +#endif // BASE_PREFS_PREF_STORE_H_ diff --git a/base/prefs/pref_store_observer_mock.cc b/components/prefs/pref_store_observer_mock.cc index f1a31bb..f1a31bb 100644 --- a/base/prefs/pref_store_observer_mock.cc +++ b/components/prefs/pref_store_observer_mock.cc diff --git a/components/prefs/pref_store_observer_mock.h b/components/prefs/pref_store_observer_mock.h new file mode 100644 index 0000000..1b24b4e --- /dev/null +++ b/components/prefs/pref_store_observer_mock.h @@ -0,0 +1,35 @@ +// 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 BASE_PREFS_PREF_STORE_OBSERVER_MOCK_H_ +#define BASE_PREFS_PREF_STORE_OBSERVER_MOCK_H_ + +#include <string> +#include <vector> + +#include "base/compiler_specific.h" +#include "base/macros.h" +#include "base/prefs/pref_store.h" + +// A mock implementation of PrefStore::Observer. +class PrefStoreObserverMock : public PrefStore::Observer { + public: + PrefStoreObserverMock(); + ~PrefStoreObserverMock() override; + + void VerifyAndResetChangedKey(const std::string& expected); + + // PrefStore::Observer implementation + void OnPrefValueChanged(const std::string& key) override; + void OnInitializationCompleted(bool success) override; + + std::vector<std::string> changed_keys; + bool initialized; + bool initialization_success; // Only valid if |initialized|. + + private: + DISALLOW_COPY_AND_ASSIGN(PrefStoreObserverMock); +}; + +#endif // BASE_PREFS_PREF_STORE_OBSERVER_MOCK_H_ diff --git a/base/prefs/pref_value_map.cc b/components/prefs/pref_value_map.cc index 2340e3c..2340e3c 100644 --- a/base/prefs/pref_value_map.cc +++ b/components/prefs/pref_value_map.cc diff --git a/components/prefs/pref_value_map.h b/components/prefs/pref_value_map.h new file mode 100644 index 0000000..349fe68 --- /dev/null +++ b/components/prefs/pref_value_map.h @@ -0,0 +1,91 @@ +// 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 BASE_PREFS_PREF_VALUE_MAP_H_ +#define BASE_PREFS_PREF_VALUE_MAP_H_ + +#include <string> +#include <vector> + +#include "base/containers/scoped_ptr_hash_map.h" +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "base/prefs/base_prefs_export.h" + +namespace base { +class Value; +} + +// A generic string to value map used by the PrefStore implementations. +class BASE_PREFS_EXPORT PrefValueMap { + public: + using Map = base::ScopedPtrHashMap<std::string, scoped_ptr<base::Value>>; + using iterator = Map::iterator; + using const_iterator = Map::const_iterator; + + PrefValueMap(); + virtual ~PrefValueMap(); + + // Gets the value for |key| and stores it in |value|. Ownership remains with + // the map. Returns true if a value is present. If not, |value| is not + // touched. + bool GetValue(const std::string& key, const base::Value** value) const; + bool GetValue(const std::string& key, base::Value** value); + + // Sets a new |value| for |key|. |value| must be non-null. Returns true if the + // value changed. + bool SetValue(const std::string& key, scoped_ptr<base::Value> value); + + // Removes the value for |key| from the map. Returns true if a value was + // removed. + bool RemoveValue(const std::string& key); + + // Clears the map. + void Clear(); + + // Swaps the contents of two maps. + void Swap(PrefValueMap* other); + + iterator begin(); + iterator end(); + const_iterator begin() const; + const_iterator end() const; + + // Gets a boolean value for |key| and stores it in |value|. Returns true if + // the value was found and of the proper type. + bool GetBoolean(const std::string& key, bool* value) const; + + // Sets the value for |key| to the boolean |value|. + void SetBoolean(const std::string& key, bool value); + + // Gets a string value for |key| and stores it in |value|. Returns true if + // the value was found and of the proper type. + bool GetString(const std::string& key, std::string* value) const; + + // Sets the value for |key| to the string |value|. + void SetString(const std::string& key, const std::string& value); + + // Gets an int value for |key| and stores it in |value|. Returns true if + // the value was found and of the proper type. + bool GetInteger(const std::string& key, int* value) const; + + // Sets the value for |key| to the int |value|. + void SetInteger(const std::string& key, const int value); + + // Sets the value for |key| to the double |value|. + void SetDouble(const std::string& key, const double value); + + // Compares this value map against |other| and stores all key names that have + // different values in |differing_keys|. This includes keys that are present + // only in one of the maps. + void GetDifferingKeys(const PrefValueMap* other, + std::vector<std::string>* differing_keys) const; + + private: + Map prefs_; + + DISALLOW_COPY_AND_ASSIGN(PrefValueMap); +}; + +#endif // BASE_PREFS_PREF_VALUE_MAP_H_ diff --git a/base/prefs/pref_value_map_unittest.cc b/components/prefs/pref_value_map_unittest.cc index f78c999..f78c999 100644 --- a/base/prefs/pref_value_map_unittest.cc +++ b/components/prefs/pref_value_map_unittest.cc diff --git a/base/prefs/pref_value_store.cc b/components/prefs/pref_value_store.cc index fe7cd67..fe7cd67 100644 --- a/base/prefs/pref_value_store.cc +++ b/components/prefs/pref_value_store.cc diff --git a/components/prefs/pref_value_store.h b/components/prefs/pref_value_store.h new file mode 100644 index 0000000..8ec8c59 --- /dev/null +++ b/components/prefs/pref_value_store.h @@ -0,0 +1,260 @@ +// 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 BASE_PREFS_PREF_VALUE_STORE_H_ +#define BASE_PREFS_PREF_VALUE_STORE_H_ + +#include <map> +#include <string> +#include <vector> + +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/pref_store.h" +#include "base/values.h" + +class PrefNotifier; +class PrefStore; + +// The PrefValueStore manages various sources of values for Preferences +// (e.g., configuration policies, extensions, and user settings). It returns +// the value of a Preference from the source with the highest priority, and +// allows setting user-defined values for preferences that are not managed. +// +// Unless otherwise explicitly noted, all of the methods of this class must +// be called on the UI thread. +class BASE_PREFS_EXPORT PrefValueStore { + public: + typedef base::Callback<void(const std::string&)> PrefChangedCallback; + + // In decreasing order of precedence: + // |managed_prefs| contains all preferences from mandatory policies. + // |supervised_user_prefs| contains all preferences from supervised user + // settings, i.e. settings configured for a supervised user by their + // custodian. + // |extension_prefs| contains preference values set by extensions. + // |command_line_prefs| contains preference values set by command-line + // switches. + // |user_prefs| contains all user-set preference values. + // |recommended_prefs| contains all preferences from recommended policies. + // |default_prefs| contains application-default preference values. It must + // be non-null if any preferences are to be registered. + // + // |pref_notifier| facilitates broadcasting preference change notifications + // to the world. + PrefValueStore(PrefStore* managed_prefs, + PrefStore* supervised_user_prefs, + PrefStore* extension_prefs, + PrefStore* command_line_prefs, + PrefStore* user_prefs, + PrefStore* recommended_prefs, + PrefStore* default_prefs, + PrefNotifier* pref_notifier); + virtual ~PrefValueStore(); + + // Creates a clone of this PrefValueStore with PrefStores overwritten + // by the parameters passed, if unequal NULL. + PrefValueStore* CloneAndSpecialize(PrefStore* managed_prefs, + PrefStore* supervised_user_prefs, + PrefStore* extension_prefs, + PrefStore* command_line_prefs, + PrefStore* user_prefs, + PrefStore* recommended_prefs, + PrefStore* default_prefs, + PrefNotifier* pref_notifier); + + // A PrefValueStore can have exactly one callback that is directly + // notified of preferences changing in the store. This does not + // filter through the PrefNotifier mechanism, which may not forward + // certain changes (e.g. unregistered prefs). + void set_callback(const PrefChangedCallback& callback); + + // Gets the value for the given preference name that has the specified value + // type. Values stored in a PrefStore that have the matching |name| but + // a non-matching |type| are silently skipped. Returns true if a valid value + // was found in any of the available PrefStores. Most callers should use + // Preference::GetValue() instead of calling this method directly. + bool GetValue(const std::string& name, + base::Value::Type type, + const base::Value** out_value) const; + + // Gets the recommended value for the given preference name that has the + // specified value type. A value stored in the recommended PrefStore that has + // the matching |name| but a non-matching |type| is silently ignored. Returns + // true if a valid value was found. Most callers should use + // Preference::GetRecommendedValue() instead of calling this method directly. + bool GetRecommendedValue(const std::string& name, + base::Value::Type type, + const base::Value** out_value) const; + + // These methods return true if a preference with the given name is in the + // indicated pref store, even if that value is currently being overridden by + // a higher-priority source. + bool PrefValueInManagedStore(const std::string& name) const; + bool PrefValueInSupervisedStore(const std::string& name) const; + bool PrefValueInExtensionStore(const std::string& name) const; + bool PrefValueInUserStore(const std::string& name) const; + + // These methods return true if a preference with the given name is actually + // being controlled by the indicated pref store and not being overridden by + // a higher-priority source. + bool PrefValueFromExtensionStore(const std::string& name) const; + bool PrefValueFromUserStore(const std::string& name) const; + bool PrefValueFromRecommendedStore(const std::string& name) const; + bool PrefValueFromDefaultStore(const std::string& name) const; + + // Check whether a Preference value is modifiable by the user, i.e. whether + // there is no higher-priority source controlling it. + bool PrefValueUserModifiable(const std::string& name) const; + + // Check whether a Preference value is modifiable by an extension, i.e. + // whether there is no higher-priority source controlling it. + bool PrefValueExtensionModifiable(const std::string& name) const; + + // Update the command line PrefStore with |command_line_prefs|. + void UpdateCommandLinePrefStore(PrefStore* command_line_prefs); + + private: + // PrefStores must be listed here in order from highest to lowest priority. + // MANAGED contains all managed preference values that are provided by + // mandatory policies (e.g. Windows Group Policy or cloud policy). + // SUPERVISED_USER contains preferences that are valid for supervised users. + // EXTENSION contains preference values set by extensions. + // COMMAND_LINE contains preference values set by command-line switches. + // USER contains all user-set preference values. + // RECOMMENDED contains all preferences that are provided by recommended + // policies. + // DEFAULT contains all application default preference values. + enum PrefStoreType { + // INVALID_STORE is not associated with an actual PrefStore but used as + // an invalid marker, e.g. as a return value. + INVALID_STORE = -1, + MANAGED_STORE = 0, + SUPERVISED_USER_STORE, + EXTENSION_STORE, + COMMAND_LINE_STORE, + USER_STORE, + RECOMMENDED_STORE, + DEFAULT_STORE, + PREF_STORE_TYPE_MAX = DEFAULT_STORE + }; + + // Keeps a PrefStore reference on behalf of the PrefValueStore and monitors + // the PrefStore for changes, forwarding notifications to PrefValueStore. This + // indirection is here for the sake of disambiguating notifications from the + // individual PrefStores. + class PrefStoreKeeper : public PrefStore::Observer { + public: + PrefStoreKeeper(); + ~PrefStoreKeeper() override; + + // Takes ownership of |pref_store|. + void Initialize(PrefValueStore* store, + PrefStore* pref_store, + PrefStoreType type); + + PrefStore* store() { return pref_store_.get(); } + const PrefStore* store() const { return pref_store_.get(); } + + private: + // PrefStore::Observer implementation. + void OnPrefValueChanged(const std::string& key) override; + void OnInitializationCompleted(bool succeeded) override; + + // PrefValueStore this keeper is part of. + PrefValueStore* pref_value_store_; + + // The PrefStore managed by this keeper. + scoped_refptr<PrefStore> pref_store_; + + // Type of the pref store. + PrefStoreType type_; + + DISALLOW_COPY_AND_ASSIGN(PrefStoreKeeper); + }; + + typedef std::map<std::string, base::Value::Type> PrefTypeMap; + + // Returns true if the preference with the given name has a value in the + // given PrefStoreType, of the same value type as the preference was + // registered with. + bool PrefValueInStore(const std::string& name, PrefStoreType store) const; + + // Returns true if a preference has an explicit value in any of the + // stores in the range specified by |first_checked_store| and + // |last_checked_store|, even if that value is currently being + // overridden by a higher-priority store. + bool PrefValueInStoreRange(const std::string& name, + PrefStoreType first_checked_store, + PrefStoreType last_checked_store) const; + + // Returns the pref store type identifying the source that controls the + // Preference identified by |name|. If none of the sources has a value, + // INVALID_STORE is returned. In practice, the default PrefStore + // should always have a value for any registered preferencem, so INVALID_STORE + // indicates an error. + PrefStoreType ControllingPrefStoreForPref(const std::string& name) const; + + // Get a value from the specified |store|. + bool GetValueFromStore(const std::string& name, + PrefStoreType store, + const base::Value** out_value) const; + + // Get a value from the specified |store| if its |type| matches. + bool GetValueFromStoreWithType(const std::string& name, + base::Value::Type type, + PrefStoreType store, + const base::Value** out_value) const; + + // Called upon changes in individual pref stores in order to determine whether + // the user-visible pref value has changed. Triggers the change notification + // if the effective value of the preference has changed, or if the store + // controlling the pref has changed. + void NotifyPrefChanged(const std::string& path, PrefStoreType new_store); + + // Called from the PrefStoreKeeper implementation when a pref value for |key| + // changed in the pref store for |type|. + void OnPrefValueChanged(PrefStoreType type, const std::string& key); + + // Handle the event that the store for |type| has completed initialization. + void OnInitializationCompleted(PrefStoreType type, bool succeeded); + + // Initializes a pref store keeper. Sets up a PrefStoreKeeper that will take + // ownership of the passed |pref_store|. + void InitPrefStore(PrefStoreType type, PrefStore* pref_store); + + // Checks whether initialization is completed and tells the notifier if that + // is the case. + void CheckInitializationCompleted(); + + // Get the PrefStore pointer for the given type. May return NULL if there is + // no PrefStore for that type. + PrefStore* GetPrefStore(PrefStoreType type) { + return pref_stores_[type].store(); + } + const PrefStore* GetPrefStore(PrefStoreType type) const { + return pref_stores_[type].store(); + } + + // Keeps the PrefStore references in order of precedence. + PrefStoreKeeper pref_stores_[PREF_STORE_TYPE_MAX + 1]; + + PrefChangedCallback pref_changed_callback_; + + // Used for generating notifications. This is a weak reference, + // since the notifier is owned by the corresponding PrefService. + PrefNotifier* pref_notifier_; + + // A mapping of preference names to their registered types. + PrefTypeMap pref_types_; + + // True if not all of the PrefStores were initialized successfully. + bool initialization_failed_; + + DISALLOW_COPY_AND_ASSIGN(PrefValueStore); +}; + +#endif // BASE_PREFS_PREF_VALUE_STORE_H_ diff --git a/base/prefs/pref_value_store_unittest.cc b/components/prefs/pref_value_store_unittest.cc index e214adf..e214adf 100644 --- a/base/prefs/pref_value_store_unittest.cc +++ b/components/prefs/pref_value_store_unittest.cc diff --git a/components/prefs/prefs.gyp b/components/prefs/prefs.gyp new file mode 100644 index 0000000..ed9c58a --- /dev/null +++ b/components/prefs/prefs.gyp @@ -0,0 +1,87 @@ +# Copyright (c) 2013 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. + +{ + 'targets': [ + { + 'target_name': 'prefs', + 'type': '<(component)', + 'dependencies': [ + '../../base/base.gyp:base', + ], + 'include_dirs': [ + '../..', + ], + 'defines': [ + 'BASE_PREFS_IMPLEMENTATION', + ], + 'sources': [ + 'default_pref_store.cc', + 'default_pref_store.h', + 'json_pref_store.cc', + 'json_pref_store.h', + 'overlay_user_pref_store.cc', + 'overlay_user_pref_store.h', + 'pref_change_registrar.cc', + 'pref_change_registrar.h', + 'pref_member.cc', + 'pref_member.h', + 'pref_notifier_impl.cc', + 'pref_notifier_impl.h', + 'pref_registry.cc', + 'pref_registry.h', + 'pref_registry_simple.cc', + 'pref_registry_simple.h', + 'pref_service.cc', + 'pref_service.h', + 'pref_service_factory.cc', + 'pref_service_factory.h', + 'pref_store.cc', + 'pref_store.h', + 'pref_value_map.cc', + 'pref_value_map.h', + 'pref_value_store.cc', + 'pref_value_store.h', + 'scoped_user_pref_update.cc', + 'scoped_user_pref_update.h', + 'value_map_pref_store.cc', + 'value_map_pref_store.h', + ], + 'conditions': [ + ['OS!="ios"', { + 'sources': [ + 'base_prefs_export.h', + 'persistent_pref_store.h', + 'pref_filter.h', + 'pref_notifier.h', + 'pref_observer.h', + 'writeable_pref_store.h', + ] + }] + ], + }, + { + 'target_name': 'prefs_test_support', + 'type': 'static_library', + 'include_dirs': [ + '../..', + ], + 'dependencies': [ + 'prefs', + '<(DEPTH)/testing/gmock.gyp:gmock', + '<(DEPTH)/testing/gtest.gyp:gtest', + ], + 'sources': [ + 'mock_pref_change_callback.cc', + 'mock_pref_change_callback.h', + 'pref_store_observer_mock.cc', + 'pref_store_observer_mock.h', + 'testing_pref_service.cc', + 'testing_pref_service.h', + 'testing_pref_store.cc', + 'testing_pref_store.h', + ], + }, + ], +} diff --git a/base/prefs/scoped_user_pref_update.cc b/components/prefs/scoped_user_pref_update.cc index 1440a57..1440a57 100644 --- a/base/prefs/scoped_user_pref_update.cc +++ b/components/prefs/scoped_user_pref_update.cc diff --git a/components/prefs/scoped_user_pref_update.h b/components/prefs/scoped_user_pref_update.h new file mode 100644 index 0000000..29ad852 --- /dev/null +++ b/components/prefs/scoped_user_pref_update.h @@ -0,0 +1,108 @@ +// Copyright 2013 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. +// +// A helper class that assists preferences in firing notifications when lists +// or dictionaries are changed. + +#ifndef BASE_PREFS_SCOPED_USER_PREF_UPDATE_H_ +#define BASE_PREFS_SCOPED_USER_PREF_UPDATE_H_ + +#include <string> + +#include "base/macros.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/pref_service.h" +#include "base/threading/non_thread_safe.h" +#include "base/values.h" + +class PrefService; + +namespace base { +class DictionaryValue; +class ListValue; +} + +namespace subtle { + +// Base class for ScopedUserPrefUpdateTemplate that contains the parts +// that do not depend on ScopedUserPrefUpdateTemplate's template parameter. +// +// We need this base class mostly for making it a friend of PrefService +// and getting access to PrefService::GetMutableUserPref and +// PrefService::ReportUserPrefChanged. +class BASE_PREFS_EXPORT ScopedUserPrefUpdateBase : public base::NonThreadSafe { + protected: + ScopedUserPrefUpdateBase(PrefService* service, const std::string& path); + + // Calls Notify(). + ~ScopedUserPrefUpdateBase(); + + // Sets |value_| to |service_|->GetMutableUserPref and returns it. + base::Value* GetValueOfType(base::Value::Type type); + + private: + // If |value_| is not null, triggers a notification of PrefObservers and + // resets |value_|. + void Notify(); + + // Weak pointer. + PrefService* service_; + // Path of the preference being updated. + std::string path_; + // Cache of value from user pref store (set between Get() and Notify() calls). + base::Value* value_; + + DISALLOW_COPY_AND_ASSIGN(ScopedUserPrefUpdateBase); +}; + +} // namespace subtle + +// Class to support modifications to DictionaryValues and ListValues while +// guaranteeing that PrefObservers are notified of changed values. +// +// This class may only be used on the UI thread as it requires access to the +// PrefService. +template <typename T, base::Value::Type type_enum_value> +class ScopedUserPrefUpdate : public subtle::ScopedUserPrefUpdateBase { + public: + ScopedUserPrefUpdate(PrefService* service, const std::string& path) + : ScopedUserPrefUpdateBase(service, path) {} + + // Triggers an update notification if Get() was called. + virtual ~ScopedUserPrefUpdate() {} + + // Returns a mutable |T| instance that + // - is already in the user pref store, or + // - is (silently) created and written to the user pref store if none existed + // before. + // + // Calling Get() implies that an update notification is necessary at + // destruction time. + // + // The ownership of the return value remains with the user pref store. + // Virtual so it can be overriden in subclasses that transform the value + // before returning it (for example to return a subelement of a dictionary). + virtual T* Get() { + return static_cast<T*>(GetValueOfType(type_enum_value)); + } + + T& operator*() { + return *Get(); + } + + T* operator->() { + return Get(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(ScopedUserPrefUpdate); +}; + +typedef ScopedUserPrefUpdate<base::DictionaryValue, + base::Value::TYPE_DICTIONARY> + DictionaryPrefUpdate; +typedef ScopedUserPrefUpdate<base::ListValue, base::Value::TYPE_LIST> + ListPrefUpdate; + +#endif // BASE_PREFS_SCOPED_USER_PREF_UPDATE_H_ diff --git a/base/prefs/scoped_user_pref_update_unittest.cc b/components/prefs/scoped_user_pref_update_unittest.cc index 48e3dc4..48e3dc4 100644 --- a/base/prefs/scoped_user_pref_update_unittest.cc +++ b/components/prefs/scoped_user_pref_update_unittest.cc diff --git a/base/prefs/testing_pref_service.cc b/components/prefs/testing_pref_service.cc index 5899376..5899376 100644 --- a/base/prefs/testing_pref_service.cc +++ b/components/prefs/testing_pref_service.cc diff --git a/components/prefs/testing_pref_service.h b/components/prefs/testing_pref_service.h new file mode 100644 index 0000000..85a2879 --- /dev/null +++ b/components/prefs/testing_pref_service.h @@ -0,0 +1,196 @@ +// 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 BASE_PREFS_TESTING_PREF_SERVICE_H_ +#define BASE_PREFS_TESTING_PREF_SERVICE_H_ + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/prefs/pref_registry.h" +#include "base/prefs/pref_service.h" +#include "base/prefs/testing_pref_store.h" + +class PrefNotifierImpl; +class PrefRegistrySimple; +class TestingPrefStore; + +// A PrefService subclass for testing. It operates totally in memory and +// provides additional API for manipulating preferences at the different levels +// (managed, extension, user) conveniently. +// +// Use this via its specializations, e.g. TestingPrefServiceSimple. +template <class SuperPrefService, class ConstructionPrefRegistry> +class TestingPrefServiceBase : public SuperPrefService { + public: + virtual ~TestingPrefServiceBase(); + + // Read the value of a preference from the managed layer. Returns NULL if the + // preference is not defined at the managed layer. + const base::Value* GetManagedPref(const std::string& path) const; + + // Set a preference on the managed layer and fire observers if the preference + // changed. Assumes ownership of |value|. + void SetManagedPref(const std::string& path, base::Value* value); + + // Clear the preference on the managed layer and fire observers if the + // preference has been defined previously. + void RemoveManagedPref(const std::string& path); + + // Similar to the above, but for user preferences. + const base::Value* GetUserPref(const std::string& path) const; + void SetUserPref(const std::string& path, base::Value* value); + void RemoveUserPref(const std::string& path); + + // Similar to the above, but for recommended policy preferences. + const base::Value* GetRecommendedPref(const std::string& path) const; + void SetRecommendedPref(const std::string& path, base::Value* value); + void RemoveRecommendedPref(const std::string& path); + + // Do-nothing implementation for TestingPrefService. + static void HandleReadError(PersistentPrefStore::PrefReadError error) {} + + protected: + TestingPrefServiceBase( + TestingPrefStore* managed_prefs, + TestingPrefStore* user_prefs, + TestingPrefStore* recommended_prefs, + ConstructionPrefRegistry* pref_registry, + PrefNotifierImpl* pref_notifier); + + private: + // Reads the value of the preference indicated by |path| from |pref_store|. + // Returns NULL if the preference was not found. + const base::Value* GetPref(TestingPrefStore* pref_store, + const std::string& path) const; + + // Sets the value for |path| in |pref_store|. + void SetPref(TestingPrefStore* pref_store, + const std::string& path, + base::Value* value); + + // Removes the preference identified by |path| from |pref_store|. + void RemovePref(TestingPrefStore* pref_store, const std::string& path); + + // Pointers to the pref stores our value store uses. + scoped_refptr<TestingPrefStore> managed_prefs_; + scoped_refptr<TestingPrefStore> user_prefs_; + scoped_refptr<TestingPrefStore> recommended_prefs_; + + DISALLOW_COPY_AND_ASSIGN(TestingPrefServiceBase); +}; + +// Test version of PrefService. +class TestingPrefServiceSimple + : public TestingPrefServiceBase<PrefService, PrefRegistry> { + public: + TestingPrefServiceSimple(); + ~TestingPrefServiceSimple() override; + + // This is provided as a convenience for registering preferences on + // an existing TestingPrefServiceSimple instance. On a production + // PrefService you would do all registrations before constructing + // it, passing it a PrefRegistry via its constructor (or via + // e.g. PrefServiceFactory). + PrefRegistrySimple* registry(); + + private: + DISALLOW_COPY_AND_ASSIGN(TestingPrefServiceSimple); +}; + +template<> +TestingPrefServiceBase<PrefService, PrefRegistry>::TestingPrefServiceBase( + TestingPrefStore* managed_prefs, + TestingPrefStore* user_prefs, + TestingPrefStore* recommended_prefs, + PrefRegistry* pref_registry, + PrefNotifierImpl* pref_notifier); + +template<class SuperPrefService, class ConstructionPrefRegistry> +TestingPrefServiceBase< + SuperPrefService, ConstructionPrefRegistry>::~TestingPrefServiceBase() { +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +const base::Value* TestingPrefServiceBase< + SuperPrefService, + ConstructionPrefRegistry>::GetManagedPref(const std::string& path) const { + return GetPref(managed_prefs_.get(), path); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: + SetManagedPref(const std::string& path, base::Value* value) { + SetPref(managed_prefs_.get(), path, value); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: + RemoveManagedPref(const std::string& path) { + RemovePref(managed_prefs_.get(), path); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +const base::Value* +TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>::GetUserPref( + const std::string& path) const { + return GetPref(user_prefs_.get(), path); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: + SetUserPref(const std::string& path, base::Value* value) { + SetPref(user_prefs_.get(), path, value); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: + RemoveUserPref(const std::string& path) { + RemovePref(user_prefs_.get(), path); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +const base::Value* +TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: + GetRecommendedPref(const std::string& path) const { + return GetPref(recommended_prefs_, path); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: + SetRecommendedPref(const std::string& path, base::Value* value) { + SetPref(recommended_prefs_.get(), path, value); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: + RemoveRecommendedPref(const std::string& path) { + RemovePref(recommended_prefs_.get(), path); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +const base::Value* +TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>::GetPref( + TestingPrefStore* pref_store, + const std::string& path) const { + const base::Value* res; + return pref_store->GetValue(path, &res) ? res : NULL; +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: + SetPref(TestingPrefStore* pref_store, + const std::string& path, + base::Value* value) { + pref_store->SetValue(path, make_scoped_ptr(value), + WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); +} + +template <class SuperPrefService, class ConstructionPrefRegistry> +void TestingPrefServiceBase<SuperPrefService, ConstructionPrefRegistry>:: + RemovePref(TestingPrefStore* pref_store, const std::string& path) { + pref_store->RemoveValue(path, WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); +} + +#endif // BASE_PREFS_TESTING_PREF_SERVICE_H_ diff --git a/base/prefs/testing_pref_store.cc b/components/prefs/testing_pref_store.cc index 33e1dc2..33e1dc2 100644 --- a/base/prefs/testing_pref_store.cc +++ b/components/prefs/testing_pref_store.cc diff --git a/components/prefs/testing_pref_store.h b/components/prefs/testing_pref_store.h new file mode 100644 index 0000000..713e69a --- /dev/null +++ b/components/prefs/testing_pref_store.h @@ -0,0 +1,114 @@ +// 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 BASE_PREFS_TESTING_PREF_STORE_H_ +#define BASE_PREFS_TESTING_PREF_STORE_H_ + +#include <stdint.h> + +#include <string> + +#include "base/compiler_specific.h" +#include "base/macros.h" +#include "base/observer_list.h" +#include "base/prefs/persistent_pref_store.h" +#include "base/prefs/pref_value_map.h" + +// |TestingPrefStore| is a preference store implementation that allows tests to +// explicitly manipulate the contents of the store, triggering notifications +// where appropriate. +class TestingPrefStore : public PersistentPrefStore { + public: + TestingPrefStore(); + + // Overriden from PrefStore. + bool GetValue(const std::string& key, + const base::Value** result) const override; + void AddObserver(PrefStore::Observer* observer) override; + void RemoveObserver(PrefStore::Observer* observer) override; + bool HasObservers() const override; + bool IsInitializationComplete() const override; + + // PersistentPrefStore overrides: + bool GetMutableValue(const std::string& key, base::Value** result) override; + void ReportValueChanged(const std::string& key, uint32_t flags) override; + void SetValue(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) override; + void SetValueSilently(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) override; + void RemoveValue(const std::string& key, uint32_t flags) override; + bool ReadOnly() const override; + PrefReadError GetReadError() const override; + PersistentPrefStore::PrefReadError ReadPrefs() override; + void ReadPrefsAsync(ReadErrorDelegate* error_delegate) override; + void CommitPendingWrite() override; + void SchedulePendingLossyWrites() override; + + // Marks the store as having completed initialization. + void SetInitializationCompleted(); + + // Used for tests to trigger notifications explicitly. + void NotifyPrefValueChanged(const std::string& key); + void NotifyInitializationCompleted(); + + // Some convenience getters/setters. + void SetString(const std::string& key, const std::string& value); + void SetInteger(const std::string& key, int value); + void SetBoolean(const std::string& key, bool value); + + bool GetString(const std::string& key, std::string* value) const; + bool GetInteger(const std::string& key, int* value) const; + bool GetBoolean(const std::string& key, bool* value) const; + + // Determines whether ReadPrefsAsync completes immediately. Defaults to false + // (non-blocking). To block, invoke this with true (blocking) before the call + // to ReadPrefsAsync. To unblock, invoke again with false (non-blocking) after + // the call to ReadPrefsAsync. + void SetBlockAsyncRead(bool block_async_read); + + // Getter and Setter methods for setting and getting the state of the + // |TestingPrefStore|. + virtual void set_read_only(bool read_only); + void set_read_success(bool read_success); + void set_read_error(PersistentPrefStore::PrefReadError read_error); + bool committed() { return committed_; } + + protected: + ~TestingPrefStore() override; + + private: + // Stores the preference values. + PrefValueMap prefs_; + + // Flag that indicates if the PrefStore is read-only + bool read_only_; + + // The result to pass to PrefStore::Observer::OnInitializationCompleted + bool read_success_; + + // The result to return from ReadPrefs or ReadPrefsAsync. + PersistentPrefStore::PrefReadError read_error_; + + // Whether a call to ReadPrefsAsync should block. + bool block_async_read_; + + // Whether there is a pending call to ReadPrefsAsync. + bool pending_async_read_; + + // Whether initialization has been completed. + bool init_complete_; + + // Whether the store contents have been committed to disk since the last + // mutation. + bool committed_; + + scoped_ptr<ReadErrorDelegate> error_delegate_; + base::ObserverList<PrefStore::Observer, true> observers_; + + DISALLOW_COPY_AND_ASSIGN(TestingPrefStore); +}; + +#endif // BASE_PREFS_TESTING_PREF_STORE_H_ diff --git a/base/prefs/value_map_pref_store.cc b/components/prefs/value_map_pref_store.cc index fdb087f..fdb087f 100644 --- a/base/prefs/value_map_pref_store.cc +++ b/components/prefs/value_map_pref_store.cc diff --git a/components/prefs/value_map_pref_store.h b/components/prefs/value_map_pref_store.h new file mode 100644 index 0000000..eac785d --- /dev/null +++ b/components/prefs/value_map_pref_store.h @@ -0,0 +1,57 @@ +// 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 BASE_PREFS_VALUE_MAP_PREF_STORE_H_ +#define BASE_PREFS_VALUE_MAP_PREF_STORE_H_ + +#include <stdint.h> + +#include <map> +#include <string> + +#include "base/macros.h" +#include "base/observer_list.h" +#include "base/prefs/base_prefs_export.h" +#include "base/prefs/pref_value_map.h" +#include "base/prefs/writeable_pref_store.h" + +// A basic PrefStore implementation that uses a simple name-value map for +// storing the preference values. +class BASE_PREFS_EXPORT ValueMapPrefStore : public WriteablePrefStore { + public: + ValueMapPrefStore(); + + // PrefStore overrides: + bool GetValue(const std::string& key, + const base::Value** value) const override; + void AddObserver(PrefStore::Observer* observer) override; + void RemoveObserver(PrefStore::Observer* observer) override; + bool HasObservers() const override; + + // WriteablePrefStore overrides: + void SetValue(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) override; + void RemoveValue(const std::string& key, uint32_t flags) override; + bool GetMutableValue(const std::string& key, base::Value** value) override; + void ReportValueChanged(const std::string& key, uint32_t flags) override; + void SetValueSilently(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) override; + + protected: + ~ValueMapPrefStore() override; + + // Notify observers about the initialization completed event. + void NotifyInitializationCompleted(); + + private: + PrefValueMap prefs_; + + base::ObserverList<PrefStore::Observer, true> observers_; + + DISALLOW_COPY_AND_ASSIGN(ValueMapPrefStore); +}; + +#endif // BASE_PREFS_VALUE_MAP_PREF_STORE_H_ diff --git a/components/prefs/writeable_pref_store.h b/components/prefs/writeable_pref_store.h new file mode 100644 index 0000000..f7da279 --- /dev/null +++ b/components/prefs/writeable_pref_store.h @@ -0,0 +1,72 @@ +// Copyright 2014 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 BASE_PREFS_WRITEABLE_PREF_STORE_H_ +#define BASE_PREFS_WRITEABLE_PREF_STORE_H_ + +#include <stdint.h> + +#include <string> + +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "base/prefs/pref_store.h" + +namespace base { +class Value; +} + +// A pref store that can be written to as well as read from. +class BASE_PREFS_EXPORT WriteablePrefStore : public PrefStore { + public: + // PrefWriteFlags can be used to change the way a pref will be written to + // storage. + enum PrefWriteFlags : uint32_t { + // No flags are specified. + DEFAULT_PREF_WRITE_FLAGS = 0, + + // This marks the pref as "lossy". There is no strict time guarantee on when + // a lossy pref will be persisted to permanent storage when it is modified. + LOSSY_PREF_WRITE_FLAG = 1 << 1 + }; + + WriteablePrefStore() {} + + // Sets a |value| for |key| in the store. |value| must be non-NULL. |flags| is + // a bitmask of PrefWriteFlags. + virtual void SetValue(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) = 0; + + // Removes the value for |key|. + virtual void RemoveValue(const std::string& key, uint32_t flags) = 0; + + // Equivalent to PrefStore::GetValue but returns a mutable value. + virtual bool GetMutableValue(const std::string& key, + base::Value** result) = 0; + + // Triggers a value changed notification. This function needs to be called + // if one retrieves a list or dictionary with GetMutableValue and change its + // value. SetValue takes care of notifications itself. Note that + // ReportValueChanged will trigger notifications even if nothing has changed. + // |flags| is a bitmask of PrefWriteFlags. + virtual void ReportValueChanged(const std::string& key, uint32_t flags) = 0; + + // Same as SetValue, but doesn't generate notifications. This is used by + // PrefService::GetMutableUserPref() in order to put empty entries + // into the user pref store. Using SetValue is not an option since existing + // tests rely on the number of notifications generated. |flags| is a bitmask + // of PrefWriteFlags. + virtual void SetValueSilently(const std::string& key, + scoped_ptr<base::Value> value, + uint32_t flags) = 0; + + protected: + ~WriteablePrefStore() override {} + + private: + DISALLOW_COPY_AND_ASSIGN(WriteablePrefStore); +}; + +#endif // BASE_PREFS_WRITEABLE_PREF_STORE_H_ diff --git a/components/proximity_auth.gypi b/components/proximity_auth.gypi index 60f952a..13486d4 100644 --- a/components/proximity_auth.gypi +++ b/components/proximity_auth.gypi @@ -17,9 +17,9 @@ ':cryptauth_proto', ':proximity_auth_logging', '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../device/bluetooth/bluetooth.gyp:device_bluetooth', '../net/net.gyp:net', + 'prefs/prefs.gyp:prefs', ], 'sources': [ "proximity_auth/authenticator.h", diff --git a/components/proxy_config.gypi b/components/proxy_config.gypi index 985bf11..f30b9f8 100644 --- a/components/proxy_config.gypi +++ b/components/proxy_config.gypi @@ -10,10 +10,10 @@ 'type': '<(component)', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../net/net.gyp:net', '../url/url.gyp:url_lib', 'pref_registry', + 'prefs/prefs.gyp:prefs', ], 'include_dirs': [ '..', diff --git a/components/signin.gypi b/components/signin.gypi index 5682bd7..5ce36bf 100644 --- a/components/signin.gypi +++ b/components/signin.gypi @@ -39,7 +39,6 @@ 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', - '../base/base.gyp:base_prefs', '../crypto/crypto.gyp:crypto', '../google_apis/google_apis.gyp:google_apis', '../net/net.gyp:net', @@ -54,6 +53,7 @@ 'keyed_service_core', 'metrics', 'os_crypt', + 'prefs/prefs.gyp:prefs', 'signin_core_common', 'signin_core_account_id', 'webdata_common', diff --git a/components/ssl_config.gypi b/components/ssl_config.gypi index 261b26c..2e742b2 100644 --- a/components/ssl_config.gypi +++ b/components/ssl_config.gypi @@ -10,10 +10,10 @@ 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../net/net.gyp:net', 'content_settings_core_browser', 'content_settings_core_common', + 'prefs/prefs.gyp:prefs', ], 'include_dirs': [ '..', diff --git a/components/startup_metric_utils.gypi b/components/startup_metric_utils.gypi index 05599dc..83ccd89 100644 --- a/components/startup_metric_utils.gypi +++ b/components/startup_metric_utils.gypi @@ -14,8 +14,8 @@ 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', 'components.gyp:version_info', + 'prefs/prefs.gyp:prefs', ], 'include_dirs': [ '..', diff --git a/components/sync_sessions.gypi b/components/sync_sessions.gypi index 5b0e1a7..c5a22b5 100644 --- a/components/sync_sessions.gypi +++ b/components/sync_sessions.gypi @@ -13,11 +13,11 @@ ], 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../sync/sync.gyp:sync', '../url/url.gyp:url_lib', 'bookmarks_browser', 'history_core_browser', + 'prefs/prefs.gyp:prefs', 'sync_driver', ], 'sources': [ diff --git a/components/syncable_prefs.gypi b/components/syncable_prefs.gypi index 7e143a1..e4cfc43 100644 --- a/components/syncable_prefs.gypi +++ b/components/syncable_prefs.gypi @@ -10,9 +10,9 @@ 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../sync/sync.gyp:sync', 'pref_registry', + 'prefs/prefs.gyp:prefs', ], 'include_dirs': [ '..', diff --git a/components/user_manager.gypi b/components/user_manager.gypi index 3ea388b..9cb57d2 100644 --- a/components/user_manager.gypi +++ b/components/user_manager.gypi @@ -51,8 +51,8 @@ 'conditions': [ ['chromeos == 1', { 'dependencies': [ - '<(DEPTH)/base/base.gyp:base_prefs', '<(DEPTH)/components/components.gyp:session_manager_component', + '<(DEPTH)/components/prefs/prefs.gyp:prefs', '<(DEPTH)/google_apis/google_apis.gyp:google_apis', '<(DEPTH)/url/url.gyp:url_lib', ], diff --git a/components/user_prefs.gypi b/components/user_prefs.gypi index db5590f..b558435 100644 --- a/components/user_prefs.gypi +++ b/components/user_prefs.gypi @@ -9,7 +9,7 @@ 'type': '<(component)', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', + 'prefs/prefs.gyp:prefs', ], 'include_dirs': [ '..', diff --git a/components/variations.gypi b/components/variations.gypi index e880638..e67f11f 100644 --- a/components/variations.gypi +++ b/components/variations.gypi @@ -15,12 +15,12 @@ # List of dependencies is intentionally very minimal. Please avoid # adding extra dependencies without first checking with OWNERS. '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../crypto/crypto.gyp:crypto', '../third_party/mt19937ar/mt19937ar.gyp:mt19937ar', '../third_party/protobuf/protobuf.gyp:protobuf_lite', '../third_party/zlib/google/zip.gyp:compression_utils', 'crash_core_common', + 'prefs/prefs.gyp:prefs', ], 'sources': [ # Note: sources list duplicated in GN build. @@ -102,13 +102,13 @@ ], 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../net/net.gyp:net', '../ui/base/ui_base.gyp:ui_base', 'data_use_measurement_core', 'metrics', 'network_time', 'pref_registry', + 'prefs/prefs.gyp:prefs', 'variations', 'version_info', 'web_resource', diff --git a/components/wallpaper.gypi b/components/wallpaper.gypi index da83084..350117b 100644 --- a/components/wallpaper.gypi +++ b/components/wallpaper.gypi @@ -8,12 +8,12 @@ 'type': '<(component)', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../content/content.gyp:content', '../skia/skia.gyp:skia', '../ui/gfx/gfx.gyp:gfx', '../ui/gfx/gfx.gyp:gfx_geometry', '../url/url.gyp:url_lib', + 'prefs/prefs.gyp:prefs', ], 'include_dirs': [ '..', diff --git a/extensions/extensions.gyp b/extensions/extensions.gyp index ad0b6bf..59ee0072 100644 --- a/extensions/extensions.gyp +++ b/extensions/extensions.gyp @@ -107,7 +107,6 @@ 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', - '../base/base.gyp:base_prefs', '../components/components.gyp:browsing_data', '../components/components.gyp:device_event_log_component', '../components/components.gyp:guest_view_browser', @@ -123,6 +122,7 @@ '../components/components.gyp:version_info', '../components/components.gyp:web_cache_browser', '../components/components.gyp:web_modal', + '../components/prefs/prefs.gyp:prefs', '../content/content.gyp:content_browser', '../device/bluetooth/bluetooth.gyp:device_bluetooth', '../device/serial/serial.gyp:device_serial', @@ -248,9 +248,9 @@ 'type': 'static_library', 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs_test_support', '../components/components.gyp:pref_registry_test_support', '../components/components.gyp:user_prefs', + '../components/prefs/prefs.gyp:prefs_test_support', '../content/content.gyp:content_browser', '../content/content.gyp:content_common', '../content/content_shell_and_tests.gyp:test_support_content', diff --git a/extensions/shell/app_shell.gyp b/extensions/shell/app_shell.gyp index 10594be..695bb32 100644 --- a/extensions/shell/app_shell.gyp +++ b/extensions/shell/app_shell.gyp @@ -22,13 +22,13 @@ 'dependencies': [ 'app_shell_version_header', '<(DEPTH)/base/base.gyp:base', - '<(DEPTH)/base/base.gyp:base_prefs', '<(DEPTH)/components/components.gyp:devtools_discovery', '<(DEPTH)/components/components.gyp:devtools_http_handler', '<(DEPTH)/components/components.gyp:pref_registry', '<(DEPTH)/components/components.gyp:update_client', '<(DEPTH)/components/components.gyp:user_prefs', '<(DEPTH)/components/components.gyp:web_cache_renderer', + '<(DEPTH)/components/prefs/prefs.gyp:prefs', '<(DEPTH)/content/content.gyp:content', '<(DEPTH)/content/content.gyp:content_browser', '<(DEPTH)/content/content.gyp:content_gpu', diff --git a/ios/chrome/ios_chrome.gyp b/ios/chrome/ios_chrome.gyp index 5d0749d..2c918ab 100644 --- a/ios/chrome/ios_chrome.gyp +++ b/ios/chrome/ios_chrome.gyp @@ -44,7 +44,6 @@ ], 'dependencies': [ '../../base/base.gyp:base', - '../../base/base.gyp:base_prefs', '../../breakpad/breakpad.gyp:breakpad_client', '../../components/components.gyp:language_usage_metrics', '../../components/components.gyp:about_handler', @@ -118,6 +117,7 @@ '../../components/components.gyp:webp_transcode', '../../components/components_resources.gyp:components_resources', '../../components/components_strings.gyp:components_strings', + '../../components/prefs/prefs.gyp:prefs', '../../components/url_formatter/url_formatter.gyp:url_formatter', '../../google_apis/google_apis.gyp:google_apis', '../../net/net.gyp:net', diff --git a/ios/chrome/ios_chrome_tests.gyp b/ios/chrome/ios_chrome_tests.gyp index d78bfc1..284d874 100644 --- a/ios/chrome/ios_chrome_tests.gyp +++ b/ios/chrome/ios_chrome_tests.gyp @@ -12,7 +12,6 @@ 'type': '<(gtest_target_type)', 'dependencies': [ '../../base/base.gyp:base', - '../../base/base.gyp:base_prefs_test_support', '../../base/base.gyp:test_support_base', '../../components/components.gyp:bookmarks_test_support', '../../components/components.gyp:favicon_base', @@ -20,6 +19,7 @@ '../../components/components.gyp:metrics_test_support', '../../components/components.gyp:update_client', '../../components/components.gyp:version_info', + '../../components/prefs/prefs.gyp:prefs_test_support', '../../net/net.gyp:net_test_support', '../../skia/skia.gyp:skia', '../../testing/gmock.gyp:gmock', diff --git a/net/net.gyp b/net/net.gyp index 68a4cc0..2222d3e 100644 --- a/net/net.gyp +++ b/net/net.gyp @@ -142,7 +142,6 @@ 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', - '../base/base.gyp:base_prefs_test_support', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../crypto/crypto.gyp:crypto', '../crypto/crypto.gyp:crypto_test_support', diff --git a/net/net_common.gypi b/net/net_common.gypi index fe14edd..1b4f45a 100644 --- a/net/net_common.gypi +++ b/net/net_common.gypi @@ -8,7 +8,6 @@ 'variables': { 'enable_wexit_time_destructors': 1, }, 'dependencies': [ '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../crypto/crypto.gyp:crypto', '../sdch/sdch.gyp:sdch', diff --git a/rlz/rlz.gyp b/rlz/rlz.gyp index bd0fe23..e893eef 100644 --- a/rlz/rlz.gyp +++ b/rlz/rlz.gyp @@ -130,7 +130,6 @@ ':rlz_lib', ':test_support_rlz', '../base/base.gyp:base', - '../base/base.gyp:base_prefs', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/zlib/zlib.gyp:zlib', diff --git a/third_party/libaddressinput/libaddressinput.gyp b/third_party/libaddressinput/libaddressinput.gyp index b9bbbf9..4dc9efb 100644 --- a/third_party/libaddressinput/libaddressinput.gyp +++ b/third_party/libaddressinput/libaddressinput.gyp @@ -110,7 +110,7 @@ }, 'dependencies': [ '../../base/base.gyp:base', - '../../base/base.gyp:base_prefs', + '../../components/prefs/prefs.gyp:prefs', '../../net/net.gyp:net', '../icu/icu.gyp:icui18n', '../icu/icu.gyp:icuuc', @@ -143,8 +143,8 @@ 'src/cpp/src/', ], 'dependencies': [ - '../../base/base.gyp:base_prefs', '../../base/base.gyp:run_all_unittests', + '../../components/prefs/prefs.gyp:prefs', '../../net/net.gyp:net_test_support', '../../testing/gtest.gyp:gtest', 'libaddressinput', |