pref_service.h revision 3345a6884c488ff3a535c2c9acdd33d74b37e311
1// Copyright (c) 2010 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#ifndef CHROME_BROWSER_PREFS_PREF_SERVICE_H_
8#define CHROME_BROWSER_PREFS_PREF_SERVICE_H_
9#pragma once
10
11#include <set>
12#include <string>
13
14#include "base/non_thread_safe.h"
15#include "base/scoped_ptr.h"
16#include "base/values.h"
17#include "chrome/browser/prefs/pref_value_store.h"
18#include "chrome/common/pref_store.h"
19
20class FilePath;
21class NotificationObserver;
22class PrefChangeObserver;
23class PrefNotifier;
24class Profile;
25
26namespace subtle {
27  class PrefMemberBase;
28};
29
30class PrefService : public NonThreadSafe {
31 public:
32  // A helper class to store all the information associated with a preference.
33  class Preference {
34   public:
35
36    // The type of the preference is determined by the type with which it is
37    // registered. This type needs to be a boolean, integer, real, string,
38    // dictionary (a branch), or list.  You shouldn't need to construct this on
39    // your own; use the PrefService::Register*Pref methods instead.
40    Preference(const PrefService* service,
41               const char* name);
42    ~Preference() {}
43
44    // Returns the name of the Preference (i.e., the key, e.g.,
45    // browser.window_placement).
46    const std::string name() const { return name_; }
47
48    // Returns the registered type of the preference.
49    Value::ValueType GetType() const;
50
51    // Returns the value of the Preference, falling back to the registered
52    // default value if no other has been set.
53    const Value* GetValue() const;
54
55    // Returns true if the Preference is managed, i.e. set by an admin policy.
56    // Since managed prefs have the highest priority, this also indicates
57    // whether the pref is actually being controlled by the policy setting.
58    bool IsManaged() const;
59
60    // Returns true if the Preference has a value set by an extension, even if
61    // that value is being overridden by a higher-priority source.
62    bool HasExtensionSetting() const;
63
64    // Returns true if the Preference has a user setting, even if that value is
65    // being overridden by a higher-priority source.
66    bool HasUserSetting() const;
67
68    // Returns true if the Preference value is currently being controlled by an
69    // extension, and not by any higher-priority source.
70    bool IsExtensionControlled() const;
71
72    // Returns true if the Preference value is currently being controlled by a
73    // user setting, and not by any higher-priority source.
74    bool IsUserControlled() const;
75
76    // Returns true if the Preference is currently using its default value,
77    // and has not been set by any higher-priority source (even with the same
78    // value).
79    bool IsDefaultValue() const;
80
81    // Returns true if the user can change the Preference value, which is the
82    // case if no higher-priority source than the user store controls the
83    // Preference.
84    bool IsUserModifiable() const;
85
86   private:
87    friend class PrefService;
88
89    std::string name_;
90
91    // Reference to the PrefService in which this pref was created.
92    const PrefService* pref_service_;
93
94    DISALLOW_COPY_AND_ASSIGN(Preference);
95  };
96
97  // Factory method that creates a new instance of a PrefService with
98  // a PrefValueStore containing all platform-applicable PrefStores.
99  // The |pref_filename| points to the user preference file. The |profile| is
100  // the one to which these preferences apply; it may be NULL if we're dealing
101  // with the local state. This is the usual way to create a new PrefService.
102  static PrefService* CreatePrefService(const FilePath& pref_filename,
103                                        Profile* profile);
104
105  // Convenience factory method for use in unit tests. Creates a new
106  // PrefService that uses a PrefValueStore with user preferences at the given
107  // |pref_filename|, a default PrefStore, and no other PrefStores (i.e., no
108  // other types of preferences).
109  static PrefService* CreateUserPrefService(const FilePath& pref_filename);
110
111  // This constructor is primarily used by tests. The |pref_value_store|
112  // provides preference values.
113  explicit PrefService(PrefValueStore* pref_value_store);
114
115  virtual ~PrefService();
116
117  // Reloads the data from file. This should only be called when the importer
118  // is running during first run, and the main process may not change pref
119  // values while the importer process is running. Returns true on success.
120  bool ReloadPersistentPrefs();
121
122  // Returns true if the preference for the given preference name is available
123  // and is managed.
124  bool IsManagedPreference(const char* pref_name) const;
125
126  // Writes the data to disk. The return value only reflects whether
127  // serialization was successful; we don't know whether the data actually made
128  // it on disk (since it's on a different thread).  This should only be used if
129  // we need to save immediately (basically, during shutdown).  Otherwise, you
130  // should use ScheduleSavePersistentPrefs.
131  bool SavePersistentPrefs();
132
133  // Serializes the data and schedules save using ImportantFileWriter.
134  void ScheduleSavePersistentPrefs();
135
136  // Make the PrefService aware of a pref.
137  void RegisterBooleanPref(const char* path, bool default_value);
138  void RegisterIntegerPref(const char* path, int default_value);
139  void RegisterRealPref(const char* path, double default_value);
140  void RegisterStringPref(const char* path, const std::string& default_value);
141  void RegisterFilePathPref(const char* path, const FilePath& default_value);
142  void RegisterListPref(const char* path);
143  void RegisterDictionaryPref(const char* path);
144
145  // These varients use a default value from the locale dll instead.
146  void RegisterLocalizedBooleanPref(const char* path,
147                                    int locale_default_message_id);
148  void RegisterLocalizedIntegerPref(const char* path,
149                                    int locale_default_message_id);
150  void RegisterLocalizedRealPref(const char* path,
151                                 int locale_default_message_id);
152  void RegisterLocalizedStringPref(const char* path,
153                                   int locale_default_message_id);
154
155  // If the path is valid and the value at the end of the path matches the type
156  // specified, it will return the specified value.  Otherwise, the default
157  // value (set when the pref was registered) will be returned.
158  bool GetBoolean(const char* path) const;
159  int GetInteger(const char* path) const;
160  double GetReal(const char* path) const;
161  std::string GetString(const char* path) const;
162  FilePath GetFilePath(const char* path) const;
163
164  // Returns the branch if it exists.  If it's not a branch or the branch does
165  // not exist, returns NULL.
166  const DictionaryValue* GetDictionary(const char* path) const;
167  const ListValue* GetList(const char* path) const;
168
169  // Removes a user pref and restores the pref to its default value.
170  void ClearPref(const char* path);
171
172  // If the path is valid (i.e., registered), update the pref value in the user
173  // prefs. Seting a null value on a preference of List or Dictionary type is
174  // equivalent to removing the user value for that preference, allowing the
175  // default value to take effect unless another value takes precedence.
176  void Set(const char* path, const Value& value);
177  void SetBoolean(const char* path, bool value);
178  void SetInteger(const char* path, int value);
179  void SetReal(const char* path, double value);
180  void SetString(const char* path, const std::string& value);
181  void SetFilePath(const char* path, const FilePath& value);
182
183  // Int64 helper methods that actually store the given value as a string.
184  // Note that if obtaining the named value via GetDictionary or GetList, the
185  // Value type will be TYPE_STRING.
186  void SetInt64(const char* path, int64 value);
187  int64 GetInt64(const char* path) const;
188  void RegisterInt64Pref(const char* path, int64 default_value);
189
190  // Used to set the value of dictionary or list values in the pref tree.  This
191  // will create a dictionary or list if one does not exist in the pref tree.
192  // This method returns NULL only if you're requesting an unregistered pref or
193  // a non-dict/non-list pref.
194  // WARNING: Changes to the dictionary or list will not automatically notify
195  // pref observers.
196  // Use a ScopedPrefUpdate to update observers on changes.
197  DictionaryValue* GetMutableDictionary(const char* path);
198  ListValue* GetMutableList(const char* path);
199
200  // Returns true if a value has been set for the specified path.
201  // NOTE: this is NOT the same as FindPreference. In particular
202  // FindPreference returns whether RegisterXXX has been invoked, where as
203  // this checks if a value exists for the path.
204  bool HasPrefPath(const char* path) const;
205
206  class PreferencePathComparator {
207   public:
208    bool operator() (Preference* lhs, Preference* rhs) const {
209      return lhs->name() < rhs->name();
210    }
211  };
212  typedef std::set<Preference*, PreferencePathComparator> PreferenceSet;
213  const PreferenceSet& preference_set() const { return prefs_; }
214
215  // A helper method to quickly look up a preference.  Returns NULL if the
216  // preference is not registered.
217  const Preference* FindPreference(const char* pref_name) const;
218
219  bool read_only() const { return pref_value_store_->ReadOnly(); }
220
221  PrefNotifier* pref_notifier() const { return pref_notifier_.get(); }
222
223  PrefValueStore* pref_value_store() const { return pref_value_store_.get(); }
224
225 protected:
226  // The PrefNotifier handles registering and notifying preference observers.
227  // It is created and owned by this PrefService. Subclasses may access it for
228  // unit testing.
229  scoped_ptr<PrefNotifier> pref_notifier_;
230
231 private:
232  // Registration of pref change observers must be done using the
233  // PrefChangeRegistrar, which is declared as a friend here to grant it
234  // access to the otherwise protected members Add/RemovePrefObserver.
235  // PrefMember registers for preferences changes notification directly to
236  // avoid the storage overhead of the registrar, so its base class must be
237  // declared as a friend, too.
238  friend class PrefChangeRegistrar;
239  friend class subtle::PrefMemberBase;
240
241  // If the pref at the given path changes, we call the observer's Observe
242  // method with PREF_CHANGED. Note that observers should not call these methods
243  // directly but rather use a PrefChangeRegistrar to make sure the observer
244  // gets cleaned up properly.
245  virtual void AddPrefObserver(const char* path, NotificationObserver* obs);
246  virtual void RemovePrefObserver(const char* path, NotificationObserver* obs);
247
248  // Add a preference to the PreferenceMap.  If the pref already exists, return
249  // false.  This method takes ownership of |default_value|.
250  void RegisterPreference(const char* path, Value* default_value);
251
252  // Returns a copy of the current pref value.  The caller is responsible for
253  // deleting the returned object.
254  Value* GetPrefCopy(const char* pref_name);
255
256  // Sets the value for this pref path in the user pref store and informs the
257  // PrefNotifier of the change.
258  void SetUserPrefValue(const char* path, Value* new_value);
259
260  // Load from disk.  Returns a non-zero error code on failure.
261  PrefStore::PrefReadError LoadPersistentPrefs();
262
263  // Load preferences from storage, attempting to diagnose and handle errors.
264  // This should only be called from the constructor.
265  void InitFromStorage();
266
267  // The PrefValueStore provides prioritized preference values. It is created
268  // and owned by this PrefService. Subclasses may access it for unit testing.
269  scoped_refptr<PrefValueStore> pref_value_store_;
270
271  // A set of all the registered Preference objects.
272  PreferenceSet prefs_;
273
274  DISALLOW_COPY_AND_ASSIGN(PrefService);
275};
276
277#endif  // CHROME_BROWSER_PREFS_PREF_SERVICE_H_
278