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"],
15 use: ["config", "messages", "template"]
18 var Prefs = Module("prefs", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]), {
19 ORIGINAL: "extensions.dactyl.original.",
20 RESTORE: "extensions.dactyl.restore.",
21 SAVED: "extensions.dactyl.saved.",
24 init: function init(branch, defaults) {
25 this._prefContexts = [];
27 this.branch = services.pref[defaults ? "getDefaultBranch" : "getBranch"](branch || "");
28 this.branch instanceof Ci.nsIPrefBranch2;
30 this.defaults = defaults ? this : this.constructor(branch, true);
32 this.branches = memoize({
34 get original() this.constructor(this.ORIGINAL + this.root),
35 get restore() this.constructor(this.RESTORE + this.root),
36 get saved() this.constructor(this.SAVED + this.root),
45 cleanup: function cleanup(reason) {
46 if (this.defaults != this)
47 this.defaults.cleanup();
51 this.branch.removeObserver("", this);
52 this.observe.unregister();
57 if (~["uninstall", "disable"].indexOf(reason)) {
58 for (let name in values(this.branches.saved.getNames()))
59 this.safeReset(name, null, true);
61 this.branches.original.resetBranch();
62 this.branches.saved.resetBranch();
65 if (reason == "uninstall" && this == prefs)
66 localPrefs.resetBranch();
71 * Returns the full name of this object's preference branch.
73 get root() this.branch.root,
76 * Returns a new Prefs instance for the sub-branch *branch* of this
79 * @param {string} branch The branch to branch to.
82 Branch: function Branch(branch) Prefs(this.root + branch),
86 "nsPref:changed": function (subject, data) {
87 let observers = this._observers[data];
89 let value = this.get(data, false);
90 this._observers[data] = observers.filter(function (callback) {
93 util.trapErrors(callback.get(), null, value);
101 * Adds a new preference observer for the given preference.
103 * @param {string} pref The preference to observe.
104 * @param {function(object)} callback The callback, called with the
105 * new value of the preference whenever it changes.
107 watch: function watch(pref, callback, strong) {
109 util.addObserver(this);
110 this.branch.addObserver("", this, false);
113 if (!this._observers[pref])
114 this._observers[pref] = [];
115 this._observers[pref].push(!strong ? Cu.getWeakReference(callback) : { get: function () callback });
119 * Lists all preferences matching *filter* or only those with changed
120 * values if *onlyNonDefault* is specified.
122 * @param {boolean} onlyNonDefault Limit the list to prefs with a
124 * @param {string} filter The list filter. A null filter lists all
128 list: function list(onlyNonDefault, filter) {
132 let prefArray = this.getNames();
135 for (let [, pref] in Iterator(prefArray)) {
136 let userValue = services.pref.prefHasUserValue(pref);
137 if (onlyNonDefault && !userValue || pref.indexOf(filter) == -1)
140 let value = this.get(pref);
143 isDefault: !userValue,
144 default: this.defaults.get(pref, null),
145 value: <>={template.highlight(value, true, 100)}</>,
147 pre: "\u00a0\u00a0" // Unicode nonbreaking space.
154 return template.options(_("pref.hostPreferences", config.host), prefs.call(this));
158 * Returns the value of a preference.
160 * @param {string} name The preference name.
161 * @param {value} defaultValue The value to return if the preference
164 get: function get(name, defaultValue) {
165 if (defaultValue == null)
168 let type = this.branch.getPrefType(name);
171 case Ci.nsIPrefBranch.PREF_STRING:
172 let value = this.branch.getComplexValue(name, Ci.nsISupportsString).data;
173 // try in case it's a localized string (will throw an exception if not)
174 if (!this.branch.prefIsLocked(name) && !this.branch.prefHasUserValue(name) &&
175 RegExp("chrome://.+/locale/.+\\.properties").test(value))
176 value = this.branch.getComplexValue(name, Ci.nsIPrefLocalizedString).data;
178 case Ci.nsIPrefBranch.PREF_INT:
179 return this.branch.getIntPref(name);
180 case Ci.nsIPrefBranch.PREF_BOOL:
181 return this.branch.getBoolPref(name);
191 getDefault: deprecated("Prefs#defaults.get", function getDefault(name, defaultValue) this.defaults.get(name, defaultValue)),
194 * Returns the names of all preferences.
196 * @param {string} branch The branch in which to search preferences.
199 getNames: function getNames(branch) this.branch.getChildList(branch || "", { value: 0 }),
201 _checkSafe: function _checkSafe(name, message, value) {
202 let curval = this.get(name, null);
204 if (this.branches.original.get(name) == null)
205 this.branches.original.set(name, curval, true);
207 if (arguments.length > 2 && curval === value)
210 let defval = this.defaults.get(name, null);
211 let saved = this.branches.saved.get(name);
213 if (saved == null && curval != defval || saved != null && curval != saved) {
214 let msg = _("pref.safeSet.warnChanged", name);
216 msg = template.linkifyHelp(msg + " " + message);
217 util.dactyl.warn(msg);
222 * Resets the preference *name* to *value* but warns the user if the value
223 * is changed from its default.
225 * @param {string} name The preference name.
226 * @param {value} value The new preference value.
227 * @param {boolean} silent Ignore errors.
229 safeReset: function safeReset(name, message, silent) {
230 this._checkSafe(name, message);
231 this.set(name, this.branches.original.get(name), silent);
232 this.branches.original.reset(name);
233 this.branches.saved.reset(name);
237 * Sets the preference *name* to *value* but warns the user if the value is
238 * changed from its default.
240 * @param {string} name The preference name.
241 * @param {value} value The new preference value.
243 safeSet: function safeSet(name, value, message, skipSave) {
244 this._checkSafe(name, message, value);
245 this.set(name, value);
246 this.branches.saved[skipSave ? "reset" : "set"](name, value);
250 * Sets the preference *name* to *value*.
252 * @param {string} name The preference name.
253 * @param {value} value The new preference value.
254 * @param {boolean} silent Ignore errors.
256 set: function set(name, value, silent) {
257 if (this._prefContexts.length)
258 this._prefContexts[this._prefContexts.length - 1][name] = this.get(name, null);
260 function assertType(needType)
261 util.assert(type === Ci.nsIPrefBranch.PREF_INVALID || type === needType,
262 type === Ci.nsIPrefBranch.PREF_INT
263 ? /*L*/"E521: Number required after =: " + name + "=" + value
264 : /*L*/"E474: Invalid argument: " + name + "=" + value);
266 let type = this.branch.getPrefType(name);
268 switch (typeof value) {
270 assertType(Ci.nsIPrefBranch.PREF_STRING);
272 this.branch.setComplexValue(name, Ci.nsISupportsString, services.String(value));
275 assertType(Ci.nsIPrefBranch.PREF_INT);
277 this.branch.setIntPref(name, value);
280 assertType(Ci.nsIPrefBranch.PREF_BOOL);
282 this.branch.setBoolPref(name, value);
285 if (value == null && this != this.defaults)
288 throw FailedAssertion("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")");
291 catch (e if silent) {}
296 * Saves the current value of a preference to be restored at next
299 * @param {string} name The preference to save.
301 save: function save(name) {
302 let val = this.get(name);
303 this.set(this.RESTORE + name, val);
304 this.safeSet(name, val);
308 * Restores saved preferences in the given branch.
310 * @param {string} branch The branch from which to restore
311 * preferences. @optional
313 restore: function restore(branch) {
314 this.getNames(this.RESTORE + (branch || "")).forEach(function (pref) {
315 this.safeSet(pref.substr(this.RESTORE.length), this.get(pref), null, true);
321 * Resets the preference *name* to its default value.
323 * @param {string} name The preference name.
325 reset: function reset(name) {
327 this.branch.clearUserPref(name);
329 catch (e) {} // ignore - thrown if not a user set value
333 * Resets the preference branch *branch* to its default value.
335 * @param {string} branch The preference name. @optional
337 resetBranch: function resetBranch(branch) {
338 this.getNames(branch).forEach(this.closure.reset);
342 * Toggles the value of the boolean preference *name*.
344 * @param {string} name The preference name.
346 toggle: function toggle(name) {
347 util.assert(this.branch.getPrefType(name) === Ci.nsIPrefBranch.PREF_BOOL,
348 _("error.trailingCharacters", name + "!"));
349 this.set(name, !this.get(name));
353 * Pushes a new preference context onto the context stack.
357 pushContext: function pushContext() {
358 this._prefContexts.push({});
362 * Pops the top preference context from the stack.
366 popContext: function popContext() {
367 for (let [k, v] in Iterator(this._prefContexts.pop()))
372 * Executes *func* with a new preference context. When *func* returns, the
373 * context is popped and any preferences set via {@link #setPref} or
374 * {@link #invertPref} are restored to their previous values.
376 * @param {function} func The function to call.
377 * @param {Object} func The 'this' object with which to call *func*
381 withContext: function withContext(func, self) {
384 return func.call(self);
392 completion: function init_completion(dactyl, modules) {
393 modules.completion.preference = function preference(context) {
394 context.anchored = false;
395 context.title = [config.host + " Preference", "Value"];
396 context.keys = { text: function (item) item, description: function (item) prefs.get(item) };
397 context.completions = prefs.getNames();
400 javascript: function init_javascript(dactyl, modules) {
401 modules.JavaScript.setCompleter([this.get, this.safeSet, this.set, this.reset, this.toggle],
402 [function (context) (context.anchored=false, this.getNames().map(function (pref) [pref, ""]))]);
406 var localPrefs = Prefs("extensions.dactyl.");
407 defineModule.modules.push(localPrefs);
411 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
413 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: