1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k@gmail.com>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
11 Components.utils.import("resource://dactyl/bootstrap.jsm");
12 defineModule("prefs", {
13 exports: ["Prefs", "localPrefs", "prefs"],
14 require: ["services", "util"]
17 this.lazyRequire("messages", ["_"]);
19 var Prefs = Module("prefs", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]), {
20 ORIGINAL: "extensions.dactyl.original.",
21 RESTORE: "extensions.dactyl.restore.",
22 SAVED: "extensions.dactyl.saved.",
25 init: function init(branch, defaults) {
26 this._prefContexts = [];
28 this.branch = services.pref[defaults ? "getDefaultBranch" : "getBranch"](branch || "");
29 this.branch instanceof Ci.nsIPrefBranch2;
31 this.defaults = defaults ? this : this.constructor(branch, true);
33 this.branches = memoize({
35 get original() this.constructor(this.ORIGINAL + this.root),
36 get restore() this.constructor(this.RESTORE + this.root),
37 get saved() this.constructor(this.SAVED + this.root),
46 cleanup: function cleanup(reason) {
47 if (this.defaults != this)
48 this.defaults.cleanup(reason);
52 this.branch.removeObserver("", this);
53 this.observe.unregister();
58 if (~["uninstall", "disable"].indexOf(reason)) {
59 for (let name in values(this.branches.saved.getNames()))
60 this.safeReset(name, null, true);
62 this.branches.original.resetBranch();
63 this.branches.saved.resetBranch();
66 if (reason == "uninstall")
67 localPrefs.resetBranch();
72 * Returns the full name of this object's preference branch.
74 get root() this.branch.root,
77 * Returns a new Prefs instance for the sub-branch *branch* of this
80 * @param {string} branch The branch to branch to.
83 Branch: function Branch(branch) Prefs(this.root + branch),
87 "nsPref:changed": function (subject, data) {
88 let observers = this._observers[data];
90 let value = this.get(data, false);
91 this._observers[data] = observers.filter(function (callback) {
94 util.trapErrors(callback.get(), null, value);
102 * Adds a new preference observer for the given preference.
104 * @param {string} pref The preference to observe.
105 * @param {function(object)} callback The callback, called with the
106 * new value of the preference whenever it changes.
108 watch: function watch(pref, callback, strong) {
110 util.addObserver(this);
111 this.branch.addObserver("", this, false);
114 if (!this._observers[pref])
115 this._observers[pref] = [];
116 this._observers[pref].push(!strong ? util.weakReference(callback) : { get: function () callback });
120 * Lists all preferences matching *filter* or only those with changed
121 * values if *onlyNonDefault* is specified.
123 * @param {boolean} onlyNonDefault Limit the list to prefs with a
125 * @param {string} filter The list filter. A null filter lists all
129 list: function list(onlyNonDefault, filter) {
133 let prefArray = this.getNames();
136 for (let [, pref] in Iterator(prefArray)) {
137 let userValue = services.pref.prefHasUserValue(pref);
138 if (onlyNonDefault && !userValue || pref.indexOf(filter) == -1)
141 let value = this.get(pref);
144 isDefault: !userValue,
145 default: this.defaults.get(pref, null),
146 value: <>={template.highlight(value, true, 100)}</>,
148 pre: "\u00a0\u00a0" // Unicode nonbreaking space.
155 return template.options(_("pref.hostPreferences", config.host), prefs.call(this));
159 * Returns the value of a preference.
161 * @param {string} name The preference name.
162 * @param {value} defaultValue The value to return if the preference
165 get: function get(name, defaultValue) {
166 if (defaultValue == null)
169 let type = this.branch.getPrefType(name);
172 case Ci.nsIPrefBranch.PREF_STRING:
173 let value = this.branch.getComplexValue(name, Ci.nsISupportsString).data;
174 // try in case it's a localized string (will throw an exception if not)
175 if (!this.branch.prefIsLocked(name) && !this.branch.prefHasUserValue(name) &&
176 RegExp("chrome://.+/locale/.+\\.properties").test(value))
177 value = this.branch.getComplexValue(name, Ci.nsIPrefLocalizedString).data;
179 case Ci.nsIPrefBranch.PREF_INT:
180 return this.branch.getIntPref(name);
181 case Ci.nsIPrefBranch.PREF_BOOL:
182 return this.branch.getBoolPref(name);
192 getDefault: deprecated("Prefs#defaults.get", function getDefault(name, defaultValue) this.defaults.get(name, defaultValue)),
195 * Returns the names of all preferences.
197 * @param {string} branch The branch in which to search preferences.
200 getNames: function getNames(branch) this.branch.getChildList(branch || "", { value: 0 }),
203 * Returns true if the current branch has the given preference.
205 * @param {string} name The preference name.
208 has: function get(name) this.branch.getPrefType(name) != 0,
210 _checkSafe: function _checkSafe(name, message, value) {
211 let curval = this.get(name, null);
213 if (this.branches.original.get(name) == null && !this.branches.saved.has(name))
214 this.branches.original.set(name, curval, true);
216 if (arguments.length > 2 && curval === value)
219 let defval = this.defaults.get(name, null);
220 let saved = this.branches.saved.get(name);
222 if (saved == null && curval != defval || saved != null && curval != saved) {
223 let msg = _("pref.safeSet.warnChanged", name);
225 msg = template.linkifyHelp(msg + " " + message);
226 util.dactyl.warn(msg);
231 * Resets the preference *name* to *value* but warns the user if the value
232 * is changed from its default.
234 * @param {string} name The preference name.
235 * @param {value} value The new preference value.
236 * @param {boolean} silent Ignore errors.
238 safeReset: function safeReset(name, message, silent) {
239 this._checkSafe(name, message);
240 this.set(name, this.branches.original.get(name), silent);
241 this.branches.original.reset(name);
242 this.branches.saved.reset(name);
246 * Sets the preference *name* to *value* but warns the user if the value is
247 * changed from its default.
249 * @param {string} name The preference name.
250 * @param {value} value The new preference value.
252 safeSet: function safeSet(name, value, message, skipSave) {
253 this._checkSafe(name, message, value);
254 this.set(name, value);
255 this.branches.saved[skipSave ? "reset" : "set"](name, value);
259 * Sets the preference *name* to *value*.
261 * @param {string} name The preference name.
262 * @param {value} value The new preference value.
263 * @param {boolean} silent Ignore errors.
265 set: function set(name, value, silent) {
266 if (this._prefContexts.length)
267 this._prefContexts[this._prefContexts.length - 1][name] = this.get(name, null);
269 function assertType(needType)
270 util.assert(type === Ci.nsIPrefBranch.PREF_INVALID || type === needType,
271 type === Ci.nsIPrefBranch.PREF_INT
272 ? /*L*/"E521: Number required after =: " + name + "=" + value
273 : /*L*/"E474: Invalid argument: " + name + "=" + value);
275 let type = this.branch.getPrefType(name);
277 switch (typeof value) {
279 assertType(Ci.nsIPrefBranch.PREF_STRING);
281 this.branch.setComplexValue(name, Ci.nsISupportsString, services.String(value));
284 assertType(Ci.nsIPrefBranch.PREF_INT);
286 this.branch.setIntPref(name, value);
289 assertType(Ci.nsIPrefBranch.PREF_BOOL);
291 this.branch.setBoolPref(name, value);
294 if (value == null && this != this.defaults)
297 throw FailedAssertion("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")");
300 catch (e if silent) {}
305 * Saves the current value of a preference to be restored at next
308 * @param {string} name The preference to save.
310 save: function save(name) {
311 let val = this.get(name);
312 this.set(this.RESTORE + name, val);
313 this.safeSet(name, val);
317 * Restores saved preferences in the given branch.
319 * @param {string} branch The branch from which to restore
320 * preferences. @optional
322 restore: function restore(branch) {
323 this.getNames(this.RESTORE + (branch || "")).forEach(function (pref) {
324 this.safeSet(pref.substr(this.RESTORE.length), this.get(pref), null, true);
330 * Resets the preference *name* to its default value.
332 * @param {string} name The preference name.
334 reset: function reset(name) {
336 this.branch.clearUserPref(name);
338 catch (e) {} // ignore - thrown if not a user set value
342 * Resets the preference branch *branch* to its default value.
344 * @param {string} branch The preference name. @optional
346 resetBranch: function resetBranch(branch) {
347 this.getNames(branch).forEach(this.closure.reset);
351 * Toggles the value of the boolean preference *name*.
353 * @param {string} name The preference name.
355 toggle: function toggle(name) {
356 util.assert(this.branch.getPrefType(name) === Ci.nsIPrefBranch.PREF_BOOL,
357 _("error.trailingCharacters", name + "!"));
358 this.set(name, !this.get(name));
362 * Pushes a new preference context onto the context stack.
366 pushContext: function pushContext() {
367 this._prefContexts.push({});
371 * Pops the top preference context from the stack.
375 popContext: function popContext() {
376 for (let [k, v] in Iterator(this._prefContexts.pop()))
381 * Executes *func* with a new preference context. When *func* returns, the
382 * context is popped and any preferences set via {@link #setPref} or
383 * {@link #invertPref} are restored to their previous values.
385 * @param {function} func The function to call.
386 * @param {Object} func The 'this' object with which to call *func*
390 withContext: function withContext(func, self) {
393 return func.call(self);
401 completion: function init_completion(dactyl, modules) {
402 modules.completion.preference = function preference(context) {
403 context.anchored = false;
404 context.title = [config.host + " Preference", "Value"];
405 context.keys = { text: function (item) item, description: function (item) prefs.get(item) };
406 context.completions = prefs.getNames();
409 javascript: function init_javascript(dactyl, modules) {
410 modules.JavaScript.setCompleter([this.get, this.safeSet, this.set, this.reset, this.toggle],
411 [function (context) (context.anchored=false, this.getNames().map(function (pref) [pref, ""]))]);
415 var localPrefs = Prefs("extensions.dactyl.");
416 defineModule.modules.push(localPrefs);
420 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
422 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: