- add sources.
[platform/framework/web/crosswalk.git] / src / base / prefs / pref_service.cc
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 void PrefService::CommitPendingWrite() {
91   DCHECK(CalledOnValidThread());
92   user_pref_store_->CommitPendingWrite();
93 }
94
95 bool PrefService::GetBoolean(const char* path) const {
96   DCHECK(CalledOnValidThread());
97
98   bool result = false;
99
100   const base::Value* value = GetPreferenceValue(path);
101   if (!value) {
102     NOTREACHED() << "Trying to read an unregistered pref: " << path;
103     return result;
104   }
105   bool rv = value->GetAsBoolean(&result);
106   DCHECK(rv);
107   return result;
108 }
109
110 int PrefService::GetInteger(const char* path) const {
111   DCHECK(CalledOnValidThread());
112
113   int result = 0;
114
115   const base::Value* value = GetPreferenceValue(path);
116   if (!value) {
117     NOTREACHED() << "Trying to read an unregistered pref: " << path;
118     return result;
119   }
120   bool rv = value->GetAsInteger(&result);
121   DCHECK(rv);
122   return result;
123 }
124
125 double PrefService::GetDouble(const char* path) const {
126   DCHECK(CalledOnValidThread());
127
128   double result = 0.0;
129
130   const base::Value* value = GetPreferenceValue(path);
131   if (!value) {
132     NOTREACHED() << "Trying to read an unregistered pref: " << path;
133     return result;
134   }
135   bool rv = value->GetAsDouble(&result);
136   DCHECK(rv);
137   return result;
138 }
139
140 std::string PrefService::GetString(const char* path) const {
141   DCHECK(CalledOnValidThread());
142
143   std::string result;
144
145   const base::Value* value = GetPreferenceValue(path);
146   if (!value) {
147     NOTREACHED() << "Trying to read an unregistered pref: " << path;
148     return result;
149   }
150   bool rv = value->GetAsString(&result);
151   DCHECK(rv);
152   return result;
153 }
154
155 base::FilePath PrefService::GetFilePath(const char* path) const {
156   DCHECK(CalledOnValidThread());
157
158   base::FilePath result;
159
160   const base::Value* value = GetPreferenceValue(path);
161   if (!value) {
162     NOTREACHED() << "Trying to read an unregistered pref: " << path;
163     return base::FilePath(result);
164   }
165   bool rv = base::GetValueAsFilePath(*value, &result);
166   DCHECK(rv);
167   return result;
168 }
169
170 bool PrefService::HasPrefPath(const char* path) const {
171   const Preference* pref = FindPreference(path);
172   return pref && !pref->IsDefaultValue();
173 }
174
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);
181     DCHECK(value);
182     out->Set(i->first, value->DeepCopy());
183   }
184   return out.Pass();
185 }
186
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);
194     DCHECK(value);
195     out->SetWithoutPathExpansion(i->first, value->DeepCopy());
196   }
197   return out.Pass();
198 }
199
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))
208     return NULL;
209   it = prefs_map_.insert(
210       std::make_pair(pref_name, Preference(
211           this, pref_name, default_value->GetType()))).first;
212   return &(it->second);
213 }
214
215 bool PrefService::ReadOnly() const {
216   return user_pref_store_->ReadOnly();
217 }
218
219 PrefService::PrefInitializationStatus PrefService::GetInitializationStatus()
220     const {
221   if (!user_pref_store_->IsInitializationComplete())
222     return INITIALIZATION_STATUS_WAITING;
223
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;
229     default:
230       return INITIALIZATION_STATUS_ERROR;
231   }
232 }
233
234 bool PrefService::IsManagedPreference(const char* pref_name) const {
235   const Preference* pref = FindPreference(pref_name);
236   return pref && pref->IsManaged();
237 }
238
239 bool PrefService::IsUserModifiablePreference(const char* pref_name) const {
240   const Preference* pref = FindPreference(pref_name);
241   return pref && pref->IsUserModifiable();
242 }
243
244 const base::DictionaryValue* PrefService::GetDictionary(
245     const char* path) const {
246   DCHECK(CalledOnValidThread());
247
248   const base::Value* value = GetPreferenceValue(path);
249   if (!value) {
250     NOTREACHED() << "Trying to read an unregistered pref: " << path;
251     return NULL;
252   }
253   if (value->GetType() != base::Value::TYPE_DICTIONARY) {
254     NOTREACHED();
255     return NULL;
256   }
257   return static_cast<const base::DictionaryValue*>(value);
258 }
259
260 const base::Value* PrefService::GetUserPrefValue(const char* path) const {
261   DCHECK(CalledOnValidThread());
262
263   const Preference* pref = FindPreference(path);
264   if (!pref) {
265     NOTREACHED() << "Trying to get an unregistered pref: " << path;
266     return NULL;
267   }
268
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))
273     return NULL;
274
275   if (!value->IsType(pref->GetType())) {
276     NOTREACHED() << "Pref value type doesn't match registered type.";
277     return NULL;
278   }
279
280   return value;
281 }
282
283 void PrefService::SetDefaultPrefValue(const char* path,
284                                       base::Value* value) {
285   DCHECK(CalledOnValidThread());
286   pref_registry_->SetDefaultPrefValue(path, value);
287 }
288
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;
295     return NULL;
296   }
297   return value;
298 }
299
300 const base::ListValue* PrefService::GetList(const char* path) const {
301   DCHECK(CalledOnValidThread());
302
303   const base::Value* value = GetPreferenceValue(path);
304   if (!value) {
305     NOTREACHED() << "Trying to read an unregistered pref: " << path;
306     return NULL;
307   }
308   if (value->GetType() != base::Value::TYPE_LIST) {
309     NOTREACHED();
310     return NULL;
311   }
312   return static_cast<const base::ListValue*>(value);
313 }
314
315 void PrefService::AddPrefObserver(const char* path, PrefObserver* obs) {
316   pref_notifier_->AddPrefObserver(path, obs);
317 }
318
319 void PrefService::RemovePrefObserver(const char* path, PrefObserver* obs) {
320   pref_notifier_->RemovePrefObserver(path, obs);
321 }
322
323 void PrefService::AddPrefInitObserver(base::Callback<void(bool)> obs) {
324   pref_notifier_->AddInitObserver(obs);
325 }
326
327 PrefRegistry* PrefService::DeprecatedGetPrefRegistry() {
328   return pref_registry_.get();
329 }
330
331 void PrefService::AddInitialPreferences() {
332   for (PrefRegistry::const_iterator it = pref_registry_->begin();
333        it != pref_registry_->end();
334        ++it) {
335     AddRegisteredPreference(it->first.c_str(), it->second);
336   }
337 }
338
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());
347
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
351   // DictionaryValue.
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;
362   }
363   if (needs_empty_value)
364     user_pref_store_->MarkNeedsEmptyValue(path);
365 }
366
367 void PrefService::ClearPref(const char* path) {
368   DCHECK(CalledOnValidThread());
369
370   const Preference* pref = FindPreference(path);
371   if (!pref) {
372     NOTREACHED() << "Trying to clear an unregistered pref: " << path;
373     return;
374   }
375   user_pref_store_->RemoveValue(path);
376 }
377
378 void PrefService::Set(const char* path, const base::Value& value) {
379   SetUserPrefValue(path, value.DeepCopy());
380 }
381
382 void PrefService::SetBoolean(const char* path, bool value) {
383   SetUserPrefValue(path, base::Value::CreateBooleanValue(value));
384 }
385
386 void PrefService::SetInteger(const char* path, int value) {
387   SetUserPrefValue(path, base::Value::CreateIntegerValue(value));
388 }
389
390 void PrefService::SetDouble(const char* path, double value) {
391   SetUserPrefValue(path, base::Value::CreateDoubleValue(value));
392 }
393
394 void PrefService::SetString(const char* path, const std::string& value) {
395   SetUserPrefValue(path, base::Value::CreateStringValue(value));
396 }
397
398 void PrefService::SetFilePath(const char* path, const base::FilePath& value) {
399   SetUserPrefValue(path, base::CreateFilePathValue(value));
400 }
401
402 void PrefService::SetInt64(const char* path, int64 value) {
403   SetUserPrefValue(path,
404                    base::Value::CreateStringValue(base::Int64ToString(value)));
405 }
406
407 int64 PrefService::GetInt64(const char* path) const {
408   DCHECK(CalledOnValidThread());
409
410   const base::Value* value = GetPreferenceValue(path);
411   if (!value) {
412     NOTREACHED() << "Trying to read an unregistered pref: " << path;
413     return 0;
414   }
415   std::string result("0");
416   bool rv = value->GetAsString(&result);
417   DCHECK(rv);
418
419   int64 val;
420   base::StringToInt64(result, &val);
421   return val;
422 }
423
424 void PrefService::SetUint64(const char* path, uint64 value) {
425   SetUserPrefValue(path,
426                    base::Value::CreateStringValue(base::Uint64ToString(value)));
427 }
428
429 uint64 PrefService::GetUint64(const char* path) const {
430   DCHECK(CalledOnValidThread());
431
432   const base::Value* value = GetPreferenceValue(path);
433   if (!value) {
434     NOTREACHED() << "Trying to read an unregistered pref: " << path;
435     return 0;
436   }
437   std::string result("0");
438   bool rv = value->GetAsString(&result);
439   DCHECK(rv);
440
441   uint64 val;
442   base::StringToUint64(result, &val);
443   return val;
444 }
445
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());
450
451   const Preference* pref = FindPreference(path);
452   if (!pref) {
453     NOTREACHED() << "Trying to get an unregistered pref: " << path;
454     return NULL;
455   }
456   if (pref->GetType() != type) {
457     NOTREACHED() << "Wrong type for GetMutableValue: " << path;
458     return NULL;
459   }
460
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;
470     } else {
471       NOTREACHED();
472     }
473     user_pref_store_->SetValueSilently(path, value);
474   }
475   return value;
476 }
477
478 void PrefService::ReportUserPrefChanged(const std::string& key) {
479   user_pref_store_->ReportValueChanged(key);
480 }
481
482 void PrefService::SetUserPrefValue(const char* path, base::Value* new_value) {
483   scoped_ptr<base::Value> owned_value(new_value);
484   DCHECK(CalledOnValidThread());
485
486   const Preference* pref = FindPreference(path);
487   if (!pref) {
488     NOTREACHED() << "Trying to write an unregistered pref: " << path;
489     return;
490   }
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();
495     return;
496   }
497
498   user_pref_store_->SetValue(path, owned_value.release());
499 }
500
501 void PrefService::UpdateCommandLinePrefStore(PrefStore* command_line_store) {
502   pref_value_store_->UpdateCommandLinePrefStore(command_line_store);
503 }
504
505 ///////////////////////////////////////////////////////////////////////////////
506 // PrefService::Preference
507
508 PrefService::Preference::Preference(const PrefService* service,
509                                     const char* name,
510                                     base::Value::Type type)
511       : name_(name),
512         type_(type),
513         pref_service_(service) {
514   DCHECK(name);
515   DCHECK(service);
516 }
517
518 const std::string PrefService::Preference::name() const {
519   return name_;
520 }
521
522 base::Value::Type PrefService::Preference::GetType() const {
523   return type_;
524 }
525
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";
529   return result;
530 }
531
532 const base::Value* PrefService::Preference::GetRecommendedValue() const {
533   DCHECK(pref_service_->FindPreference(name_.c_str())) <<
534       "Must register pref before getting its value";
535
536   const base::Value* found_value = NULL;
537   if (pref_value_store()->GetRecommendedValue(name_, type_, &found_value)) {
538     DCHECK(found_value->IsType(type_));
539     return found_value;
540   }
541
542   // The pref has no recommended value.
543   return NULL;
544 }
545
546 bool PrefService::Preference::IsManaged() const {
547   return pref_value_store()->PrefValueInManagedStore(name_.c_str());
548 }
549
550 bool PrefService::Preference::IsRecommended() const {
551   return pref_value_store()->PrefValueFromRecommendedStore(name_.c_str());
552 }
553
554 bool PrefService::Preference::HasExtensionSetting() const {
555   return pref_value_store()->PrefValueInExtensionStore(name_.c_str());
556 }
557
558 bool PrefService::Preference::HasUserSetting() const {
559   return pref_value_store()->PrefValueInUserStore(name_.c_str());
560 }
561
562 bool PrefService::Preference::IsExtensionControlled() const {
563   return pref_value_store()->PrefValueFromExtensionStore(name_.c_str());
564 }
565
566 bool PrefService::Preference::IsUserControlled() const {
567   return pref_value_store()->PrefValueFromUserStore(name_.c_str());
568 }
569
570 bool PrefService::Preference::IsDefaultValue() const {
571   return pref_value_store()->PrefValueFromDefaultStore(name_.c_str());
572 }
573
574 bool PrefService::Preference::IsUserModifiable() const {
575   return pref_value_store()->PrefValueUserModifiable(name_.c_str());
576 }
577
578 bool PrefService::Preference::IsExtensionModifiable() const {
579   return pref_value_store()->PrefValueExtensionModifiable(name_.c_str());
580 }
581
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));
591       return found_value;
592     } else {
593       // Every registered preference has at least a default value.
594       NOTREACHED() << "no valid value found for registered pref " << path;
595     }
596   }
597
598   return NULL;
599 }