3 // NOTE: You *must* also include this line in any test that uses this file:
4 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
6 var prefService = Components.classes["@mozilla.org/preferences-service;1"]
7 .getService(Components.interfaces.nsIPrefService);
9 function determinePrefKind(branch, prefName) {
10 switch (branch.getPrefType(prefName)) {
11 case branch.PREF_STRING: return "CharPref";
12 case branch.PREF_INT: return "IntPref";
13 case branch.PREF_BOOL: return "BoolPref";
14 default: /* PREF_INVALID */ return "ComplexValue";
18 function memoize(fn, obj) {
19 var cache = {}, sep = '___',
20 join = Array.prototype.join;
22 var key = join.call(arguments, sep);
24 cache[key] = fn.apply(obj, arguments);
29 var makeAccessor = memoize(function(pref) {
30 var splat = pref.split('.'),
31 basePref = splat.pop(),
35 branch = prefService.getBranch(splat.join('.') + '.')
37 alert("Calling prefService.getBranch failed: " +
38 "did you read the NOTE in mozprefs.js?");
42 kind = determinePrefKind(branch, basePref);
44 return function(value) {
45 var oldValue = branch['get' + kind](basePref);
46 if (arguments.length > 0)
47 branch['set' + kind](basePref, value);
52 /* function pref(name[, value[, fn[, obj]]])
53 * -----------------------------------------
56 * 1. Get the value of the dom.disable_open_during_load preference:
58 * pref('dom.disable_open_during_load')
60 * 2. Set the preference to true, returning the old value:
62 * var oldValue = pref('dom.disable_open_during_load', true);
64 * 3. Set the value of the preference to true just for the duration
65 * of the specified function's execution:
67 * pref('dom.disable_open_during_load', true, function() {
68 * window.open(this.getUrl()); // fails if still loading
69 * }, this); // for convenience, allow binding
71 * Rationale: Unless a great deal of care is taken to catch all
72 * exceptions and restore original preference values,
73 * manually setting & restoring preferences can lead
74 * to unpredictable test behavior. The try-finally
75 * block below eliminates that risk.
77 function pref(name, /*optional:*/ value, fn, obj) {
78 var acc = makeAccessor(name);
79 switch (arguments.length) {
81 case 2: return acc(value);
83 var oldValue = acc(value),
84 extra_args = [].slice.call(arguments, 4);
85 try { return fn.apply(obj, extra_args) }
86 finally { acc(oldValue) } // reset no matter what
90 window.pref = pref; // export