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