summaryrefslogtreecommitdiffstats
path: root/chrome/browser/prefs/pref_service.cc
blob: efe9a93238237d04ada02490cfb40b5ff76d41dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/prefs/pref_service.h"

#include <algorithm>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/prefs/default_pref_store.h"
#include "base/prefs/json_pref_store.h"
#include "base/prefs/overlay_user_pref_store.h"
#include "base/stl_util.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/value_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_pref_store.h"
#include "chrome/browser/policy/configuration_policy_pref_store.h"
#include "chrome/browser/prefs/command_line_pref_store.h"
#include "chrome/browser/prefs/pref_model_associator.h"
#include "chrome/browser/prefs/pref_notifier_impl.h"
#include "chrome/browser/prefs/pref_service_observer.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/prefs/prefs_tab_helper.h"
#include "chrome/browser/ui/profile_error_dialog.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

using content::BrowserContext;
using content::BrowserThread;

namespace {

// A helper function for RegisterLocalized*Pref that creates a Value* based on
// the string value in the locale dll.  Because we control the values in a
// locale dll, this should always return a Value of the appropriate type.
Value* CreateLocaleDefaultValue(base::Value::Type type, int message_id) {
  std::string resource_string = l10n_util::GetStringUTF8(message_id);
  DCHECK(!resource_string.empty());
  switch (type) {
    case Value::TYPE_BOOLEAN: {
      if ("true" == resource_string)
        return Value::CreateBooleanValue(true);
      if ("false" == resource_string)
        return Value::CreateBooleanValue(false);
      break;
    }

    case Value::TYPE_INTEGER: {
      int val;
      base::StringToInt(resource_string, &val);
      return Value::CreateIntegerValue(val);
    }

    case Value::TYPE_DOUBLE: {
      double val;
      base::StringToDouble(resource_string, &val);
      return Value::CreateDoubleValue(val);
    }

    case Value::TYPE_STRING: {
      return Value::CreateStringValue(resource_string);
    }

    default: {
      NOTREACHED() <<
          "list and dictionary types cannot have default locale values";
    }
  }
  NOTREACHED();
  return Value::CreateNullValue();
}

// Forwards a notification after a PostMessage so that we can wait for the
// MessageLoop to run.
void NotifyReadError(int message_id) {
  ShowProfileErrorDialog(message_id);
}

// Shows notifications which correspond to PersistentPrefStore's reading errors.
class ReadErrorHandler : public PersistentPrefStore::ReadErrorDelegate {
 public:
  virtual void OnError(PersistentPrefStore::PrefReadError error) {
    if (error != PersistentPrefStore::PREF_READ_ERROR_NONE) {
      // Failing to load prefs on startup is a bad thing(TM). See bug 38352 for
      // an example problem that this can cause.
      // Do some diagnosis and try to avoid losing data.
      int message_id = 0;
      if (error <= PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE) {
        message_id = IDS_PREFERENCES_CORRUPT_ERROR;
      } else if (error != PersistentPrefStore::PREF_READ_ERROR_NO_FILE) {
        message_id = IDS_PREFERENCES_UNREADABLE_ERROR;
      }

      if (message_id) {
        BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
            base::Bind(&NotifyReadError, message_id));
      }
      UMA_HISTOGRAM_ENUMERATION("PrefService.ReadError", error,
                                PersistentPrefStore::PREF_READ_ERROR_MAX_ENUM);
    }
  }
};

}  // namespace

PrefServiceBase* PrefServiceBase::FromBrowserContext(BrowserContext* context) {
  return static_cast<Profile*>(context)->GetPrefs();
}

// static
PrefService* PrefService::CreatePrefService(
    const FilePath& pref_filename,
    base::SequencedTaskRunner* pref_io_task_runner,
    policy::PolicyService* policy_service,
    PrefStore* extension_prefs,
    bool async) {
  using policy::ConfigurationPolicyPrefStore;

#if defined(OS_LINUX)
  // We'd like to see what fraction of our users have the preferences
  // stored on a network file system, as we've had no end of troubles
  // with NFS/AFS.
  // TODO(evanm): remove this once we've collected state.
  file_util::FileSystemType fstype;
  if (file_util::GetFileSystemType(pref_filename.DirName(), &fstype)) {
    UMA_HISTOGRAM_ENUMERATION("PrefService.FileSystemType",
                              static_cast<int>(fstype),
                              file_util::FILE_SYSTEM_TYPE_COUNT);
  }
#endif

#if defined(ENABLE_CONFIGURATION_POLICY)
  ConfigurationPolicyPrefStore* managed =
      ConfigurationPolicyPrefStore::CreateMandatoryPolicyPrefStore(
          policy_service);
  ConfigurationPolicyPrefStore* recommended =
      ConfigurationPolicyPrefStore::CreateRecommendedPolicyPrefStore(
          policy_service);
#else
  ConfigurationPolicyPrefStore* managed = NULL;
  ConfigurationPolicyPrefStore* recommended = NULL;
#endif  // ENABLE_CONFIGURATION_POLICY

  CommandLinePrefStore* command_line =
      new CommandLinePrefStore(CommandLine::ForCurrentProcess());
  JsonPrefStore* user = new JsonPrefStore(
      pref_filename, pref_io_task_runner);
  DefaultPrefStore* default_pref_store = new DefaultPrefStore();

  PrefNotifierImpl* pref_notifier = new PrefNotifierImpl();
  PrefModelAssociator* pref_sync_associator = new PrefModelAssociator();

  return new PrefService(
      pref_notifier,
      new PrefValueStore(
          managed,
          extension_prefs,
          command_line,
          user,
          recommended,
          default_pref_store,
          pref_sync_associator,
          pref_notifier),
      user,
      default_pref_store,
      pref_sync_associator,
      async);
}

PrefService* PrefService::CreateIncognitoPrefService(
    PrefStore* incognito_extension_prefs) {
  pref_service_forked_ = true;
  PrefNotifierImpl* pref_notifier = new PrefNotifierImpl();
  OverlayUserPrefStore* incognito_pref_store =
      new OverlayUserPrefStore(user_pref_store_.get());
  PrefsTabHelper::InitIncognitoUserPrefStore(incognito_pref_store);
  return new PrefService(
      pref_notifier,
      pref_value_store_->CloneAndSpecialize(
          NULL,  // managed
          incognito_extension_prefs,
          NULL,  // command_line_prefs
          incognito_pref_store,
          NULL,  // recommended
          default_store_.get(),
          NULL,  // pref_sync_associator
          pref_notifier),
      incognito_pref_store,
      default_store_.get(),
      NULL,
      false);
}

PrefService::PrefService(PrefNotifierImpl* pref_notifier,
                         PrefValueStore* pref_value_store,
                         PersistentPrefStore* user_prefs,
                         DefaultPrefStore* default_store,
                         PrefModelAssociator* pref_sync_associator,
                         bool async)
    : pref_notifier_(pref_notifier),
      pref_value_store_(pref_value_store),
      user_pref_store_(user_prefs),
      default_store_(default_store),
      pref_sync_associator_(pref_sync_associator),
      pref_service_forked_(false) {
  pref_notifier_->SetPrefService(this);
  if (pref_sync_associator_.get())
    pref_sync_associator_->SetPrefService(this);
  InitFromStorage(async);
}

PrefService::~PrefService() {
  DCHECK(CalledOnValidThread());

  // Reset pointers so accesses after destruction reliably crash.
  pref_value_store_.reset();
  user_pref_store_ = NULL;
  default_store_ = NULL;
  pref_sync_associator_.reset();
  pref_notifier_.reset();
}

void PrefService::InitFromStorage(bool async) {
  if (!async) {
    ReadErrorHandler error_handler;
    error_handler.OnError(user_pref_store_->ReadPrefs());
  } else {
    // Guarantee that initialization happens after this function returned.
    MessageLoop::current()->PostTask(
        FROM_HERE,
        base::Bind(&PersistentPrefStore::ReadPrefsAsync,
                   user_pref_store_.get(),
                   new ReadErrorHandler()));
  }
}

bool PrefService::ReloadPersistentPrefs() {
  return user_pref_store_->ReadPrefs() ==
             PersistentPrefStore::PREF_READ_ERROR_NONE;
}

void PrefService::CommitPendingWrite() {
  DCHECK(CalledOnValidThread());
  user_pref_store_->CommitPendingWrite();
}

void PrefService::AddObserver(PrefServiceObserver* observer) {
  observer_list_.AddObserver(observer);
}

void PrefService::RemoveObserver(PrefServiceObserver* observer) {
  observer_list_.RemoveObserver(observer);
}

bool PrefService::IsSyncing() {
  return pref_sync_associator_.get() &&
      pref_sync_associator_->models_associated();
}

void PrefService::OnIsSyncingChanged() {
  FOR_EACH_OBSERVER(PrefServiceObserver, observer_list_, OnIsSyncingChanged());
}

namespace {

// If there's no g_browser_process or no local state, return true (for testing).
bool IsLocalStatePrefService(PrefService* prefs) {
  return (!g_browser_process ||
          !g_browser_process->local_state() ||
          g_browser_process->local_state() == prefs);
}

// If there's no g_browser_process, return true (for testing).
bool IsProfilePrefService(PrefService* prefs) {
  // TODO(zea): uncomment this once all preferences are only ever registered
  // with either the local_state's pref service or the profile's pref service.
  // return (!g_browser_process || g_browser_process->local_state() != prefs);
  return true;
}

}  // namespace


// Local State prefs.
void PrefService::RegisterBooleanPref(const char* path,
                                      bool default_value) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(path,
                     Value::CreateBooleanValue(default_value),
                     UNSYNCABLE_PREF);
}

void PrefService::RegisterIntegerPref(const char* path, int default_value) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(path,
                     Value::CreateIntegerValue(default_value),
                     UNSYNCABLE_PREF);
}

void PrefService::RegisterDoublePref(const char* path, double default_value) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(path,
                     Value::CreateDoubleValue(default_value),
                     UNSYNCABLE_PREF);
}

void PrefService::RegisterStringPref(const char* path,
                                     const std::string& default_value) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(path,
                     Value::CreateStringValue(default_value),
                     UNSYNCABLE_PREF);
}

void PrefService::RegisterFilePathPref(const char* path,
                                       const FilePath& default_value) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(path,
                     Value::CreateStringValue(default_value.value()),
                     UNSYNCABLE_PREF);
}

void PrefService::RegisterListPref(const char* path) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(path,
                     new ListValue(),
                     UNSYNCABLE_PREF);
}

void PrefService::RegisterListPref(const char* path, ListValue* default_value) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(path,
                     default_value,
                     UNSYNCABLE_PREF);
}

void PrefService::RegisterDictionaryPref(const char* path) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(path,
                     new DictionaryValue(),
                     UNSYNCABLE_PREF);
}

void PrefService::RegisterDictionaryPref(const char* path,
                                         DictionaryValue* default_value) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(path,
                     default_value,
                     UNSYNCABLE_PREF);
}

void PrefService::RegisterLocalizedBooleanPref(const char* path,
                                               int locale_default_message_id) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(
      path,
      CreateLocaleDefaultValue(Value::TYPE_BOOLEAN, locale_default_message_id),
      UNSYNCABLE_PREF);
}

void PrefService::RegisterLocalizedIntegerPref(const char* path,
                                               int locale_default_message_id) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(
      path,
      CreateLocaleDefaultValue(Value::TYPE_INTEGER, locale_default_message_id),
      UNSYNCABLE_PREF);
}

void PrefService::RegisterLocalizedDoublePref(const char* path,
                                              int locale_default_message_id) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(
      path,
      CreateLocaleDefaultValue(Value::TYPE_DOUBLE, locale_default_message_id),
      UNSYNCABLE_PREF);
}

void PrefService::RegisterLocalizedStringPref(const char* path,
                                              int locale_default_message_id) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(
      path,
      CreateLocaleDefaultValue(Value::TYPE_STRING, locale_default_message_id),
      UNSYNCABLE_PREF);
}

void PrefService::RegisterInt64Pref(const char* path, int64 default_value) {
  // If this fails, the pref service in use is a profile pref service, so the
  // sync status must be provided (see profile pref registration calls below).
  DCHECK(IsLocalStatePrefService(this));
  RegisterPreference(
      path,
      Value::CreateStringValue(base::Int64ToString(default_value)),
      UNSYNCABLE_PREF);
}

// Profile prefs (must use the sync_status variable).
void PrefService::RegisterBooleanPref(const char* path,
                                      bool default_value,
                                      PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(path,
                     Value::CreateBooleanValue(default_value),
                     sync_status);
}

void PrefService::RegisterIntegerPref(const char* path,
                                      int default_value,
                                      PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(path,
                     Value::CreateIntegerValue(default_value),
                     sync_status);
}

void PrefService::RegisterDoublePref(const char* path,
                                     double default_value,
                                     PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(path,
                     Value::CreateDoubleValue(default_value),
                     sync_status);
}

void PrefService::RegisterStringPref(const char* path,
                                     const std::string& default_value,
                                     PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(path,
                     Value::CreateStringValue(default_value),
                     sync_status);
}

void PrefService::RegisterFilePathPref(const char* path,
                                       const FilePath& default_value,
                                       PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(path,
                     Value::CreateStringValue(default_value.value()),
                     sync_status);
}

void PrefService::RegisterListPref(const char* path,
                                   PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(path, new ListValue(), sync_status);
}

void PrefService::RegisterListPref(const char* path,
                                   ListValue* default_value,
                                   PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(path, default_value, sync_status);
}

void PrefService::RegisterDictionaryPref(const char* path,
                                         PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(path, new DictionaryValue(), sync_status);
}

void PrefService::RegisterDictionaryPref(const char* path,
                                         DictionaryValue* default_value,
                                         PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(path, default_value, sync_status);
}

void PrefService::RegisterLocalizedBooleanPref(const char* path,
                                               int locale_default_message_id,
                                               PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(
      path,
      CreateLocaleDefaultValue(Value::TYPE_BOOLEAN, locale_default_message_id),
      sync_status);
}

void PrefService::RegisterLocalizedIntegerPref(const char* path,
                                               int locale_default_message_id,
                                               PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(
      path,
      CreateLocaleDefaultValue(Value::TYPE_INTEGER, locale_default_message_id),
      sync_status);
}

void PrefService::RegisterLocalizedDoublePref(const char* path,
                                              int locale_default_message_id,
                                              PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(
      path,
      CreateLocaleDefaultValue(Value::TYPE_DOUBLE, locale_default_message_id),
      sync_status);
}

void PrefService::RegisterLocalizedStringPref(const char* path,
                                              int locale_default_message_id,
                                              PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(
      path,
      CreateLocaleDefaultValue(Value::TYPE_STRING, locale_default_message_id),
      sync_status);
}

void PrefService::RegisterInt64Pref(const char* path,
                                    int64 default_value,
                                    PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(
      path,
      Value::CreateStringValue(base::Int64ToString(default_value)),
      sync_status);
}

void PrefService::RegisterUint64Pref(const char* path,
                                     uint64 default_value,
                                     PrefSyncStatus sync_status) {
  DCHECK(IsProfilePrefService(this));
  RegisterPreference(
      path,
      Value::CreateStringValue(base::Uint64ToString(default_value)),
      sync_status);
}

bool PrefService::GetBoolean(const char* path) const {
  DCHECK(CalledOnValidThread());

  bool result = false;

  const base::Value* value = GetPreferenceValue(path);
  if (!value) {
    NOTREACHED() << "Trying to read an unregistered pref: " << path;
    return result;
  }
  bool rv = value->GetAsBoolean(&result);
  DCHECK(rv);
  return result;
}

int PrefService::GetInteger(const char* path) const {
  DCHECK(CalledOnValidThread());

  int result = 0;

  const base::Value* value = GetPreferenceValue(path);
  if (!value) {
    NOTREACHED() << "Trying to read an unregistered pref: " << path;
    return result;
  }
  bool rv = value->GetAsInteger(&result);
  DCHECK(rv);
  return result;
}

double PrefService::GetDouble(const char* path) const {
  DCHECK(CalledOnValidThread());

  double result = 0.0;

  const base::Value* value = GetPreferenceValue(path);
  if (!value) {
    NOTREACHED() << "Trying to read an unregistered pref: " << path;
    return result;
  }
  bool rv = value->GetAsDouble(&result);
  DCHECK(rv);
  return result;
}

std::string PrefService::GetString(const char* path) const {
  DCHECK(CalledOnValidThread());

  std::string result;

  const base::Value* value = GetPreferenceValue(path);
  if (!value) {
    NOTREACHED() << "Trying to read an unregistered pref: " << path;
    return result;
  }
  bool rv = value->GetAsString(&result);
  DCHECK(rv);
  return result;
}

FilePath PrefService::GetFilePath(const char* path) const {
  DCHECK(CalledOnValidThread());

  FilePath result;

  const base::Value* value = GetPreferenceValue(path);
  if (!value) {
    NOTREACHED() << "Trying to read an unregistered pref: " << path;
    return FilePath(result);
  }
  bool rv = base::GetValueAsFilePath(*value, &result);
  DCHECK(rv);
  return result;
}

bool PrefService::HasPrefPath(const char* path) const {
  const Preference* pref = FindPreference(path);
  return pref && !pref->IsDefaultValue();
}

DictionaryValue* PrefService::GetPreferenceValues() const {
  DCHECK(CalledOnValidThread());
  DictionaryValue* out = new DictionaryValue;
  DefaultPrefStore::const_iterator i = default_store_->begin();
  for (; i != default_store_->end(); ++i) {
    const Value* value = GetPreferenceValue(i->first);
    DCHECK(value);
    out->Set(i->first, value->DeepCopy());
  }
  return out;
}

const PrefService::Preference* PrefService::FindPreference(
    const char* pref_name) const {
  DCHECK(CalledOnValidThread());
  PreferenceMap::iterator it = prefs_map_.find(pref_name);
  if (it != prefs_map_.end())
    return &(it->second);
  const base::Value::Type type = default_store_->GetType(pref_name);
  if (type == Value::TYPE_NULL)
    return NULL;
  it = prefs_map_.insert(
      std::make_pair(pref_name, Preference(this, pref_name, type))).first;
  return &(it->second);
}

bool PrefService::ReadOnly() const {
  return user_pref_store_->ReadOnly();
}

PrefService::PrefInitializationStatus PrefService::GetInitializationStatus()
    const {
  if (!user_pref_store_->IsInitializationComplete())
    return INITIALIZATION_STATUS_WAITING;

  switch (user_pref_store_->GetReadError()) {
    case PersistentPrefStore::PREF_READ_ERROR_NONE:
      return INITIALIZATION_STATUS_SUCCESS;
    case PersistentPrefStore::PREF_READ_ERROR_NO_FILE:
      return INITIALIZATION_STATUS_CREATED_NEW_PROFILE;
    default:
      return INITIALIZATION_STATUS_ERROR;
  }
}

bool PrefService::IsManagedPreference(const char* pref_name) const {
  const Preference* pref = FindPreference(pref_name);
  return pref && pref->IsManaged();
}

bool PrefService::IsUserModifiablePreference(const char* pref_name) const {
  const Preference* pref = FindPreference(pref_name);
  return pref && pref->IsUserModifiable();
}

const DictionaryValue* PrefService::GetDictionary(const char* path) const {
  DCHECK(CalledOnValidThread());

  const Value* value = GetPreferenceValue(path);
  if (!value) {
    NOTREACHED() << "Trying to read an unregistered pref: " << path;
    return NULL;
  }
  if (value->GetType() != Value::TYPE_DICTIONARY) {
    NOTREACHED();
    return NULL;
  }
  return static_cast<const DictionaryValue*>(value);
}

const base::Value* PrefService::GetUserPrefValue(const char* path) const {
  DCHECK(CalledOnValidThread());

  const Preference* pref = FindPreference(path);
  if (!pref) {
    NOTREACHED() << "Trying to get an unregistered pref: " << path;
    return NULL;
  }

  // Look for an existing preference in the user store. If it doesn't
  // exist, return NULL.
  base::Value* value = NULL;
  if (!user_pref_store_->GetMutableValue(path, &value))
    return NULL;

  if (!value->IsType(pref->GetType())) {
    NOTREACHED() << "Pref value type doesn't match registered type.";
    return NULL;
  }

  return value;
}

const base::Value* PrefService::GetDefaultPrefValue(const char* path) const {
  DCHECK(CalledOnValidThread());
  // Lookup the preference in the default store.
  const base::Value* value = NULL;
  if (!default_store_->GetValue(path, &value)) {
    NOTREACHED() << "Default value missing for pref: " << path;
    return NULL;
  }
  return value;
}

const ListValue* PrefService::GetList(const char* path) const {
  DCHECK(CalledOnValidThread());

  const Value* value = GetPreferenceValue(path);
  if (!value) {
    NOTREACHED() << "Trying to read an unregistered pref: " << path;
    return NULL;
  }
  if (value->GetType() != Value::TYPE_LIST) {
    NOTREACHED();
    return NULL;
  }
  return static_cast<const ListValue*>(value);
}

void PrefService::AddPrefObserver(const char* path, PrefObserver* obs) {
  pref_notifier_->AddPrefObserver(path, obs);
}

void PrefService::RemovePrefObserver(const char* path, PrefObserver* obs) {
  pref_notifier_->RemovePrefObserver(path, obs);
}

void PrefService::AddPrefInitObserver(base::Callback<void(bool)> obs) {
  pref_notifier_->AddInitObserver(obs);
}

void PrefService::RegisterPreference(const char* path,
                                     Value* default_value,
                                     PrefSyncStatus sync_status) {
  DCHECK(CalledOnValidThread());

  // The main code path takes ownership, but most don't. We'll be safe.
  scoped_ptr<Value> scoped_value(default_value);

  CHECK(!FindPreference(path)) << "Tried to register duplicate pref " << path;

  base::Value::Type orig_type = default_value->GetType();
  DCHECK(orig_type != Value::TYPE_NULL && orig_type != Value::TYPE_BINARY) <<
         "invalid preference type: " << orig_type;

  // For ListValue and DictionaryValue with non empty default, empty value
  // for |path| needs to be persisted in |user_pref_store_|. So that
  // non empty default is not used when user sets an empty ListValue or
  // DictionaryValue.
  bool needs_empty_value = false;
  if (orig_type == base::Value::TYPE_LIST) {
    const base::ListValue* list = NULL;
    if (default_value->GetAsList(&list) && !list->empty())
      needs_empty_value = true;
  } else if (orig_type == base::Value::TYPE_DICTIONARY) {
    const base::DictionaryValue* dict = NULL;
    if (default_value->GetAsDictionary(&dict) && !dict->empty())
      needs_empty_value = true;
  }
  if (needs_empty_value)
    user_pref_store_->MarkNeedsEmptyValue(path);

  // Hand off ownership.
  default_store_->SetDefaultValue(path, scoped_value.release());

  // Register with sync if necessary.
  if (sync_status == SYNCABLE_PREF && pref_sync_associator_.get())
    pref_sync_associator_->RegisterPref(path);
}

void PrefService::UnregisterPreference(const char* path) {
  DCHECK(CalledOnValidThread());

  PreferenceMap::iterator it = prefs_map_.find(path);
  CHECK(it != prefs_map_.end()) << "Trying to unregister an unregistered pref: "
                                << path;

  prefs_map_.erase(it);
  default_store_->RemoveDefaultValue(path);
  if (pref_sync_associator_.get() &&
      pref_sync_associator_->IsPrefRegistered(path)) {
    pref_sync_associator_->UnregisterPref(path);
  }
}

void PrefService::ClearPref(const char* path) {
  DCHECK(CalledOnValidThread());

  const Preference* pref = FindPreference(path);
  if (!pref) {
    NOTREACHED() << "Trying to clear an unregistered pref: " << path;
    return;
  }
  user_pref_store_->RemoveValue(path);
}

void PrefService::Set(const char* path, const Value& value) {
  SetUserPrefValue(path, value.DeepCopy());
}

void PrefService::SetBoolean(const char* path, bool value) {
  SetUserPrefValue(path, Value::CreateBooleanValue(value));
}

void PrefService::SetInteger(const char* path, int value) {
  SetUserPrefValue(path, Value::CreateIntegerValue(value));
}

void PrefService::SetDouble(const char* path, double value) {
  SetUserPrefValue(path, Value::CreateDoubleValue(value));
}

void PrefService::SetString(const char* path, const std::string& value) {
  SetUserPrefValue(path, Value::CreateStringValue(value));
}

void PrefService::SetFilePath(const char* path, const FilePath& value) {
  SetUserPrefValue(path, base::CreateFilePathValue(value));
}

void PrefService::SetInt64(const char* path, int64 value) {
  SetUserPrefValue(path, Value::CreateStringValue(base::Int64ToString(value)));
}

int64 PrefService::GetInt64(const char* path) const {
  DCHECK(CalledOnValidThread());

  const Value* value = GetPreferenceValue(path);
  if (!value) {
    NOTREACHED() << "Trying to read an unregistered pref: " << path;
    return 0;
  }
  std::string result("0");
  bool rv = value->GetAsString(&result);
  DCHECK(rv);

  int64 val;
  base::StringToInt64(result, &val);
  return val;
}

void PrefService::SetUint64(const char* path, uint64 value) {
  SetUserPrefValue(path, Value::CreateStringValue(base::Uint64ToString(value)));
}

uint64 PrefService::GetUint64(const char* path) const {
  DCHECK(CalledOnValidThread());

  const Value* value = GetPreferenceValue(path);
  if (!value) {
    NOTREACHED() << "Trying to read an unregistered pref: " << path;
    return 0;
  }
  std::string result("0");
  bool rv = value->GetAsString(&result);
  DCHECK(rv);

  uint64 val;
  base::StringToUint64(result, &val);
  return val;
}

Value* PrefService::GetMutableUserPref(const char* path,
                                       base::Value::Type type) {
  CHECK(type == Value::TYPE_DICTIONARY || type == Value::TYPE_LIST);
  DCHECK(CalledOnValidThread());

  const Preference* pref = FindPreference(path);
  if (!pref) {
    NOTREACHED() << "Trying to get an unregistered pref: " << path;
    return NULL;
  }
  if (pref->GetType() != type) {
    NOTREACHED() << "Wrong type for GetMutableValue: " << path;
    return NULL;
  }

  // Look for an existing preference in the user store. If it doesn't
  // exist or isn't the correct type, create a new user preference.
  Value* value = NULL;
  if (!user_pref_store_->GetMutableValue(path, &value) ||
      !value->IsType(type)) {
    if (type == Value::TYPE_DICTIONARY) {
      value = new DictionaryValue;
    } else if (type == Value::TYPE_LIST) {
      value = new ListValue;
    } else {
      NOTREACHED();
    }
    user_pref_store_->SetValueSilently(path, value);
  }
  return value;
}

void PrefService::ReportUserPrefChanged(const std::string& key) {
  user_pref_store_->ReportValueChanged(key);
}

void PrefService::SetUserPrefValue(const char* path, Value* new_value) {
  scoped_ptr<Value> owned_value(new_value);
  DCHECK(CalledOnValidThread());

  const Preference* pref = FindPreference(path);
  if (!pref) {
    NOTREACHED() << "Trying to write an unregistered pref: " << path;
    return;
  }
  if (pref->GetType() != new_value->GetType()) {
    NOTREACHED() << "Trying to set pref " << path
                 << " of type " << pref->GetType()
                 << " to value of type " << new_value->GetType();
    return;
  }

  user_pref_store_->SetValue(path, owned_value.release());
}

syncer::SyncableService* PrefService::GetSyncableService() {
  return pref_sync_associator_.get();
}

void PrefService::UpdateCommandLinePrefStore(CommandLine* command_line) {
  // If |pref_service_forked_| is true, then this PrefService and the forked
  // copies will be out of sync.
  DCHECK(!pref_service_forked_);
  pref_value_store_->UpdateCommandLinePrefStore(
      new CommandLinePrefStore(command_line));
}

///////////////////////////////////////////////////////////////////////////////
// PrefService::Preference

PrefService::Preference::Preference(const PrefService* service,
                                    const char* name,
                                    base::Value::Type type)
      : name_(name),
        type_(type),
        pref_service_(service) {
  DCHECK(name);
  DCHECK(service);
}

const std::string PrefService::Preference::name() const {
  return name_;
}

base::Value::Type PrefService::Preference::GetType() const {
  return type_;
}

const Value* PrefService::Preference::GetValue() const {
  const Value* result= pref_service_->GetPreferenceValue(name_);
  DCHECK(result) << "Must register pref before getting its value";
  return result;
}

const Value* PrefService::Preference::GetRecommendedValue() const {
  DCHECK(pref_service_->FindPreference(name_.c_str())) <<
      "Must register pref before getting its value";

  const Value* found_value = NULL;
  if (pref_value_store()->GetRecommendedValue(name_, type_, &found_value)) {
    DCHECK(found_value->IsType(type_));
    return found_value;
  }

  // The pref has no recommended value.
  return NULL;
}

bool PrefService::Preference::IsManaged() const {
  return pref_value_store()->PrefValueInManagedStore(name_.c_str());
}

bool PrefService::Preference::IsRecommended() const {
  return pref_value_store()->PrefValueFromRecommendedStore(name_.c_str());
}

bool PrefService::Preference::HasExtensionSetting() const {
  return pref_value_store()->PrefValueInExtensionStore(name_.c_str());
}

bool PrefService::Preference::HasUserSetting() const {
  return pref_value_store()->PrefValueInUserStore(name_.c_str());
}

bool PrefService::Preference::IsExtensionControlled() const {
  return pref_value_store()->PrefValueFromExtensionStore(name_.c_str());
}

bool PrefService::Preference::IsUserControlled() const {
  return pref_value_store()->PrefValueFromUserStore(name_.c_str());
}

bool PrefService::Preference::IsDefaultValue() const {
  return pref_value_store()->PrefValueFromDefaultStore(name_.c_str());
}

bool PrefService::Preference::IsUserModifiable() const {
  return pref_value_store()->PrefValueUserModifiable(name_.c_str());
}

bool PrefService::Preference::IsExtensionModifiable() const {
  return pref_value_store()->PrefValueExtensionModifiable(name_.c_str());
}

const base::Value* PrefService::GetPreferenceValue(
    const std::string& path) const {
  DCHECK(CalledOnValidThread());
  const base::Value::Type type = default_store_->GetType(path);
  if (type == Value::TYPE_NULL)
    return NULL;
  const Value* found_value = NULL;
  if (pref_value_store_->GetValue(path, type, &found_value)) {
    DCHECK(found_value->IsType(type));
    return found_value;
  }

  // Every registered preference has at least a default value.
  NOTREACHED() << "no valid value found for registered pref " << path;
  return NULL;
}