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 // This provides a way to access the application's current preferences.
      6 
      7 // Chromium settings and storage represent user-selected preferences and
      8 // information and MUST not be extracted, overwritten or modified except
      9 // through Chromium defined APIs.
     10 
     11 #ifndef BASE_PREFS_PREF_SERVICE_H_
     12 #define BASE_PREFS_PREF_SERVICE_H_
     13 
     14 #include <set>
     15 #include <string>
     16 
     17 #include "base/callback.h"
     18 #include "base/compiler_specific.h"
     19 #include "base/containers/hash_tables.h"
     20 #include "base/memory/ref_counted.h"
     21 #include "base/memory/scoped_ptr.h"
     22 #include "base/observer_list.h"
     23 #include "base/prefs/base_prefs_export.h"
     24 #include "base/prefs/persistent_pref_store.h"
     25 #include "base/threading/non_thread_safe.h"
     26 #include "base/values.h"
     27 
     28 class PrefNotifier;
     29 class PrefNotifierImpl;
     30 class PrefObserver;
     31 class PrefRegistry;
     32 class PrefValueStore;
     33 class PrefStore;
     34 
     35 namespace base {
     36 class FilePath;
     37 }
     38 
     39 namespace subtle {
     40 class PrefMemberBase;
     41 class ScopedUserPrefUpdateBase;
     42 }
     43 
     44 // Base class for PrefServices. You can use the base class to read and
     45 // interact with preferences, but not to register new preferences; for
     46 // that see e.g. PrefRegistrySimple.
     47 //
     48 // Settings and storage accessed through this class represent
     49 // user-selected preferences and information and MUST not be
     50 // extracted, overwritten or modified except through the defined APIs.
     51 class BASE_PREFS_EXPORT PrefService : public base::NonThreadSafe {
     52  public:
     53   enum PrefInitializationStatus {
     54     INITIALIZATION_STATUS_WAITING,
     55     INITIALIZATION_STATUS_SUCCESS,
     56     INITIALIZATION_STATUS_CREATED_NEW_PREF_STORE,
     57     INITIALIZATION_STATUS_ERROR
     58   };
     59 
     60   // A helper class to store all the information associated with a preference.
     61   class BASE_PREFS_EXPORT Preference {
     62    public:
     63     // The type of the preference is determined by the type with which it is
     64     // registered. This type needs to be a boolean, integer, double, string,
     65     // dictionary (a branch), or list.  You shouldn't need to construct this on
     66     // your own; use the PrefService::Register*Pref methods instead.
     67     Preference(const PrefService* service,
     68                const char* name,
     69                base::Value::Type type);
     70     ~Preference() {}
     71 
     72     // Returns the name of the Preference (i.e., the key, e.g.,
     73     // browser.window_placement).
     74     const std::string name() const;
     75 
     76     // Returns the registered type of the preference.
     77     base::Value::Type GetType() const;
     78 
     79     // Returns the value of the Preference, falling back to the registered
     80     // default value if no other has been set.
     81     const base::Value* GetValue() const;
     82 
     83     // Returns the value recommended by the admin, if any.
     84     const base::Value* GetRecommendedValue() const;
     85 
     86     // Returns true if the Preference is managed, i.e. set by an admin policy.
     87     // Since managed prefs have the highest priority, this also indicates
     88     // whether the pref is actually being controlled by the policy setting.
     89     bool IsManaged() const;
     90 
     91     // Returns true if the Preference is recommended, i.e. set by an admin
     92     // policy but the user is allowed to change it.
     93     bool IsRecommended() const;
     94 
     95     // Returns true if the Preference has a value set by an extension, even if
     96     // that value is being overridden by a higher-priority source.
     97     bool HasExtensionSetting() const;
     98 
     99     // Returns true if the Preference has a user setting, even if that value is
    100     // being overridden by a higher-priority source.
    101     bool HasUserSetting() const;
    102 
    103     // Returns true if the Preference value is currently being controlled by an
    104     // extension, and not by any higher-priority source.
    105     bool IsExtensionControlled() const;
    106 
    107     // Returns true if the Preference value is currently being controlled by a
    108     // user setting, and not by any higher-priority source.
    109     bool IsUserControlled() const;
    110 
    111     // Returns true if the Preference is currently using its default value,
    112     // and has not been set by any higher-priority source (even with the same
    113     // value).
    114     bool IsDefaultValue() const;
    115 
    116     // Returns true if the user can change the Preference value, which is the
    117     // case if no higher-priority source than the user store controls the
    118     // Preference.
    119     bool IsUserModifiable() const;
    120 
    121     // Returns true if an extension can change the Preference value, which is
    122     // the case if no higher-priority source than the extension store controls
    123     // the Preference.
    124     bool IsExtensionModifiable() const;
    125 
    126    private:
    127     friend class PrefService;
    128 
    129     PrefValueStore* pref_value_store() const {
    130       return pref_service_->pref_value_store_.get();
    131     }
    132 
    133     const std::string name_;
    134 
    135     const base::Value::Type type_;
    136 
    137     // Reference to the PrefService in which this pref was created.
    138     const PrefService* pref_service_;
    139   };
    140 
    141   // You may wish to use PrefServiceBuilder or one of its subclasses
    142   // for simplified construction.
    143   PrefService(
    144       PrefNotifierImpl* pref_notifier,
    145       PrefValueStore* pref_value_store,
    146       PersistentPrefStore* user_prefs,
    147       PrefRegistry* pref_registry,
    148       base::Callback<void(PersistentPrefStore::PrefReadError)>
    149           read_error_callback,
    150       bool async);
    151   virtual ~PrefService();
    152 
    153   // Reloads the data from file. This should only be called when the importer
    154   // is running during first run, and the main process may not change pref
    155   // values while the importer process is running. Returns true on success.
    156   bool ReloadPersistentPrefs();
    157 
    158   // Lands pending writes to disk. This should only be used if we need to save
    159   // immediately (basically, during shutdown).
    160   void CommitPendingWrite();
    161 
    162   // Returns true if the preference for the given preference name is available
    163   // and is managed.
    164   bool IsManagedPreference(const char* pref_name) const;
    165 
    166   // Returns |true| if a preference with the given name is available and its
    167   // value can be changed by the user.
    168   bool IsUserModifiablePreference(const char* pref_name) const;
    169 
    170   // Look up a preference.  Returns NULL if the preference is not
    171   // registered.
    172   const PrefService::Preference* FindPreference(const char* path) const;
    173 
    174   // If the path is valid and the value at the end of the path matches the type
    175   // specified, it will return the specified value.  Otherwise, the default
    176   // value (set when the pref was registered) will be returned.
    177   bool GetBoolean(const char* path) const;
    178   int GetInteger(const char* path) const;
    179   double GetDouble(const char* path) const;
    180   std::string GetString(const char* path) const;
    181   base::FilePath GetFilePath(const char* path) const;
    182 
    183   // Returns the branch if it exists, or the registered default value otherwise.
    184   // Note that |path| must point to a registered preference. In that case, these
    185   // functions will never return NULL.
    186   const base::DictionaryValue* GetDictionary(
    187       const char* path) const;
    188   const base::ListValue* GetList(const char* path) const;
    189 
    190   // Removes a user pref and restores the pref to its default value.
    191   void ClearPref(const char* path);
    192 
    193   // If the path is valid (i.e., registered), update the pref value in the user
    194   // prefs.
    195   // To set the value of dictionary or list values in the pref tree use
    196   // Set(), but to modify the value of a dictionary or list use either
    197   // ListPrefUpdate or DictionaryPrefUpdate from scoped_user_pref_update.h.
    198   void Set(const char* path, const base::Value& value);
    199   void SetBoolean(const char* path, bool value);
    200   void SetInteger(const char* path, int value);
    201   void SetDouble(const char* path, double value);
    202   void SetString(const char* path, const std::string& value);
    203   void SetFilePath(const char* path, const base::FilePath& value);
    204 
    205   // Int64 helper methods that actually store the given value as a string.
    206   // Note that if obtaining the named value via GetDictionary or GetList, the
    207   // Value type will be TYPE_STRING.
    208   void SetInt64(const char* path, int64 value);
    209   int64 GetInt64(const char* path) const;
    210 
    211   // As above, but for unsigned values.
    212   void SetUint64(const char* path, uint64 value);
    213   uint64 GetUint64(const char* path) const;
    214 
    215   // Returns the value of the given preference, from the user pref store. If
    216   // the preference is not set in the user pref store, returns NULL.
    217   const base::Value* GetUserPrefValue(const char* path) const;
    218 
    219   // Changes the default value for a preference. Takes ownership of |value|.
    220   //
    221   // Will cause a pref change notification to be fired if this causes
    222   // the effective value to change.
    223   void SetDefaultPrefValue(const char* path, base::Value* value);
    224 
    225   // Returns the default value of the given preference. |path| must point to a
    226   // registered preference. In that case, will never return NULL.
    227   const base::Value* GetDefaultPrefValue(const char* path) const;
    228 
    229   // Returns true if a value has been set for the specified path.
    230   // NOTE: this is NOT the same as FindPreference. In particular
    231   // FindPreference returns whether RegisterXXX has been invoked, where as
    232   // this checks if a value exists for the path.
    233   bool HasPrefPath(const char* path) const;
    234 
    235   // Returns a dictionary with effective preference values. The ownership
    236   // is passed to the caller.
    237   base::DictionaryValue* GetPreferenceValues() const;
    238 
    239   bool ReadOnly() const;
    240 
    241   PrefInitializationStatus GetInitializationStatus() const;
    242 
    243   // Tell our PrefValueStore to update itself to |command_line_store|.
    244   // Takes ownership of the store.
    245   virtual void UpdateCommandLinePrefStore(PrefStore* command_line_store);
    246 
    247   // We run the callback once, when initialization completes. The bool
    248   // parameter will be set to true for successful initialization,
    249   // false for unsuccessful.
    250   void AddPrefInitObserver(base::Callback<void(bool)> callback);
    251 
    252   // Returns the PrefRegistry object for this service. You should not
    253   // use this; the intent is for no registrations to take place after
    254   // PrefService has been constructed.
    255   PrefRegistry* DeprecatedGetPrefRegistry();
    256 
    257  protected:
    258   // Adds the registered preferences from the PrefRegistry instance
    259   // passed to us at construction time.
    260   void AddInitialPreferences();
    261 
    262   // Updates local caches for a preference registered at |path|. The
    263   // |default_value| must not be NULL as it determines the preference
    264   // value's type.  AddRegisteredPreference must not be called twice
    265   // for the same path.
    266   void AddRegisteredPreference(const char* path,
    267                                base::Value* default_value);
    268 
    269   // The PrefNotifier handles registering and notifying preference observers.
    270   // It is created and owned by this PrefService. Subclasses may access it for
    271   // unit testing.
    272   scoped_ptr<PrefNotifierImpl> pref_notifier_;
    273 
    274   // The PrefValueStore provides prioritized preference values. It is owned by
    275   // this PrefService. Subclasses may access it for unit testing.
    276   scoped_ptr<PrefValueStore> pref_value_store_;
    277 
    278   scoped_refptr<PrefRegistry> pref_registry_;
    279 
    280   // Pref Stores and profile that we passed to the PrefValueStore.
    281   scoped_refptr<PersistentPrefStore> user_pref_store_;
    282 
    283   // Callback to call when a read error occurs.
    284   base::Callback<void(PersistentPrefStore::PrefReadError)> read_error_callback_;
    285 
    286  private:
    287   // Hash map expected to be fastest here since it minimises expensive
    288   // string comparisons. Order is unimportant, and deletions are rare.
    289   // Confirmed on Android where this speeded Chrome startup by roughly 50ms
    290   // vs. std::map, and by roughly 180ms vs. std::set of Preference pointers.
    291   typedef base::hash_map<std::string, Preference> PreferenceMap;
    292 
    293   // Give access to ReportUserPrefChanged() and GetMutableUserPref().
    294   friend class subtle::ScopedUserPrefUpdateBase;
    295 
    296   // Registration of pref change observers must be done using the
    297   // PrefChangeRegistrar, which is declared as a friend here to grant it
    298   // access to the otherwise protected members Add/RemovePrefObserver.
    299   // PrefMember registers for preferences changes notification directly to
    300   // avoid the storage overhead of the registrar, so its base class must be
    301   // declared as a friend, too.
    302   friend class PrefChangeRegistrar;
    303   friend class subtle::PrefMemberBase;
    304 
    305   // These are protected so they can only be accessed by the friend
    306   // classes listed above.
    307   //
    308   // If the pref at the given path changes, we call the observer's
    309   // OnPreferenceChanged method. Note that observers should not call
    310   // these methods directly but rather use a PrefChangeRegistrar to
    311   // make sure the observer gets cleaned up properly.
    312   //
    313   // Virtual for testing.
    314   virtual void AddPrefObserver(const char* path, PrefObserver* obs);
    315   virtual void RemovePrefObserver(const char* path, PrefObserver* obs);
    316 
    317   // Sends notification of a changed preference. This needs to be called by
    318   // a ScopedUserPrefUpdate if a DictionaryValue or ListValue is changed.
    319   void ReportUserPrefChanged(const std::string& key);
    320 
    321   // Sets the value for this pref path in the user pref store and informs the
    322   // PrefNotifier of the change.
    323   void SetUserPrefValue(const char* path, base::Value* new_value);
    324 
    325   // Load preferences from storage, attempting to diagnose and handle errors.
    326   // This should only be called from the constructor.
    327   void InitFromStorage(bool async);
    328 
    329   // Used to set the value of dictionary or list values in the user pref store.
    330   // This will create a dictionary or list if one does not exist in the user
    331   // pref store. This method returns NULL only if you're requesting an
    332   // unregistered pref or a non-dict/non-list pref.
    333   // |type| may only be Values::TYPE_DICTIONARY or Values::TYPE_LIST and
    334   // |path| must point to a registered preference of type |type|.
    335   // Ownership of the returned value remains at the user pref store.
    336   base::Value* GetMutableUserPref(const char* path,
    337                                   base::Value::Type type);
    338 
    339   // GetPreferenceValue is the equivalent of FindPreference(path)->GetValue(),
    340   // it has been added for performance. If is faster because it does
    341   // not need to find or create a Preference object to get the
    342   // value (GetValue() calls back though the preference service to
    343   // actually get the value.).
    344   const base::Value* GetPreferenceValue(const std::string& path) const;
    345 
    346   // Local cache of registered Preference objects. The pref_registry_
    347   // is authoritative with respect to what the types and default values
    348   // of registered preferences are.
    349   mutable PreferenceMap prefs_map_;
    350 
    351   DISALLOW_COPY_AND_ASSIGN(PrefService);
    352 };
    353 
    354 #endif  // BASE_PREFS_PREF_SERVICE_H_
    355