summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/prefs.js
blob: 5bfe115c7ee2a51102539663acbc8a3b952ebe79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

const EventEmitter = require("resource://devtools/shared/event-emitter.js");

/**
 * Shortcuts for lazily accessing and setting various preferences.
 * Usage:
 *   let prefs = new Prefs("root.path.to.branch", {
 *     myIntPref: ["Int", "leaf.path.to.my-int-pref"],
 *     myCharPref: ["Char", "leaf.path.to.my-char-pref"],
 *     myJsonPref: ["Json", "leaf.path.to.my-json-pref"],
 *     myFloatPref: ["Float", "leaf.path.to.my-float-pref"]
 *     ...
 *   });
 *
 * Get/set:
 *   prefs.myCharPref = "foo";
 *   let aux = prefs.myCharPref;
 *
 * Observe:
 *   prefs.registerObserver();
 *   prefs.on("pref-changed", (prefValue) => {
 *     ...
 *   });
 *
 * @param string prefsRoot
 *        The root path to the required preferences branch.
 * @param object prefsBlueprint
 *        An object containing { accessorName: [prefType, prefName] } keys.
 */
function PrefsHelper(prefsRoot = "", prefsBlueprint = {}) {
  EventEmitter.decorate(this);

  const cache = new Map();

  for (const accessorName in prefsBlueprint) {
    const [prefType, prefName, fallbackValue] = prefsBlueprint[accessorName];
    map(
      this,
      cache,
      accessorName,
      prefType,
      prefsRoot,
      prefName,
      fallbackValue
    );
  }

  const observer = makeObserver(this, cache, prefsRoot, prefsBlueprint);
  this.registerObserver = () => observer.register();
  this.unregisterObserver = () => observer.unregister();
}

/**
 * Helper method for getting a pref value.
 *
 * @param Map cache
 * @param string prefType
 * @param string prefsRoot
 * @param string prefName
 * @param string|int|boolean fallbackValue
 * @return any
 */
function get(cache, prefType, prefsRoot, prefName, fallbackValue) {
  const cachedPref = cache.get(prefName);
  if (cachedPref !== undefined) {
    return cachedPref;
  }
  const value = Services.prefs["get" + prefType + "Pref"](
    [prefsRoot, prefName].join("."),
    fallbackValue
  );
  cache.set(prefName, value);
  return value;
}

/**
 * Helper method for setting a pref value.
 *
 * @param Map cache
 * @param string prefType
 * @param string prefsRoot
 * @param string prefName
 * @param any value
 */
function set(cache, prefType, prefsRoot, prefName, value) {
  Services.prefs["set" + prefType + "Pref"](
    [prefsRoot, prefName].join("."),
    value
  );
  cache.set(prefName, value);
}

/**
 * Maps a property name to a pref, defining lazy getters and setters.
 * Supported types are "Bool", "Char", "Int", "Float" (sugar around "Char"
 * type and casting), and "Json" (which is basically just sugar for "Char"
 * using the standard JSON serializer).
 *
 * @param PrefsHelper self
 * @param Map cache
 * @param string accessorName
 * @param string prefType
 * @param string prefsRoot
 * @param string prefName
 * @param string|int|boolean fallbackValue
 * @param array serializer [optional]
 */
function map(
  self,
  cache,
  accessorName,
  prefType,
  prefsRoot,
  prefName,
  fallbackValue,
  serializer = { in: e => e, out: e => e }
) {
  if (prefName in self) {
    throw new Error(
      `Can't use ${prefName} because it overrides a property` +
        "on the instance."
    );
  }
  if (prefType == "Json") {
    map(
      self,
      cache,
      accessorName,
      "String",
      prefsRoot,
      prefName,
      fallbackValue,
      {
        in: JSON.parse,
        out: JSON.stringify,
      }
    );
    return;
  }
  if (prefType == "Float") {
    map(self, cache, accessorName, "Char", prefsRoot, prefName, fallbackValue, {
      in: Number.parseFloat,
      out: n => n + "",
    });
    return;
  }

  Object.defineProperty(self, accessorName, {
    get: () =>
      serializer.in(get(cache, prefType, prefsRoot, prefName, fallbackValue)),
    set: e => {
      set(cache, prefType, prefsRoot, prefName, serializer.out(e));
    },
  });
}

/**
 * Finds the accessor for the provided pref, based on the blueprint object
 * used in the constructor.
 *
 * @param PrefsHelper self
 * @param object prefsBlueprint
 * @return string
 */
function accessorNameForPref(somePrefName, prefsBlueprint) {
  for (const accessorName in prefsBlueprint) {
    const [, prefName] = prefsBlueprint[accessorName];
    if (somePrefName == prefName) {
      return accessorName;
    }
  }
  return "";
}

/**
 * Creates a pref observer for `self`.
 *
 * @param PrefsHelper self
 * @param Map cache
 * @param string prefsRoot
 * @param object prefsBlueprint
 * @return object
 */
function makeObserver(self, cache, prefsRoot, prefsBlueprint) {
  return {
    register() {
      this._branch = Services.prefs.getBranch(prefsRoot + ".");
      this._branch.addObserver("", this);
    },
    unregister() {
      this._branch.removeObserver("", this);
    },
    observe(subject, topic, prefName) {
      // If this particular pref isn't handled by the blueprint object,
      // even though it's in the specified branch, ignore it.
      const accessorName = accessorNameForPref(prefName, prefsBlueprint);
      if (!(accessorName in self)) {
        return;
      }
      cache.delete(prefName);
      self.emit("pref-changed", accessorName, self[accessorName]);
    },
  };
}

exports.PrefsHelper = PrefsHelper;

/**
 * A PreferenceObserver observes a pref branch for pref changes.
 * It emits an event for each preference change.
 */
function PrefObserver(branchName) {
  this.branchName = branchName;
  this.branch = Services.prefs.getBranch(branchName);
  this.branch.addObserver("", this);

  EventEmitter.decorate(this);
}

exports.PrefObserver = PrefObserver;

PrefObserver.prototype = {
  observe(subject, topic, data) {
    if (topic == "nsPref:changed") {
      this.emit(this.branchName + data);
    }
  },

  destroy() {
    if (this.branch) {
      this.branch.removeObserver("", this);
    }
  },
};