Add ICU message format support
[chromium-blink-merge.git] / base / prefs / pref_service.cc
blobc53b8966b347c02134967d6c8d932eb024d1decb
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"
7 #include <algorithm>
9 #include "base/bind.h"
10 #include "base/files/file_path.h"
11 #include "base/location.h"
12 #include "base/logging.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/single_thread_task_runner.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/thread_task_runner_handle.h"
23 #include "base/value_conversions.h"
24 #include "build/build_config.h"
26 namespace {
28 class ReadErrorHandler : public PersistentPrefStore::ReadErrorDelegate {
29 public:
30 ReadErrorHandler(base::Callback<void(PersistentPrefStore::PrefReadError)> cb)
31 : callback_(cb) {}
33 void OnError(PersistentPrefStore::PrefReadError error) override {
34 callback_.Run(error);
37 private:
38 base::Callback<void(PersistentPrefStore::PrefReadError)> callback_;
41 // Returns the WriteablePrefStore::PrefWriteFlags for the pref with the given
42 // |path|.
43 uint32 GetWriteFlags(const PrefService::Preference* pref) {
44 uint32 write_flags = WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS;
46 if (!pref)
47 return write_flags;
49 if (pref->registration_flags() & PrefRegistry::LOSSY_PREF)
50 write_flags |= WriteablePrefStore::LOSSY_PREF_WRITE_FLAG;
51 return write_flags;
54 } // namespace
56 PrefService::PrefService(
57 PrefNotifierImpl* pref_notifier,
58 PrefValueStore* pref_value_store,
59 PersistentPrefStore* user_prefs,
60 PrefRegistry* pref_registry,
61 base::Callback<void(PersistentPrefStore::PrefReadError)>
62 read_error_callback,
63 bool async)
64 : pref_notifier_(pref_notifier),
65 pref_value_store_(pref_value_store),
66 pref_registry_(pref_registry),
67 user_pref_store_(user_prefs),
68 read_error_callback_(read_error_callback) {
69 pref_notifier_->SetPrefService(this);
71 // TODO(battre): This is a check for crbug.com/435208 to make sure that
72 // access violations are caused by a use-after-free bug and not by an
73 // initialization bug.
74 CHECK(pref_registry_);
75 CHECK(pref_value_store_);
77 InitFromStorage(async);
80 PrefService::~PrefService() {
81 DCHECK(CalledOnValidThread());
83 // Reset pointers so accesses after destruction reliably crash.
84 pref_value_store_.reset();
85 pref_registry_ = NULL;
86 user_pref_store_ = NULL;
87 pref_notifier_.reset();
90 void PrefService::InitFromStorage(bool async) {
91 if (user_pref_store_->IsInitializationComplete()) {
92 read_error_callback_.Run(user_pref_store_->GetReadError());
93 } else if (!async) {
94 read_error_callback_.Run(user_pref_store_->ReadPrefs());
95 } else {
96 // Guarantee that initialization happens after this function returned.
97 base::ThreadTaskRunnerHandle::Get()->PostTask(
98 FROM_HERE,
99 base::Bind(&PersistentPrefStore::ReadPrefsAsync, user_pref_store_.get(),
100 new ReadErrorHandler(read_error_callback_)));
104 void PrefService::CommitPendingWrite() {
105 DCHECK(CalledOnValidThread());
106 user_pref_store_->CommitPendingWrite();
109 void PrefService::SchedulePendingLossyWrites() {
110 DCHECK(CalledOnValidThread());
111 user_pref_store_->SchedulePendingLossyWrites();
114 bool PrefService::GetBoolean(const std::string& path) const {
115 DCHECK(CalledOnValidThread());
117 bool result = false;
119 const base::Value* value = GetPreferenceValue(path);
120 if (!value) {
121 NOTREACHED() << "Trying to read an unregistered pref: " << path;
122 return result;
124 bool rv = value->GetAsBoolean(&result);
125 DCHECK(rv);
126 return result;
129 int PrefService::GetInteger(const std::string& path) const {
130 DCHECK(CalledOnValidThread());
132 int result = 0;
134 const base::Value* value = GetPreferenceValue(path);
135 if (!value) {
136 NOTREACHED() << "Trying to read an unregistered pref: " << path;
137 return result;
139 bool rv = value->GetAsInteger(&result);
140 DCHECK(rv);
141 return result;
144 double PrefService::GetDouble(const std::string& path) const {
145 DCHECK(CalledOnValidThread());
147 double result = 0.0;
149 const base::Value* value = GetPreferenceValue(path);
150 if (!value) {
151 NOTREACHED() << "Trying to read an unregistered pref: " << path;
152 return result;
154 bool rv = value->GetAsDouble(&result);
155 DCHECK(rv);
156 return result;
159 std::string PrefService::GetString(const std::string& path) const {
160 DCHECK(CalledOnValidThread());
162 std::string result;
164 const base::Value* value = GetPreferenceValue(path);
165 if (!value) {
166 NOTREACHED() << "Trying to read an unregistered pref: " << path;
167 return result;
169 bool rv = value->GetAsString(&result);
170 DCHECK(rv);
171 return result;
174 base::FilePath PrefService::GetFilePath(const std::string& path) const {
175 DCHECK(CalledOnValidThread());
177 base::FilePath result;
179 const base::Value* value = GetPreferenceValue(path);
180 if (!value) {
181 NOTREACHED() << "Trying to read an unregistered pref: " << path;
182 return base::FilePath(result);
184 bool rv = base::GetValueAsFilePath(*value, &result);
185 DCHECK(rv);
186 return result;
189 bool PrefService::HasPrefPath(const std::string& path) const {
190 const Preference* pref = FindPreference(path);
191 return pref && !pref->IsDefaultValue();
194 scoped_ptr<base::DictionaryValue> PrefService::GetPreferenceValues() const {
195 DCHECK(CalledOnValidThread());
196 scoped_ptr<base::DictionaryValue> out(new base::DictionaryValue);
197 for (const auto& it : *pref_registry_) {
198 out->Set(it.first, GetPreferenceValue(it.first)->CreateDeepCopy());
200 return out.Pass();
203 scoped_ptr<base::DictionaryValue> PrefService::GetPreferenceValuesOmitDefaults()
204 const {
205 DCHECK(CalledOnValidThread());
206 scoped_ptr<base::DictionaryValue> out(new base::DictionaryValue);
207 for (const auto& it : *pref_registry_) {
208 const Preference* pref = FindPreference(it.first);
209 if (pref->IsDefaultValue())
210 continue;
211 out->Set(it.first, pref->GetValue()->CreateDeepCopy());
213 return out.Pass();
216 scoped_ptr<base::DictionaryValue>
217 PrefService::GetPreferenceValuesWithoutPathExpansion() const {
218 DCHECK(CalledOnValidThread());
219 scoped_ptr<base::DictionaryValue> out(new base::DictionaryValue);
220 for (const auto& it : *pref_registry_) {
221 const base::Value* value = GetPreferenceValue(it.first);
222 DCHECK(value);
223 out->SetWithoutPathExpansion(it.first, value->CreateDeepCopy());
225 return out.Pass();
228 const PrefService::Preference* PrefService::FindPreference(
229 const std::string& pref_name) const {
230 DCHECK(CalledOnValidThread());
231 PreferenceMap::iterator it = prefs_map_.find(pref_name);
232 if (it != prefs_map_.end())
233 return &(it->second);
234 const base::Value* default_value = NULL;
235 if (!pref_registry_->defaults()->GetValue(pref_name, &default_value))
236 return NULL;
237 it = prefs_map_.insert(
238 std::make_pair(pref_name, Preference(
239 this, pref_name, default_value->GetType()))).first;
240 return &(it->second);
243 bool PrefService::ReadOnly() const {
244 return user_pref_store_->ReadOnly();
247 PrefService::PrefInitializationStatus PrefService::GetInitializationStatus()
248 const {
249 if (!user_pref_store_->IsInitializationComplete())
250 return INITIALIZATION_STATUS_WAITING;
252 switch (user_pref_store_->GetReadError()) {
253 case PersistentPrefStore::PREF_READ_ERROR_NONE:
254 return INITIALIZATION_STATUS_SUCCESS;
255 case PersistentPrefStore::PREF_READ_ERROR_NO_FILE:
256 return INITIALIZATION_STATUS_CREATED_NEW_PREF_STORE;
257 default:
258 return INITIALIZATION_STATUS_ERROR;
262 bool PrefService::IsManagedPreference(const std::string& pref_name) const {
263 const Preference* pref = FindPreference(pref_name);
264 return pref && pref->IsManaged();
267 bool PrefService::IsPreferenceManagedByCustodian(
268 const std::string& pref_name) const {
269 const Preference* pref = FindPreference(pref_name);
270 return pref && pref->IsManagedByCustodian();
273 bool PrefService::IsUserModifiablePreference(
274 const std::string& pref_name) const {
275 const Preference* pref = FindPreference(pref_name);
276 return pref && pref->IsUserModifiable();
279 const base::DictionaryValue* PrefService::GetDictionary(
280 const std::string& path) const {
281 DCHECK(CalledOnValidThread());
283 const base::Value* value = GetPreferenceValue(path);
284 if (!value) {
285 NOTREACHED() << "Trying to read an unregistered pref: " << path;
286 return NULL;
288 if (value->GetType() != base::Value::TYPE_DICTIONARY) {
289 NOTREACHED();
290 return NULL;
292 return static_cast<const base::DictionaryValue*>(value);
295 const base::Value* PrefService::GetUserPrefValue(
296 const std::string& path) const {
297 DCHECK(CalledOnValidThread());
299 const Preference* pref = FindPreference(path);
300 if (!pref) {
301 NOTREACHED() << "Trying to get an unregistered pref: " << path;
302 return NULL;
305 // Look for an existing preference in the user store. If it doesn't
306 // exist, return NULL.
307 base::Value* value = NULL;
308 if (!user_pref_store_->GetMutableValue(path, &value))
309 return NULL;
311 if (!value->IsType(pref->GetType())) {
312 NOTREACHED() << "Pref value type doesn't match registered type.";
313 return NULL;
316 return value;
319 void PrefService::SetDefaultPrefValue(const std::string& path,
320 base::Value* value) {
321 DCHECK(CalledOnValidThread());
322 pref_registry_->SetDefaultPrefValue(path, value);
325 const base::Value* PrefService::GetDefaultPrefValue(
326 const std::string& path) const {
327 DCHECK(CalledOnValidThread());
328 // Lookup the preference in the default store.
329 const base::Value* value = NULL;
330 if (!pref_registry_->defaults()->GetValue(path, &value)) {
331 NOTREACHED() << "Default value missing for pref: " << path;
332 return NULL;
334 return value;
337 const base::ListValue* PrefService::GetList(const std::string& path) const {
338 DCHECK(CalledOnValidThread());
340 const base::Value* value = GetPreferenceValue(path);
341 if (!value) {
342 NOTREACHED() << "Trying to read an unregistered pref: " << path;
343 return NULL;
345 if (value->GetType() != base::Value::TYPE_LIST) {
346 NOTREACHED();
347 return NULL;
349 return static_cast<const base::ListValue*>(value);
352 void PrefService::AddPrefObserver(const std::string& path, PrefObserver* obs) {
353 pref_notifier_->AddPrefObserver(path, obs);
356 void PrefService::RemovePrefObserver(const std::string& path,
357 PrefObserver* obs) {
358 pref_notifier_->RemovePrefObserver(path, obs);
361 void PrefService::AddPrefInitObserver(base::Callback<void(bool)> obs) {
362 pref_notifier_->AddInitObserver(obs);
365 PrefRegistry* PrefService::DeprecatedGetPrefRegistry() {
366 return pref_registry_.get();
369 void PrefService::ClearPref(const std::string& path) {
370 DCHECK(CalledOnValidThread());
372 const Preference* pref = FindPreference(path);
373 if (!pref) {
374 NOTREACHED() << "Trying to clear an unregistered pref: " << path;
375 return;
377 user_pref_store_->RemoveValue(path, GetWriteFlags(pref));
380 void PrefService::Set(const std::string& path, const base::Value& value) {
381 SetUserPrefValue(path, value.DeepCopy());
384 void PrefService::SetBoolean(const std::string& path, bool value) {
385 SetUserPrefValue(path, new base::FundamentalValue(value));
388 void PrefService::SetInteger(const std::string& path, int value) {
389 SetUserPrefValue(path, new base::FundamentalValue(value));
392 void PrefService::SetDouble(const std::string& path, double value) {
393 SetUserPrefValue(path, new base::FundamentalValue(value));
396 void PrefService::SetString(const std::string& path, const std::string& value) {
397 SetUserPrefValue(path, new base::StringValue(value));
400 void PrefService::SetFilePath(const std::string& path,
401 const base::FilePath& value) {
402 SetUserPrefValue(path, base::CreateFilePathValue(value));
405 void PrefService::SetInt64(const std::string& path, int64 value) {
406 SetUserPrefValue(path, new base::StringValue(base::Int64ToString(value)));
409 int64 PrefService::GetInt64(const std::string& path) const {
410 DCHECK(CalledOnValidThread());
412 const base::Value* value = GetPreferenceValue(path);
413 if (!value) {
414 NOTREACHED() << "Trying to read an unregistered pref: " << path;
415 return 0;
417 std::string result("0");
418 bool rv = value->GetAsString(&result);
419 DCHECK(rv);
421 int64 val;
422 base::StringToInt64(result, &val);
423 return val;
426 void PrefService::SetUint64(const std::string& path, uint64 value) {
427 SetUserPrefValue(path, new base::StringValue(base::Uint64ToString(value)));
430 uint64 PrefService::GetUint64(const std::string& path) const {
431 DCHECK(CalledOnValidThread());
433 const base::Value* value = GetPreferenceValue(path);
434 if (!value) {
435 NOTREACHED() << "Trying to read an unregistered pref: " << path;
436 return 0;
438 std::string result("0");
439 bool rv = value->GetAsString(&result);
440 DCHECK(rv);
442 uint64 val;
443 base::StringToUint64(result, &val);
444 return val;
447 base::Value* PrefService::GetMutableUserPref(const std::string& path,
448 base::Value::Type type) {
449 CHECK(type == base::Value::TYPE_DICTIONARY || type == base::Value::TYPE_LIST);
450 DCHECK(CalledOnValidThread());
452 const Preference* pref = FindPreference(path);
453 if (!pref) {
454 NOTREACHED() << "Trying to get an unregistered pref: " << path;
455 return NULL;
457 if (pref->GetType() != type) {
458 NOTREACHED() << "Wrong type for GetMutableValue: " << path;
459 return NULL;
462 // Look for an existing preference in the user store. If it doesn't
463 // exist or isn't the correct type, create a new user preference.
464 base::Value* value = NULL;
465 if (!user_pref_store_->GetMutableValue(path, &value) ||
466 !value->IsType(type)) {
467 if (type == base::Value::TYPE_DICTIONARY) {
468 value = new base::DictionaryValue;
469 } else if (type == base::Value::TYPE_LIST) {
470 value = new base::ListValue;
471 } else {
472 NOTREACHED();
474 user_pref_store_->SetValueSilently(path, make_scoped_ptr(value),
475 GetWriteFlags(pref));
477 return value;
480 void PrefService::ReportUserPrefChanged(const std::string& key) {
481 DCHECK(CalledOnValidThread());
482 user_pref_store_->ReportValueChanged(key, GetWriteFlags(FindPreference(key)));
485 void PrefService::SetUserPrefValue(const std::string& path,
486 base::Value* new_value) {
487 scoped_ptr<base::Value> owned_value(new_value);
488 DCHECK(CalledOnValidThread());
490 const Preference* pref = FindPreference(path);
491 if (!pref) {
492 NOTREACHED() << "Trying to write an unregistered pref: " << path;
493 return;
495 if (pref->GetType() != new_value->GetType()) {
496 NOTREACHED() << "Trying to set pref " << path
497 << " of type " << pref->GetType()
498 << " to value of type " << new_value->GetType();
499 return;
502 user_pref_store_->SetValue(path, owned_value.Pass(), GetWriteFlags(pref));
505 void PrefService::UpdateCommandLinePrefStore(PrefStore* command_line_store) {
506 pref_value_store_->UpdateCommandLinePrefStore(command_line_store);
509 ///////////////////////////////////////////////////////////////////////////////
510 // PrefService::Preference
512 PrefService::Preference::Preference(const PrefService* service,
513 const std::string& name,
514 base::Value::Type type)
515 : name_(name), type_(type), pref_service_(service) {
516 DCHECK(service);
517 // Cache the registration flags at creation time to avoid multiple map lookups
518 // later.
519 registration_flags_ = service->pref_registry_->GetRegistrationFlags(name_);
522 const std::string PrefService::Preference::name() const {
523 return name_;
526 base::Value::Type PrefService::Preference::GetType() const {
527 return type_;
530 const base::Value* PrefService::Preference::GetValue() const {
531 const base::Value* result= pref_service_->GetPreferenceValue(name_);
532 DCHECK(result) << "Must register pref before getting its value";
533 return result;
536 const base::Value* PrefService::Preference::GetRecommendedValue() const {
537 DCHECK(pref_service_->FindPreference(name_))
538 << "Must register pref before getting its value";
540 const base::Value* found_value = NULL;
541 if (pref_value_store()->GetRecommendedValue(name_, type_, &found_value)) {
542 DCHECK(found_value->IsType(type_));
543 return found_value;
546 // The pref has no recommended value.
547 return NULL;
550 bool PrefService::Preference::IsManaged() const {
551 return pref_value_store()->PrefValueInManagedStore(name_);
554 bool PrefService::Preference::IsManagedByCustodian() const {
555 return pref_value_store()->PrefValueInSupervisedStore(name_.c_str());
558 bool PrefService::Preference::IsRecommended() const {
559 return pref_value_store()->PrefValueFromRecommendedStore(name_);
562 bool PrefService::Preference::HasExtensionSetting() const {
563 return pref_value_store()->PrefValueInExtensionStore(name_);
566 bool PrefService::Preference::HasUserSetting() const {
567 return pref_value_store()->PrefValueInUserStore(name_);
570 bool PrefService::Preference::IsExtensionControlled() const {
571 return pref_value_store()->PrefValueFromExtensionStore(name_);
574 bool PrefService::Preference::IsUserControlled() const {
575 return pref_value_store()->PrefValueFromUserStore(name_);
578 bool PrefService::Preference::IsDefaultValue() const {
579 return pref_value_store()->PrefValueFromDefaultStore(name_);
582 bool PrefService::Preference::IsUserModifiable() const {
583 return pref_value_store()->PrefValueUserModifiable(name_);
586 bool PrefService::Preference::IsExtensionModifiable() const {
587 return pref_value_store()->PrefValueExtensionModifiable(name_);
590 const base::Value* PrefService::GetPreferenceValue(
591 const std::string& path) const {
592 DCHECK(CalledOnValidThread());
594 // TODO(battre): This is a check for crbug.com/435208. After analyzing some
595 // crash dumps it looks like the PrefService is accessed even though it has
596 // been cleared already.
597 CHECK(pref_registry_);
598 CHECK(pref_registry_->defaults());
599 CHECK(pref_value_store_);
601 const base::Value* default_value = NULL;
602 if (pref_registry_->defaults()->GetValue(path, &default_value)) {
603 const base::Value* found_value = NULL;
604 base::Value::Type default_type = default_value->GetType();
605 if (pref_value_store_->GetValue(path, default_type, &found_value)) {
606 DCHECK(found_value->IsType(default_type));
607 return found_value;
608 } else {
609 // Every registered preference has at least a default value.
610 NOTREACHED() << "no valid value found for registered pref " << path;
614 return NULL;