Home | History | Annotate | Download | only in prefs
      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/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 
     24 namespace {
     25 
     26 class 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 
     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)>
     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 
     64 PrefService::~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 
     77 void 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 
     90 bool PrefService::ReloadPersistentPrefs() {
     91   return user_pref_store_->ReadPrefs() ==
     92              PersistentPrefStore::PREF_READ_ERROR_NONE;
     93 }
     94 
     95 void PrefService::CommitPendingWrite() {
     96   DCHECK(CalledOnValidThread());
     97   user_pref_store_->CommitPendingWrite();
     98 }
     99 
    100 bool 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 
    115 int 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 
    130 double 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 
    145 std::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 
    160 base::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 
    175 bool PrefService::HasPrefPath(const char* path) const {
    176   const Preference* pref = FindPreference(path);
    177   return pref && !pref->IsDefaultValue();
    178 }
    179 
    180 base::DictionaryValue* PrefService::GetPreferenceValues() const {
    181   DCHECK(CalledOnValidThread());
    182   base::DictionaryValue* out = new base::DictionaryValue;
    183   PrefRegistry::const_iterator i = pref_registry_->begin();
    184   for (; i != pref_registry_->end(); ++i) {
    185     const base::Value* value = GetPreferenceValue(i->first);
    186     DCHECK(value);
    187     out->Set(i->first, value->DeepCopy());
    188   }
    189   return out;
    190 }
    191 
    192 const 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 
    207 bool PrefService::ReadOnly() const {
    208   return user_pref_store_->ReadOnly();
    209 }
    210 
    211 PrefService::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 
    226 bool PrefService::IsManagedPreference(const char* pref_name) const {
    227   const Preference* pref = FindPreference(pref_name);
    228   return pref && pref->IsManaged();
    229 }
    230 
    231 bool PrefService::IsUserModifiablePreference(const char* pref_name) const {
    232   const Preference* pref = FindPreference(pref_name);
    233   return pref && pref->IsUserModifiable();
    234 }
    235 
    236 const base::DictionaryValue* PrefService::GetDictionary(
    237     const char* path) const {
    238   DCHECK(CalledOnValidThread());
    239 
    240   const base::Value* value = GetPreferenceValue(path);
    241   if (!value) {
    242     NOTREACHED() << "Trying to read an unregistered pref: " << path;
    243     return NULL;
    244   }
    245   if (value->GetType() != base::Value::TYPE_DICTIONARY) {
    246     NOTREACHED();
    247     return NULL;
    248   }
    249   return static_cast<const base::DictionaryValue*>(value);
    250 }
    251 
    252 const base::Value* PrefService::GetUserPrefValue(const char* path) const {
    253   DCHECK(CalledOnValidThread());
    254 
    255   const Preference* pref = FindPreference(path);
    256   if (!pref) {
    257     NOTREACHED() << "Trying to get an unregistered pref: " << path;
    258     return NULL;
    259   }
    260 
    261   // Look for an existing preference in the user store. If it doesn't
    262   // exist, return NULL.
    263   base::Value* value = NULL;
    264   if (!user_pref_store_->GetMutableValue(path, &value))
    265     return NULL;
    266 
    267   if (!value->IsType(pref->GetType())) {
    268     NOTREACHED() << "Pref value type doesn't match registered type.";
    269     return NULL;
    270   }
    271 
    272   return value;
    273 }
    274 
    275 void PrefService::SetDefaultPrefValue(const char* path,
    276                                       base::Value* value) {
    277   DCHECK(CalledOnValidThread());
    278   pref_registry_->SetDefaultPrefValue(path, value);
    279 }
    280 
    281 const base::Value* PrefService::GetDefaultPrefValue(const char* path) const {
    282   DCHECK(CalledOnValidThread());
    283   // Lookup the preference in the default store.
    284   const base::Value* value = NULL;
    285   if (!pref_registry_->defaults()->GetValue(path, &value)) {
    286     NOTREACHED() << "Default value missing for pref: " << path;
    287     return NULL;
    288   }
    289   return value;
    290 }
    291 
    292 const base::ListValue* PrefService::GetList(const char* path) const {
    293   DCHECK(CalledOnValidThread());
    294 
    295   const base::Value* value = GetPreferenceValue(path);
    296   if (!value) {
    297     NOTREACHED() << "Trying to read an unregistered pref: " << path;
    298     return NULL;
    299   }
    300   if (value->GetType() != base::Value::TYPE_LIST) {
    301     NOTREACHED();
    302     return NULL;
    303   }
    304   return static_cast<const base::ListValue*>(value);
    305 }
    306 
    307 void PrefService::AddPrefObserver(const char* path, PrefObserver* obs) {
    308   pref_notifier_->AddPrefObserver(path, obs);
    309 }
    310 
    311 void PrefService::RemovePrefObserver(const char* path, PrefObserver* obs) {
    312   pref_notifier_->RemovePrefObserver(path, obs);
    313 }
    314 
    315 void PrefService::AddPrefInitObserver(base::Callback<void(bool)> obs) {
    316   pref_notifier_->AddInitObserver(obs);
    317 }
    318 
    319 PrefRegistry* PrefService::DeprecatedGetPrefRegistry() {
    320   return pref_registry_.get();
    321 }
    322 
    323 void PrefService::AddInitialPreferences() {
    324   for (PrefRegistry::const_iterator it = pref_registry_->begin();
    325        it != pref_registry_->end();
    326        ++it) {
    327     AddRegisteredPreference(it->first.c_str(), it->second);
    328   }
    329 }
    330 
    331 // TODO(joi): Once MarkNeedsEmptyValue is gone, we can probably
    332 // completely get rid of this method. There will be one difference in
    333 // semantics; currently all registered preferences are stored right
    334 // away in the prefs_map_, if we remove this they would be stored only
    335 // opportunistically.
    336 void PrefService::AddRegisteredPreference(const char* path,
    337                                           base::Value* default_value) {
    338   DCHECK(CalledOnValidThread());
    339 
    340   // For ListValue and DictionaryValue with non empty default, empty value
    341   // for |path| needs to be persisted in |user_pref_store_|. So that
    342   // non empty default is not used when user sets an empty ListValue or
    343   // DictionaryValue.
    344   bool needs_empty_value = false;
    345   base::Value::Type orig_type = default_value->GetType();
    346   if (orig_type == base::Value::TYPE_LIST) {
    347     const base::ListValue* list = NULL;
    348     if (default_value->GetAsList(&list) && !list->empty())
    349       needs_empty_value = true;
    350   } else if (orig_type == base::Value::TYPE_DICTIONARY) {
    351     const base::DictionaryValue* dict = NULL;
    352     if (default_value->GetAsDictionary(&dict) && !dict->empty())
    353       needs_empty_value = true;
    354   }
    355   if (needs_empty_value)
    356     user_pref_store_->MarkNeedsEmptyValue(path);
    357 }
    358 
    359 void PrefService::ClearPref(const char* path) {
    360   DCHECK(CalledOnValidThread());
    361 
    362   const Preference* pref = FindPreference(path);
    363   if (!pref) {
    364     NOTREACHED() << "Trying to clear an unregistered pref: " << path;
    365     return;
    366   }
    367   user_pref_store_->RemoveValue(path);
    368 }
    369 
    370 void PrefService::Set(const char* path, const base::Value& value) {
    371   SetUserPrefValue(path, value.DeepCopy());
    372 }
    373 
    374 void PrefService::SetBoolean(const char* path, bool value) {
    375   SetUserPrefValue(path, base::Value::CreateBooleanValue(value));
    376 }
    377 
    378 void PrefService::SetInteger(const char* path, int value) {
    379   SetUserPrefValue(path, base::Value::CreateIntegerValue(value));
    380 }
    381 
    382 void PrefService::SetDouble(const char* path, double value) {
    383   SetUserPrefValue(path, base::Value::CreateDoubleValue(value));
    384 }
    385 
    386 void PrefService::SetString(const char* path, const std::string& value) {
    387   SetUserPrefValue(path, base::Value::CreateStringValue(value));
    388 }
    389 
    390 void PrefService::SetFilePath(const char* path, const base::FilePath& value) {
    391   SetUserPrefValue(path, base::CreateFilePathValue(value));
    392 }
    393 
    394 void PrefService::SetInt64(const char* path, int64 value) {
    395   SetUserPrefValue(path,
    396                    base::Value::CreateStringValue(base::Int64ToString(value)));
    397 }
    398 
    399 int64 PrefService::GetInt64(const char* path) const {
    400   DCHECK(CalledOnValidThread());
    401 
    402   const base::Value* value = GetPreferenceValue(path);
    403   if (!value) {
    404     NOTREACHED() << "Trying to read an unregistered pref: " << path;
    405     return 0;
    406   }
    407   std::string result("0");
    408   bool rv = value->GetAsString(&result);
    409   DCHECK(rv);
    410 
    411   int64 val;
    412   base::StringToInt64(result, &val);
    413   return val;
    414 }
    415 
    416 void PrefService::SetUint64(const char* path, uint64 value) {
    417   SetUserPrefValue(path,
    418                    base::Value::CreateStringValue(base::Uint64ToString(value)));
    419 }
    420 
    421 uint64 PrefService::GetUint64(const char* path) const {
    422   DCHECK(CalledOnValidThread());
    423 
    424   const base::Value* value = GetPreferenceValue(path);
    425   if (!value) {
    426     NOTREACHED() << "Trying to read an unregistered pref: " << path;
    427     return 0;
    428   }
    429   std::string result("0");
    430   bool rv = value->GetAsString(&result);
    431   DCHECK(rv);
    432 
    433   uint64 val;
    434   base::StringToUint64(result, &val);
    435   return val;
    436 }
    437 
    438 base::Value* PrefService::GetMutableUserPref(const char* path,
    439                                              base::Value::Type type) {
    440   CHECK(type == base::Value::TYPE_DICTIONARY || type == base::Value::TYPE_LIST);
    441   DCHECK(CalledOnValidThread());
    442 
    443   const Preference* pref = FindPreference(path);
    444   if (!pref) {
    445     NOTREACHED() << "Trying to get an unregistered pref: " << path;
    446     return NULL;
    447   }
    448   if (pref->GetType() != type) {
    449     NOTREACHED() << "Wrong type for GetMutableValue: " << path;
    450     return NULL;
    451   }
    452 
    453   // Look for an existing preference in the user store. If it doesn't
    454   // exist or isn't the correct type, create a new user preference.
    455   base::Value* value = NULL;
    456   if (!user_pref_store_->GetMutableValue(path, &value) ||
    457       !value->IsType(type)) {
    458     if (type == base::Value::TYPE_DICTIONARY) {
    459       value = new base::DictionaryValue;
    460     } else if (type == base::Value::TYPE_LIST) {
    461       value = new base::ListValue;
    462     } else {
    463       NOTREACHED();
    464     }
    465     user_pref_store_->SetValueSilently(path, value);
    466   }
    467   return value;
    468 }
    469 
    470 void PrefService::ReportUserPrefChanged(const std::string& key) {
    471   user_pref_store_->ReportValueChanged(key);
    472 }
    473 
    474 void PrefService::SetUserPrefValue(const char* path, base::Value* new_value) {
    475   scoped_ptr<base::Value> owned_value(new_value);
    476   DCHECK(CalledOnValidThread());
    477 
    478   const Preference* pref = FindPreference(path);
    479   if (!pref) {
    480     NOTREACHED() << "Trying to write an unregistered pref: " << path;
    481     return;
    482   }
    483   if (pref->GetType() != new_value->GetType()) {
    484     NOTREACHED() << "Trying to set pref " << path
    485                  << " of type " << pref->GetType()
    486                  << " to value of type " << new_value->GetType();
    487     return;
    488   }
    489 
    490   user_pref_store_->SetValue(path, owned_value.release());
    491 }
    492 
    493 void PrefService::UpdateCommandLinePrefStore(PrefStore* command_line_store) {
    494   pref_value_store_->UpdateCommandLinePrefStore(command_line_store);
    495 }
    496 
    497 ///////////////////////////////////////////////////////////////////////////////
    498 // PrefService::Preference
    499 
    500 PrefService::Preference::Preference(const PrefService* service,
    501                                     const char* name,
    502                                     base::Value::Type type)
    503       : name_(name),
    504         type_(type),
    505         pref_service_(service) {
    506   DCHECK(name);
    507   DCHECK(service);
    508 }
    509 
    510 const std::string PrefService::Preference::name() const {
    511   return name_;
    512 }
    513 
    514 base::Value::Type PrefService::Preference::GetType() const {
    515   return type_;
    516 }
    517 
    518 const base::Value* PrefService::Preference::GetValue() const {
    519   const base::Value* result= pref_service_->GetPreferenceValue(name_);
    520   DCHECK(result) << "Must register pref before getting its value";
    521   return result;
    522 }
    523 
    524 const base::Value* PrefService::Preference::GetRecommendedValue() const {
    525   DCHECK(pref_service_->FindPreference(name_.c_str())) <<
    526       "Must register pref before getting its value";
    527 
    528   const base::Value* found_value = NULL;
    529   if (pref_value_store()->GetRecommendedValue(name_, type_, &found_value)) {
    530     DCHECK(found_value->IsType(type_));
    531     return found_value;
    532   }
    533 
    534   // The pref has no recommended value.
    535   return NULL;
    536 }
    537 
    538 bool PrefService::Preference::IsManaged() const {
    539   return pref_value_store()->PrefValueInManagedStore(name_.c_str());
    540 }
    541 
    542 bool PrefService::Preference::IsRecommended() const {
    543   return pref_value_store()->PrefValueFromRecommendedStore(name_.c_str());
    544 }
    545 
    546 bool PrefService::Preference::HasExtensionSetting() const {
    547   return pref_value_store()->PrefValueInExtensionStore(name_.c_str());
    548 }
    549 
    550 bool PrefService::Preference::HasUserSetting() const {
    551   return pref_value_store()->PrefValueInUserStore(name_.c_str());
    552 }
    553 
    554 bool PrefService::Preference::IsExtensionControlled() const {
    555   return pref_value_store()->PrefValueFromExtensionStore(name_.c_str());
    556 }
    557 
    558 bool PrefService::Preference::IsUserControlled() const {
    559   return pref_value_store()->PrefValueFromUserStore(name_.c_str());
    560 }
    561 
    562 bool PrefService::Preference::IsDefaultValue() const {
    563   return pref_value_store()->PrefValueFromDefaultStore(name_.c_str());
    564 }
    565 
    566 bool PrefService::Preference::IsUserModifiable() const {
    567   return pref_value_store()->PrefValueUserModifiable(name_.c_str());
    568 }
    569 
    570 bool PrefService::Preference::IsExtensionModifiable() const {
    571   return pref_value_store()->PrefValueExtensionModifiable(name_.c_str());
    572 }
    573 
    574 const base::Value* PrefService::GetPreferenceValue(
    575     const std::string& path) const {
    576   DCHECK(CalledOnValidThread());
    577   const base::Value* default_value = NULL;
    578   if (pref_registry_->defaults()->GetValue(path, &default_value)) {
    579     const base::Value* found_value = NULL;
    580     base::Value::Type default_type = default_value->GetType();
    581     if (pref_value_store_->GetValue(path, default_type, &found_value)) {
    582       DCHECK(found_value->IsType(default_type));
    583       return found_value;
    584     } else {
    585       // Every registered preference has at least a default value.
    586       NOTREACHED() << "no valid value found for registered pref " << path;
    587     }
    588   }
    589 
    590   return NULL;
    591 }
    592