pref_service.cc revision 868fa2fe829687343ffae624259930155e16dbd8
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.
4
5#include "base/prefs/pref_service.h"
6
7#include <algorithm>
8
9#include "base/bind.h"
10#include "base/files/file_path.h"
11#include "base/logging.h"
12#include "base/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"
23
24namespace {
25
26class ReadErrorHandler : public PersistentPrefStore::ReadErrorDelegate {
27 public:
28  ReadErrorHandler(base::Callback<void(PersistentPrefStore::PrefReadError)> cb)
29      : callback_(cb) {}
30
31  virtual void OnError(PersistentPrefStore::PrefReadError error) OVERRIDE {
32    callback_.Run(error);
33  }
34
35 private:
36  base::Callback<void(PersistentPrefStore::PrefReadError)> callback_;
37};
38
39}  // namespace
40
41PrefService::PrefService(
42    PrefNotifierImpl* pref_notifier,
43    PrefValueStore* pref_value_store,
44    PersistentPrefStore* user_prefs,
45    PrefRegistry* pref_registry,
46    base::Callback<void(PersistentPrefStore::PrefReadError)>
47        read_error_callback,
48    bool async)
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);
55
56  pref_registry_->SetRegistrationCallback(
57      base::Bind(&PrefService::AddRegisteredPreference,
58                 base::Unretained(this)));
59  AddInitialPreferences();
60
61  InitFromStorage(async);
62}
63
64PrefService::~PrefService() {
65  DCHECK(CalledOnValidThread());
66
67  // Remove our callback, setting a NULL one.
68  pref_registry_->SetRegistrationCallback(PrefRegistry::RegistrationCallback());
69
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();
75}
76
77void PrefService::InitFromStorage(bool async) {
78  if (!async) {
79    read_error_callback_.Run(user_pref_store_->ReadPrefs());
80  } else {
81    // Guarantee that initialization happens after this function returned.
82    base::MessageLoop::current()->PostTask(
83        FROM_HERE,
84        base::Bind(&PersistentPrefStore::ReadPrefsAsync,
85                   user_pref_store_.get(),
86                   new ReadErrorHandler(read_error_callback_)));
87  }
88}
89
90bool PrefService::ReloadPersistentPrefs() {
91  return user_pref_store_->ReadPrefs() ==
92             PersistentPrefStore::PREF_READ_ERROR_NONE;
93}
94
95void PrefService::CommitPendingWrite() {
96  DCHECK(CalledOnValidThread());
97  user_pref_store_->CommitPendingWrite();
98}
99
100bool PrefService::GetBoolean(const char* path) const {
101  DCHECK(CalledOnValidThread());
102
103  bool result = false;
104
105  const base::Value* value = GetPreferenceValue(path);
106  if (!value) {
107    NOTREACHED() << "Trying to read an unregistered pref: " << path;
108    return result;
109  }
110  bool rv = value->GetAsBoolean(&result);
111  DCHECK(rv);
112  return result;
113}
114
115int PrefService::GetInteger(const char* path) const {
116  DCHECK(CalledOnValidThread());
117
118  int result = 0;
119
120  const base::Value* value = GetPreferenceValue(path);
121  if (!value) {
122    NOTREACHED() << "Trying to read an unregistered pref: " << path;
123    return result;
124  }
125  bool rv = value->GetAsInteger(&result);
126  DCHECK(rv);
127  return result;
128}
129
130double PrefService::GetDouble(const char* path) const {
131  DCHECK(CalledOnValidThread());
132
133  double result = 0.0;
134
135  const base::Value* value = GetPreferenceValue(path);
136  if (!value) {
137    NOTREACHED() << "Trying to read an unregistered pref: " << path;
138    return result;
139  }
140  bool rv = value->GetAsDouble(&result);
141  DCHECK(rv);
142  return result;
143}
144
145std::string PrefService::GetString(const char* path) const {
146  DCHECK(CalledOnValidThread());
147
148  std::string result;
149
150  const base::Value* value = GetPreferenceValue(path);
151  if (!value) {
152    NOTREACHED() << "Trying to read an unregistered pref: " << path;
153    return result;
154  }
155  bool rv = value->GetAsString(&result);
156  DCHECK(rv);
157  return result;
158}
159
160base::FilePath PrefService::GetFilePath(const char* path) const {
161  DCHECK(CalledOnValidThread());
162
163  base::FilePath result;
164
165  const base::Value* value = GetPreferenceValue(path);
166  if (!value) {
167    NOTREACHED() << "Trying to read an unregistered pref: " << path;
168    return base::FilePath(result);
169  }
170  bool rv = base::GetValueAsFilePath(*value, &result);
171  DCHECK(rv);
172  return result;
173}
174
175bool PrefService::HasPrefPath(const char* path) const {
176  const Preference* pref = FindPreference(path);
177  return pref && !pref->IsDefaultValue();
178}
179
180DictionaryValue* PrefService::GetPreferenceValues() const {
181  DCHECK(CalledOnValidThread());
182  DictionaryValue* out = new DictionaryValue;
183  PrefRegistry::const_iterator i = pref_registry_->begin();
184  for (; i != pref_registry_->end(); ++i) {
185    const Value* value = GetPreferenceValue(i->first);
186    DCHECK(value);
187    out->Set(i->first, value->DeepCopy());
188  }
189  return out;
190}
191
192const PrefService::Preference* PrefService::FindPreference(
193    const char* pref_name) const {
194  DCHECK(CalledOnValidThread());
195  PreferenceMap::iterator it = prefs_map_.find(pref_name);
196  if (it != prefs_map_.end())
197    return &(it->second);
198  const base::Value* default_value = NULL;
199  if (!pref_registry_->defaults()->GetValue(pref_name, &default_value))
200    return NULL;
201  it = prefs_map_.insert(
202      std::make_pair(pref_name, Preference(
203          this, pref_name, default_value->GetType()))).first;
204  return &(it->second);
205}
206
207bool PrefService::ReadOnly() const {
208  return user_pref_store_->ReadOnly();
209}
210
211PrefService::PrefInitializationStatus PrefService::GetInitializationStatus()
212    const {
213  if (!user_pref_store_->IsInitializationComplete())
214    return INITIALIZATION_STATUS_WAITING;
215
216  switch (user_pref_store_->GetReadError()) {
217    case PersistentPrefStore::PREF_READ_ERROR_NONE:
218      return INITIALIZATION_STATUS_SUCCESS;
219    case PersistentPrefStore::PREF_READ_ERROR_NO_FILE:
220      return INITIALIZATION_STATUS_CREATED_NEW_PREF_STORE;
221    default:
222      return INITIALIZATION_STATUS_ERROR;
223  }
224}
225
226bool PrefService::IsManagedPreference(const char* pref_name) const {
227  const Preference* pref = FindPreference(pref_name);
228  return pref && pref->IsManaged();
229}
230
231bool PrefService::IsUserModifiablePreference(const char* pref_name) const {
232  const Preference* pref = FindPreference(pref_name);
233  return pref && pref->IsUserModifiable();
234}
235
236const DictionaryValue* PrefService::GetDictionary(const char* path) const {
237  DCHECK(CalledOnValidThread());
238
239  const Value* value = GetPreferenceValue(path);
240  if (!value) {
241    NOTREACHED() << "Trying to read an unregistered pref: " << path;
242    return NULL;
243  }
244  if (value->GetType() != Value::TYPE_DICTIONARY) {
245    NOTREACHED();
246    return NULL;
247  }
248  return static_cast<const DictionaryValue*>(value);
249}
250
251const base::Value* PrefService::GetUserPrefValue(const char* path) const {
252  DCHECK(CalledOnValidThread());
253
254  const Preference* pref = FindPreference(path);
255  if (!pref) {
256    NOTREACHED() << "Trying to get an unregistered pref: " << path;
257    return NULL;
258  }
259
260  // Look for an existing preference in the user store. If it doesn't
261  // exist, return NULL.
262  base::Value* value = NULL;
263  if (!user_pref_store_->GetMutableValue(path, &value))
264    return NULL;
265
266  if (!value->IsType(pref->GetType())) {
267    NOTREACHED() << "Pref value type doesn't match registered type.";
268    return NULL;
269  }
270
271  return value;
272}
273
274void PrefService::SetDefaultPrefValue(const char* path,
275                                      base::Value* value) {
276  DCHECK(CalledOnValidThread());
277  pref_registry_->SetDefaultPrefValue(path, value);
278}
279
280const base::Value* PrefService::GetDefaultPrefValue(const char* path) const {
281  DCHECK(CalledOnValidThread());
282  // Lookup the preference in the default store.
283  const base::Value* value = NULL;
284  if (!pref_registry_->defaults()->GetValue(path, &value)) {
285    NOTREACHED() << "Default value missing for pref: " << path;
286    return NULL;
287  }
288  return value;
289}
290
291const ListValue* PrefService::GetList(const char* path) const {
292  DCHECK(CalledOnValidThread());
293
294  const Value* value = GetPreferenceValue(path);
295  if (!value) {
296    NOTREACHED() << "Trying to read an unregistered pref: " << path;
297    return NULL;
298  }
299  if (value->GetType() != Value::TYPE_LIST) {
300    NOTREACHED();
301    return NULL;
302  }
303  return static_cast<const ListValue*>(value);
304}
305
306void PrefService::AddPrefObserver(const char* path, PrefObserver* obs) {
307  pref_notifier_->AddPrefObserver(path, obs);
308}
309
310void PrefService::RemovePrefObserver(const char* path, PrefObserver* obs) {
311  pref_notifier_->RemovePrefObserver(path, obs);
312}
313
314void PrefService::AddPrefInitObserver(base::Callback<void(bool)> obs) {
315  pref_notifier_->AddInitObserver(obs);
316}
317
318PrefRegistry* PrefService::DeprecatedGetPrefRegistry() {
319  return pref_registry_.get();
320}
321
322void PrefService::AddInitialPreferences() {
323  for (PrefRegistry::const_iterator it = pref_registry_->begin();
324       it != pref_registry_->end();
325       ++it) {
326    AddRegisteredPreference(it->first.c_str(), it->second);
327  }
328}
329
330// TODO(joi): Once MarkNeedsEmptyValue is gone, we can probably
331// completely get rid of this method. There will be one difference in
332// semantics; currently all registered preferences are stored right
333// away in the prefs_map_, if we remove this they would be stored only
334// opportunistically.
335void PrefService::AddRegisteredPreference(const char* path,
336                                          Value* default_value) {
337  DCHECK(CalledOnValidThread());
338
339  // For ListValue and DictionaryValue with non empty default, empty value
340  // for |path| needs to be persisted in |user_pref_store_|. So that
341  // non empty default is not used when user sets an empty ListValue or
342  // DictionaryValue.
343  bool needs_empty_value = false;
344  base::Value::Type orig_type = default_value->GetType();
345  if (orig_type == base::Value::TYPE_LIST) {
346    const base::ListValue* list = NULL;
347    if (default_value->GetAsList(&list) && !list->empty())
348      needs_empty_value = true;
349  } else if (orig_type == base::Value::TYPE_DICTIONARY) {
350    const base::DictionaryValue* dict = NULL;
351    if (default_value->GetAsDictionary(&dict) && !dict->empty())
352      needs_empty_value = true;
353  }
354  if (needs_empty_value)
355    user_pref_store_->MarkNeedsEmptyValue(path);
356}
357
358void PrefService::ClearPref(const char* path) {
359  DCHECK(CalledOnValidThread());
360
361  const Preference* pref = FindPreference(path);
362  if (!pref) {
363    NOTREACHED() << "Trying to clear an unregistered pref: " << path;
364    return;
365  }
366  user_pref_store_->RemoveValue(path);
367}
368
369void PrefService::Set(const char* path, const Value& value) {
370  SetUserPrefValue(path, value.DeepCopy());
371}
372
373void PrefService::SetBoolean(const char* path, bool value) {
374  SetUserPrefValue(path, Value::CreateBooleanValue(value));
375}
376
377void PrefService::SetInteger(const char* path, int value) {
378  SetUserPrefValue(path, Value::CreateIntegerValue(value));
379}
380
381void PrefService::SetDouble(const char* path, double value) {
382  SetUserPrefValue(path, Value::CreateDoubleValue(value));
383}
384
385void PrefService::SetString(const char* path, const std::string& value) {
386  SetUserPrefValue(path, Value::CreateStringValue(value));
387}
388
389void PrefService::SetFilePath(const char* path, const base::FilePath& value) {
390  SetUserPrefValue(path, base::CreateFilePathValue(value));
391}
392
393void PrefService::SetInt64(const char* path, int64 value) {
394  SetUserPrefValue(path, Value::CreateStringValue(base::Int64ToString(value)));
395}
396
397int64 PrefService::GetInt64(const char* path) const {
398  DCHECK(CalledOnValidThread());
399
400  const Value* value = GetPreferenceValue(path);
401  if (!value) {
402    NOTREACHED() << "Trying to read an unregistered pref: " << path;
403    return 0;
404  }
405  std::string result("0");
406  bool rv = value->GetAsString(&result);
407  DCHECK(rv);
408
409  int64 val;
410  base::StringToInt64(result, &val);
411  return val;
412}
413
414void PrefService::SetUint64(const char* path, uint64 value) {
415  SetUserPrefValue(path, Value::CreateStringValue(base::Uint64ToString(value)));
416}
417
418uint64 PrefService::GetUint64(const char* path) const {
419  DCHECK(CalledOnValidThread());
420
421  const Value* value = GetPreferenceValue(path);
422  if (!value) {
423    NOTREACHED() << "Trying to read an unregistered pref: " << path;
424    return 0;
425  }
426  std::string result("0");
427  bool rv = value->GetAsString(&result);
428  DCHECK(rv);
429
430  uint64 val;
431  base::StringToUint64(result, &val);
432  return val;
433}
434
435Value* PrefService::GetMutableUserPref(const char* path,
436                                       base::Value::Type type) {
437  CHECK(type == Value::TYPE_DICTIONARY || type == Value::TYPE_LIST);
438  DCHECK(CalledOnValidThread());
439
440  const Preference* pref = FindPreference(path);
441  if (!pref) {
442    NOTREACHED() << "Trying to get an unregistered pref: " << path;
443    return NULL;
444  }
445  if (pref->GetType() != type) {
446    NOTREACHED() << "Wrong type for GetMutableValue: " << path;
447    return NULL;
448  }
449
450  // Look for an existing preference in the user store. If it doesn't
451  // exist or isn't the correct type, create a new user preference.
452  Value* value = NULL;
453  if (!user_pref_store_->GetMutableValue(path, &value) ||
454      !value->IsType(type)) {
455    if (type == Value::TYPE_DICTIONARY) {
456      value = new DictionaryValue;
457    } else if (type == Value::TYPE_LIST) {
458      value = new ListValue;
459    } else {
460      NOTREACHED();
461    }
462    user_pref_store_->SetValueSilently(path, value);
463  }
464  return value;
465}
466
467void PrefService::ReportUserPrefChanged(const std::string& key) {
468  user_pref_store_->ReportValueChanged(key);
469}
470
471void PrefService::SetUserPrefValue(const char* path, Value* new_value) {
472  scoped_ptr<Value> owned_value(new_value);
473  DCHECK(CalledOnValidThread());
474
475  const Preference* pref = FindPreference(path);
476  if (!pref) {
477    NOTREACHED() << "Trying to write an unregistered pref: " << path;
478    return;
479  }
480  if (pref->GetType() != new_value->GetType()) {
481    NOTREACHED() << "Trying to set pref " << path
482                 << " of type " << pref->GetType()
483                 << " to value of type " << new_value->GetType();
484    return;
485  }
486
487  user_pref_store_->SetValue(path, owned_value.release());
488}
489
490void PrefService::UpdateCommandLinePrefStore(PrefStore* command_line_store) {
491  pref_value_store_->UpdateCommandLinePrefStore(command_line_store);
492}
493
494///////////////////////////////////////////////////////////////////////////////
495// PrefService::Preference
496
497PrefService::Preference::Preference(const PrefService* service,
498                                    const char* name,
499                                    base::Value::Type type)
500      : name_(name),
501        type_(type),
502        pref_service_(service) {
503  DCHECK(name);
504  DCHECK(service);
505}
506
507const std::string PrefService::Preference::name() const {
508  return name_;
509}
510
511base::Value::Type PrefService::Preference::GetType() const {
512  return type_;
513}
514
515const Value* PrefService::Preference::GetValue() const {
516  const Value* result= pref_service_->GetPreferenceValue(name_);
517  DCHECK(result) << "Must register pref before getting its value";
518  return result;
519}
520
521const Value* PrefService::Preference::GetRecommendedValue() const {
522  DCHECK(pref_service_->FindPreference(name_.c_str())) <<
523      "Must register pref before getting its value";
524
525  const Value* found_value = NULL;
526  if (pref_value_store()->GetRecommendedValue(name_, type_, &found_value)) {
527    DCHECK(found_value->IsType(type_));
528    return found_value;
529  }
530
531  // The pref has no recommended value.
532  return NULL;
533}
534
535bool PrefService::Preference::IsManaged() const {
536  return pref_value_store()->PrefValueInManagedStore(name_.c_str());
537}
538
539bool PrefService::Preference::IsRecommended() const {
540  return pref_value_store()->PrefValueFromRecommendedStore(name_.c_str());
541}
542
543bool PrefService::Preference::HasExtensionSetting() const {
544  return pref_value_store()->PrefValueInExtensionStore(name_.c_str());
545}
546
547bool PrefService::Preference::HasUserSetting() const {
548  return pref_value_store()->PrefValueInUserStore(name_.c_str());
549}
550
551bool PrefService::Preference::IsExtensionControlled() const {
552  return pref_value_store()->PrefValueFromExtensionStore(name_.c_str());
553}
554
555bool PrefService::Preference::IsUserControlled() const {
556  return pref_value_store()->PrefValueFromUserStore(name_.c_str());
557}
558
559bool PrefService::Preference::IsDefaultValue() const {
560  return pref_value_store()->PrefValueFromDefaultStore(name_.c_str());
561}
562
563bool PrefService::Preference::IsUserModifiable() const {
564  return pref_value_store()->PrefValueUserModifiable(name_.c_str());
565}
566
567bool PrefService::Preference::IsExtensionModifiable() const {
568  return pref_value_store()->PrefValueExtensionModifiable(name_.c_str());
569}
570
571const base::Value* PrefService::GetPreferenceValue(
572    const std::string& path) const {
573  DCHECK(CalledOnValidThread());
574  const Value* default_value = NULL;
575  if (pref_registry_->defaults()->GetValue(path, &default_value)) {
576    const Value* found_value = NULL;
577    base::Value::Type default_type = default_value->GetType();
578    if (pref_value_store_->GetValue(path, default_type, &found_value)) {
579      DCHECK(found_value->IsType(default_type));
580      return found_value;
581    } else {
582      // Every registered preference has at least a default value.
583      NOTREACHED() << "no valid value found for registered pref " << path;
584    }
585  }
586
587  return NULL;
588}
589