1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/prefs/pref_service.h"
10 #include "base/files/file_path.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/histogram.h"
14 #include "base/prefs/default_pref_store.h"
15 #include "base/prefs/pref_notifier_impl.h"
16 #include "base/prefs/pref_registry.h"
17 #include "base/prefs/pref_value_store.h"
18 #include "base/stl_util.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_util.h"
21 #include "base/value_conversions.h"
22 #include "build/build_config.h"
26 class ReadErrorHandler : public PersistentPrefStore::ReadErrorDelegate {
28 ReadErrorHandler(base::Callback<void(PersistentPrefStore::PrefReadError)> cb)
31 virtual void OnError(PersistentPrefStore::PrefReadError error) OVERRIDE {
36 base::Callback<void(PersistentPrefStore::PrefReadError)> callback_;
41 PrefService::PrefService(
42 PrefNotifierImpl* pref_notifier,
43 PrefValueStore* pref_value_store,
44 PersistentPrefStore* user_prefs,
45 PrefRegistry* pref_registry,
46 base::Callback<void(PersistentPrefStore::PrefReadError)>
49 : pref_notifier_(pref_notifier),
50 pref_value_store_(pref_value_store),
51 pref_registry_(pref_registry),
52 user_pref_store_(user_prefs),
53 read_error_callback_(read_error_callback) {
54 pref_notifier_->SetPrefService(this);
56 pref_registry_->SetRegistrationCallback(
57 base::Bind(&PrefService::AddRegisteredPreference,
58 base::Unretained(this)));
59 AddInitialPreferences();
61 InitFromStorage(async);
64 PrefService::~PrefService() {
65 DCHECK(CalledOnValidThread());
67 // Remove our callback, setting a NULL one.
68 pref_registry_->SetRegistrationCallback(PrefRegistry::RegistrationCallback());
70 // Reset pointers so accesses after destruction reliably crash.
71 pref_value_store_.reset();
72 pref_registry_ = NULL;
73 user_pref_store_ = NULL;
74 pref_notifier_.reset();
77 void PrefService::InitFromStorage(bool async) {
79 read_error_callback_.Run(user_pref_store_->ReadPrefs());
81 // Guarantee that initialization happens after this function returned.
82 base::MessageLoop::current()->PostTask(
84 base::Bind(&PersistentPrefStore::ReadPrefsAsync,
85 user_pref_store_.get(),
86 new ReadErrorHandler(read_error_callback_)));
90 void PrefService::CommitPendingWrite() {
91 DCHECK(CalledOnValidThread());
92 user_pref_store_->CommitPendingWrite();
95 bool PrefService::GetBoolean(const char* path) const {
96 DCHECK(CalledOnValidThread());
100 const base::Value* value = GetPreferenceValue(path);
102 NOTREACHED() << "Trying to read an unregistered pref: " << path;
105 bool rv = value->GetAsBoolean(&result);
110 int PrefService::GetInteger(const char* path) const {
111 DCHECK(CalledOnValidThread());
115 const base::Value* value = GetPreferenceValue(path);
117 NOTREACHED() << "Trying to read an unregistered pref: " << path;
120 bool rv = value->GetAsInteger(&result);
125 double PrefService::GetDouble(const char* path) const {
126 DCHECK(CalledOnValidThread());
130 const base::Value* value = GetPreferenceValue(path);
132 NOTREACHED() << "Trying to read an unregistered pref: " << path;
135 bool rv = value->GetAsDouble(&result);
140 std::string PrefService::GetString(const char* path) const {
141 DCHECK(CalledOnValidThread());
145 const base::Value* value = GetPreferenceValue(path);
147 NOTREACHED() << "Trying to read an unregistered pref: " << path;
150 bool rv = value->GetAsString(&result);
155 base::FilePath PrefService::GetFilePath(const char* path) const {
156 DCHECK(CalledOnValidThread());
158 base::FilePath result;
160 const base::Value* value = GetPreferenceValue(path);
162 NOTREACHED() << "Trying to read an unregistered pref: " << path;
163 return base::FilePath(result);
165 bool rv = base::GetValueAsFilePath(*value, &result);
170 bool PrefService::HasPrefPath(const char* path) const {
171 const Preference* pref = FindPreference(path);
172 return pref && !pref->IsDefaultValue();
175 scoped_ptr<base::DictionaryValue> PrefService::GetPreferenceValues() const {
176 DCHECK(CalledOnValidThread());
177 scoped_ptr<base::DictionaryValue> out(new base::DictionaryValue);
178 PrefRegistry::const_iterator i = pref_registry_->begin();
179 for (; i != pref_registry_->end(); ++i) {
180 const base::Value* value = GetPreferenceValue(i->first);
182 out->Set(i->first, value->DeepCopy());
187 scoped_ptr<base::DictionaryValue>
188 PrefService::GetPreferenceValuesWithoutPathExpansion() const {
189 DCHECK(CalledOnValidThread());
190 scoped_ptr<base::DictionaryValue> out(new base::DictionaryValue);
191 PrefRegistry::const_iterator i = pref_registry_->begin();
192 for (; i != pref_registry_->end(); ++i) {
193 const base::Value* value = GetPreferenceValue(i->first);
195 out->SetWithoutPathExpansion(i->first, value->DeepCopy());
200 const PrefService::Preference* PrefService::FindPreference(
201 const char* pref_name) const {
202 DCHECK(CalledOnValidThread());
203 PreferenceMap::iterator it = prefs_map_.find(pref_name);
204 if (it != prefs_map_.end())
205 return &(it->second);
206 const base::Value* default_value = NULL;
207 if (!pref_registry_->defaults()->GetValue(pref_name, &default_value))
209 it = prefs_map_.insert(
210 std::make_pair(pref_name, Preference(
211 this, pref_name, default_value->GetType()))).first;
212 return &(it->second);
215 bool PrefService::ReadOnly() const {
216 return user_pref_store_->ReadOnly();
219 PrefService::PrefInitializationStatus PrefService::GetInitializationStatus()
221 if (!user_pref_store_->IsInitializationComplete())
222 return INITIALIZATION_STATUS_WAITING;
224 switch (user_pref_store_->GetReadError()) {
225 case PersistentPrefStore::PREF_READ_ERROR_NONE:
226 return INITIALIZATION_STATUS_SUCCESS;
227 case PersistentPrefStore::PREF_READ_ERROR_NO_FILE:
228 return INITIALIZATION_STATUS_CREATED_NEW_PREF_STORE;
230 return INITIALIZATION_STATUS_ERROR;
234 bool PrefService::IsManagedPreference(const char* pref_name) const {
235 const Preference* pref = FindPreference(pref_name);
236 return pref && pref->IsManaged();
239 bool PrefService::IsUserModifiablePreference(const char* pref_name) const {
240 const Preference* pref = FindPreference(pref_name);
241 return pref && pref->IsUserModifiable();
244 const base::DictionaryValue* PrefService::GetDictionary(
245 const char* path) const {
246 DCHECK(CalledOnValidThread());
248 const base::Value* value = GetPreferenceValue(path);
250 NOTREACHED() << "Trying to read an unregistered pref: " << path;
253 if (value->GetType() != base::Value::TYPE_DICTIONARY) {
257 return static_cast<const base::DictionaryValue*>(value);
260 const base::Value* PrefService::GetUserPrefValue(const char* path) const {
261 DCHECK(CalledOnValidThread());
263 const Preference* pref = FindPreference(path);
265 NOTREACHED() << "Trying to get an unregistered pref: " << path;
269 // Look for an existing preference in the user store. If it doesn't
270 // exist, return NULL.
271 base::Value* value = NULL;
272 if (!user_pref_store_->GetMutableValue(path, &value))
275 if (!value->IsType(pref->GetType())) {
276 NOTREACHED() << "Pref value type doesn't match registered type.";
283 void PrefService::SetDefaultPrefValue(const char* path,
284 base::Value* value) {
285 DCHECK(CalledOnValidThread());
286 pref_registry_->SetDefaultPrefValue(path, value);
289 const base::Value* PrefService::GetDefaultPrefValue(const char* path) const {
290 DCHECK(CalledOnValidThread());
291 // Lookup the preference in the default store.
292 const base::Value* value = NULL;
293 if (!pref_registry_->defaults()->GetValue(path, &value)) {
294 NOTREACHED() << "Default value missing for pref: " << path;
300 const base::ListValue* PrefService::GetList(const char* path) const {
301 DCHECK(CalledOnValidThread());
303 const base::Value* value = GetPreferenceValue(path);
305 NOTREACHED() << "Trying to read an unregistered pref: " << path;
308 if (value->GetType() != base::Value::TYPE_LIST) {
312 return static_cast<const base::ListValue*>(value);
315 void PrefService::AddPrefObserver(const char* path, PrefObserver* obs) {
316 pref_notifier_->AddPrefObserver(path, obs);
319 void PrefService::RemovePrefObserver(const char* path, PrefObserver* obs) {
320 pref_notifier_->RemovePrefObserver(path, obs);
323 void PrefService::AddPrefInitObserver(base::Callback<void(bool)> obs) {
324 pref_notifier_->AddInitObserver(obs);
327 PrefRegistry* PrefService::DeprecatedGetPrefRegistry() {
328 return pref_registry_.get();
331 void PrefService::AddInitialPreferences() {
332 for (PrefRegistry::const_iterator it = pref_registry_->begin();
333 it != pref_registry_->end();
335 AddRegisteredPreference(it->first.c_str(), it->second);
339 // TODO(joi): Once MarkNeedsEmptyValue is gone, we can probably
340 // completely get rid of this method. There will be one difference in
341 // semantics; currently all registered preferences are stored right
342 // away in the prefs_map_, if we remove this they would be stored only
343 // opportunistically.
344 void PrefService::AddRegisteredPreference(const char* path,
345 base::Value* default_value) {
346 DCHECK(CalledOnValidThread());
348 // For ListValue and DictionaryValue with non empty default, empty value
349 // for |path| needs to be persisted in |user_pref_store_|. So that
350 // non empty default is not used when user sets an empty ListValue or
352 bool needs_empty_value = false;
353 base::Value::Type orig_type = default_value->GetType();
354 if (orig_type == base::Value::TYPE_LIST) {
355 const base::ListValue* list = NULL;
356 if (default_value->GetAsList(&list) && !list->empty())
357 needs_empty_value = true;
358 } else if (orig_type == base::Value::TYPE_DICTIONARY) {
359 const base::DictionaryValue* dict = NULL;
360 if (default_value->GetAsDictionary(&dict) && !dict->empty())
361 needs_empty_value = true;
363 if (needs_empty_value)
364 user_pref_store_->MarkNeedsEmptyValue(path);
367 void PrefService::ClearPref(const char* path) {
368 DCHECK(CalledOnValidThread());
370 const Preference* pref = FindPreference(path);
372 NOTREACHED() << "Trying to clear an unregistered pref: " << path;
375 user_pref_store_->RemoveValue(path);
378 void PrefService::Set(const char* path, const base::Value& value) {
379 SetUserPrefValue(path, value.DeepCopy());
382 void PrefService::SetBoolean(const char* path, bool value) {
383 SetUserPrefValue(path, base::Value::CreateBooleanValue(value));
386 void PrefService::SetInteger(const char* path, int value) {
387 SetUserPrefValue(path, base::Value::CreateIntegerValue(value));
390 void PrefService::SetDouble(const char* path, double value) {
391 SetUserPrefValue(path, base::Value::CreateDoubleValue(value));
394 void PrefService::SetString(const char* path, const std::string& value) {
395 SetUserPrefValue(path, base::Value::CreateStringValue(value));
398 void PrefService::SetFilePath(const char* path, const base::FilePath& value) {
399 SetUserPrefValue(path, base::CreateFilePathValue(value));
402 void PrefService::SetInt64(const char* path, int64 value) {
403 SetUserPrefValue(path,
404 base::Value::CreateStringValue(base::Int64ToString(value)));
407 int64 PrefService::GetInt64(const char* path) const {
408 DCHECK(CalledOnValidThread());
410 const base::Value* value = GetPreferenceValue(path);
412 NOTREACHED() << "Trying to read an unregistered pref: " << path;
415 std::string result("0");
416 bool rv = value->GetAsString(&result);
420 base::StringToInt64(result, &val);
424 void PrefService::SetUint64(const char* path, uint64 value) {
425 SetUserPrefValue(path,
426 base::Value::CreateStringValue(base::Uint64ToString(value)));
429 uint64 PrefService::GetUint64(const char* path) const {
430 DCHECK(CalledOnValidThread());
432 const base::Value* value = GetPreferenceValue(path);
434 NOTREACHED() << "Trying to read an unregistered pref: " << path;
437 std::string result("0");
438 bool rv = value->GetAsString(&result);
442 base::StringToUint64(result, &val);
446 base::Value* PrefService::GetMutableUserPref(const char* path,
447 base::Value::Type type) {
448 CHECK(type == base::Value::TYPE_DICTIONARY || type == base::Value::TYPE_LIST);
449 DCHECK(CalledOnValidThread());
451 const Preference* pref = FindPreference(path);
453 NOTREACHED() << "Trying to get an unregistered pref: " << path;
456 if (pref->GetType() != type) {
457 NOTREACHED() << "Wrong type for GetMutableValue: " << path;
461 // Look for an existing preference in the user store. If it doesn't
462 // exist or isn't the correct type, create a new user preference.
463 base::Value* value = NULL;
464 if (!user_pref_store_->GetMutableValue(path, &value) ||
465 !value->IsType(type)) {
466 if (type == base::Value::TYPE_DICTIONARY) {
467 value = new base::DictionaryValue;
468 } else if (type == base::Value::TYPE_LIST) {
469 value = new base::ListValue;
473 user_pref_store_->SetValueSilently(path, value);
478 void PrefService::ReportUserPrefChanged(const std::string& key) {
479 user_pref_store_->ReportValueChanged(key);
482 void PrefService::SetUserPrefValue(const char* path, base::Value* new_value) {
483 scoped_ptr<base::Value> owned_value(new_value);
484 DCHECK(CalledOnValidThread());
486 const Preference* pref = FindPreference(path);
488 NOTREACHED() << "Trying to write an unregistered pref: " << path;
491 if (pref->GetType() != new_value->GetType()) {
492 NOTREACHED() << "Trying to set pref " << path
493 << " of type " << pref->GetType()
494 << " to value of type " << new_value->GetType();
498 user_pref_store_->SetValue(path, owned_value.release());
501 void PrefService::UpdateCommandLinePrefStore(PrefStore* command_line_store) {
502 pref_value_store_->UpdateCommandLinePrefStore(command_line_store);
505 ///////////////////////////////////////////////////////////////////////////////
506 // PrefService::Preference
508 PrefService::Preference::Preference(const PrefService* service,
510 base::Value::Type type)
513 pref_service_(service) {
518 const std::string PrefService::Preference::name() const {
522 base::Value::Type PrefService::Preference::GetType() const {
526 const base::Value* PrefService::Preference::GetValue() const {
527 const base::Value* result= pref_service_->GetPreferenceValue(name_);
528 DCHECK(result) << "Must register pref before getting its value";
532 const base::Value* PrefService::Preference::GetRecommendedValue() const {
533 DCHECK(pref_service_->FindPreference(name_.c_str())) <<
534 "Must register pref before getting its value";
536 const base::Value* found_value = NULL;
537 if (pref_value_store()->GetRecommendedValue(name_, type_, &found_value)) {
538 DCHECK(found_value->IsType(type_));
542 // The pref has no recommended value.
546 bool PrefService::Preference::IsManaged() const {
547 return pref_value_store()->PrefValueInManagedStore(name_.c_str());
550 bool PrefService::Preference::IsRecommended() const {
551 return pref_value_store()->PrefValueFromRecommendedStore(name_.c_str());
554 bool PrefService::Preference::HasExtensionSetting() const {
555 return pref_value_store()->PrefValueInExtensionStore(name_.c_str());
558 bool PrefService::Preference::HasUserSetting() const {
559 return pref_value_store()->PrefValueInUserStore(name_.c_str());
562 bool PrefService::Preference::IsExtensionControlled() const {
563 return pref_value_store()->PrefValueFromExtensionStore(name_.c_str());
566 bool PrefService::Preference::IsUserControlled() const {
567 return pref_value_store()->PrefValueFromUserStore(name_.c_str());
570 bool PrefService::Preference::IsDefaultValue() const {
571 return pref_value_store()->PrefValueFromDefaultStore(name_.c_str());
574 bool PrefService::Preference::IsUserModifiable() const {
575 return pref_value_store()->PrefValueUserModifiable(name_.c_str());
578 bool PrefService::Preference::IsExtensionModifiable() const {
579 return pref_value_store()->PrefValueExtensionModifiable(name_.c_str());
582 const base::Value* PrefService::GetPreferenceValue(
583 const std::string& path) const {
584 DCHECK(CalledOnValidThread());
585 const base::Value* default_value = NULL;
586 if (pref_registry_->defaults()->GetValue(path, &default_value)) {
587 const base::Value* found_value = NULL;
588 base::Value::Type default_type = default_value->GetType();
589 if (pref_value_store_->GetValue(path, default_type, &found_value)) {
590 DCHECK(found_value->IsType(default_type));
593 // Every registered preference has at least a default value.
594 NOTREACHED() << "no valid value found for registered pref " << path;