summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/settings/prefs/prefs.js
blob: 4dbce56349082cb26f72bcc76b4573c220f0239f (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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/* Copyright 2015 The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file. */

/**
 * @fileoverview
 * 'cr-settings-prefs' exposes a singleton model of Chrome settings and
 * preferences, which listens to changes to Chrome prefs whitelisted in
 * chrome.settingsPrivate. When changing prefs in this element's 'prefs'
 * property via the UI, the singleton model tries to set those preferences in
 * Chrome. Whether or not the calls to settingsPrivate.setPref succeed, 'prefs'
 * is eventually consistent with the Chrome pref store.
 *
 * Example:
 *
 *    <cr-settings-prefs prefs="{{prefs}}"></cr-settings-prefs>
 *    <cr-settings-checkbox pref="{{prefs.homepage_is_newtabpage}}">
 *    </cr-settings-checkbox>
 *
 * @group Chrome Settings Elements
 * @element cr-settings-prefs
 */

(function() {
  'use strict';

  /**
   * Checks whether two values are recursively equal. Only compares serializable
   * data (primitives, serializable arrays and serializable objects).
   * @param {*} val1 Value to compare.
   * @param {*} val2 Value to compare with val1.
   * @return {boolean} True if the values are recursively equal.
   */
  function deepEqual(val1, val2) {
    if (val1 === val2)
      return true;

    if (Array.isArray(val1) || Array.isArray(val2)) {
      if (!Array.isArray(val1) || !Array.isArray(val2))
        return false;
      return arraysEqual(/** @type {!Array} */(val1),
                         /** @type {!Array} */(val2));
    }

    if (val1 instanceof Object && val2 instanceof Object)
      return objectsEqual(val1, val2);

    return false;
  }

  /**
   * @param {!Array} arr1
   * @param {!Array} arr2
   * @return {boolean} True if the arrays are recursively equal.
   */
  function arraysEqual(arr1, arr2) {
    if (arr1.length != arr2.length)
      return false;

    for (var i = 0; i < arr1.length; i++) {
      if (!deepEqual(arr1[i], arr2[i]))
        return false;
    }

    return true;
  }

  /**
   * @param {!Object} obj1
   * @param {!Object} obj2
   * @return {boolean} True if the objects are recursively equal.
   */
  function objectsEqual(obj1, obj2) {
    var keys1 = Object.keys(obj1);
    var keys2 = Object.keys(obj2);
    if (keys1.length != keys2.length)
      return false;

    for (var i = 0; i < keys1.length; i++) {
      var key = keys1[i];
      if (!deepEqual(obj1[key], obj2[key]))
        return false;
    }

    return true;
  }

  /**
   * Returns a recursive copy of the value.
   * @param {*} val Value to copy. Should be a primitive or only contain
   *     serializable data (primitives, serializable arrays and
   *     serializable objects).
   * @return {*} A deep copy of the value.
   */
  function deepCopy(val) {
    if (!(val instanceof Object))
      return val;
    return Array.isArray(val) ? deepCopyArray(/** @type {!Array} */(val)) :
        deepCopyObject(val);
  };

  /**
   * @param {!Array} arr
   * @return {!Array} Deep copy of the array.
   */
  function deepCopyArray(arr) {
    var copy = [];
    for (var i = 0; i < arr.length; i++)
      copy.push(deepCopy(arr[i]));
    return copy;
  }

  /**
   * @param {!Object} obj
   * @return {!Object} Deep copy of the object.
   */
  function deepCopyObject(obj) {
    var copy = {};
    var keys = Object.keys(obj);
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];
      copy[key] = deepCopy(obj[key]);
    }
    return copy;
  }

  Polymer({
    is: 'cr-settings-prefs',

    properties: {
      /**
       * Object containing all preferences, for use by Polymer controls.
       */
      prefs: {
        type: Object,
        notify: true,
      },

      /**
       * Singleton element created at startup which provides the prefs model.
       * @type {!Element}
       */
      singleton_: {
        type: Object,
        value: document.createElement('cr-settings-prefs-singleton'),
      },
    },

    observers: [
      'prefsChanged_(prefs.*)',
    ],

    /** @override */
    ready: function() {
      this.singleton_.initialize();
      this.startListening_();
    },

    /**
     * Binds this.prefs to the cr-settings-prefs-singleton's shared prefs once
     * preferences are initialized.
     * @private
     */
    startListening_: function() {
      CrSettingsPrefs.initialized.then(function() {
        // Ignore changes to prevent prefsChanged_ from notifying singleton_.
        this.runWhileIgnoringChanges_(function() {
          this.prefs = this.singleton_.prefs;
          this.stopListening_();
          this.listen(
              this.singleton_, 'prefs-changed', 'singletonPrefsChanged_');
        });
      }.bind(this));
    },

    /**
     * Stops listening for changes to cr-settings-prefs-singleton's shared
     * prefs.
     * @private
     */
    stopListening_: function() {
      this.unlisten(
          this.singleton_, 'prefs-changed', 'singletonPrefsChanged_');
    },

    /**
     * Handles changes reported by singleton_ by forwarding them to the host.
     * @private
     */
    singletonPrefsChanged_: function(e) {
      // Ignore changes because we've defeated Polymer's dirty-checking.
      this.runWhileIgnoringChanges_(function() {
        // Forward notification to host.
        this.fire(e.type, e.detail, {bubbles: false});
      });
    },

    /**
     * Forwards changes to this.prefs to cr-settings-prefs-singleton.
     * @private
     */
    prefsChanged_: function(info) {
      // Ignore changes that came from singleton_ so we don't re-process
      // changes made in other instances of this element.
      if (!this.ignoreChanges_)
        this.singleton_.fire('prefs-changed', info, {bubbles: false});
    },

    /**
     * Sets ignoreChanged_ before calling the function to suppress change
     * events that are manually handled.
     * @param {!function()} fn
     * @private
     */
    runWhileIgnoringChanges_: function(fn) {
      assert(!this.ignoreChanges_,
             'Nested calls to runWhileIgnoringChanges_ are not supported');
      this.ignoreChanges_ = true;
      fn.call(this);
      // We can unset ignoreChanges_ now because change notifications
      // are synchronous.
      this.ignoreChanges_ = false;
    },

    /**
     * Uninitializes this element to remove it from tests. Also resets
     * cr-settings-prefs-singleton, allowing newly created elements to
     * re-initialize it.
     */
    resetForTesting: function() {
      this.stopListening_();
      this.singleton_.resetForTesting();
    },
  });

  /**
   * Privately used element that contains, listens to and updates the shared
   * prefs state.
   */
  Polymer({
    is: 'cr-settings-prefs-singleton',

    properties: {
      /**
       * Object containing all preferences, for use by Polymer controls.
       * @type {Object|undefined}
       */
      prefs: {
        type: Object,
        notify: true,
      },

      /**
       * Map of pref keys to values representing the state of the Chrome
       * pref store as of the last update from the API.
       * @type {Object<*>}
       * @private
       */
      lastPrefValues_: {
        type: Object,
        value: function() { return {}; },
      },
    },

    // Listen for the manually fired prefs-changed event.
    listeners: {
      'prefs-changed': 'prefsChanged_',
    },

    settingsApi_: chrome.settingsPrivate,

    initialize: function() {
      // Only initialize once (or after resetForTesting() is called).
      if (this.initialized_)
        return;
      this.initialized_ = true;

      // Set window.mockApi to pass a custom settings API, i.e. for tests.
      // TODO(michaelpg): don't use a global.
      if (window.mockApi)
        this.settingsApi_ = window.mockApi;

      this.settingsApi_.onPrefsChanged.addListener(
          this.onSettingsPrivatePrefsChanged_.bind(this));
      this.settingsApi_.getAllPrefs(
          this.onSettingsPrivatePrefsFetched_.bind(this));
    },

    /**
     * Polymer callback for changes to this.prefs.
     * @param {!CustomEvent} e
     * @param {!{path: string}} change
     * @private
     */
    prefsChanged_: function(e, change) {
      if (!CrSettingsPrefs.isInitialized)
        return;

      var key = this.getPrefKeyFromPath_(change.path);
      var prefStoreValue = this.lastPrefValues_[key];

      var prefObj = /** @type {chrome.settingsPrivate.PrefObject} */(
          this.get(key, this.prefs));

      // If settingsPrivate already has this value, do nothing. (Otherwise,
      // a change event from settingsPrivate could make us call
      // settingsPrivate.setPref and potentially trigger an IPC loop.)
      if (deepEqual(prefStoreValue, prefObj.value))
        return;

      this.settingsApi_.setPref(
          key,
          prefObj.value,
          /* pageId */ '',
          /* callback */ this.setPrefCallback_.bind(this, key));
    },

    /**
     * Called when prefs in the underlying Chrome pref store are changed.
     * @param {!Array<!chrome.settingsPrivate.PrefObject>} prefs
     *     The prefs that changed.
     * @private
     */
    onSettingsPrivatePrefsChanged_: function(prefs) {
      if (CrSettingsPrefs.isInitialized)
        this.updatePrefs_(prefs);
    },

    /**
     * Called when prefs are fetched from settingsPrivate.
     * @param {!Array<!chrome.settingsPrivate.PrefObject>} prefs
     * @private
     */
    onSettingsPrivatePrefsFetched_: function(prefs) {
      this.updatePrefs_(prefs);
      CrSettingsPrefs.setInitialized();
    },

    /**
     * Checks the result of calling settingsPrivate.setPref.
     * @param {string} key The key used in the call to setPref.
     * @param {boolean} success True if setting the pref succeeded.
     * @private
     */
    setPrefCallback_: function(key, success) {
      if (success)
        return;

      // Get the current pref value from chrome.settingsPrivate to ensure the
      // UI stays up to date.
      this.settingsApi_.getPref(key, function(pref) {
        this.updatePrefs_([pref]);
      }.bind(this));
    },

    /**
     * Updates the prefs model with the given prefs.
     * @param {!Array<!chrome.settingsPrivate.PrefObject>} newPrefs
     * @private
     */
    updatePrefs_: function(newPrefs) {
      // Use the existing prefs object or create it.
      var prefs = this.prefs || {};
      newPrefs.forEach(function(newPrefObj) {
        // Use the PrefObject from settingsPrivate to create a copy in
        // lastPrefValues_ at the pref's key.
        this.lastPrefValues_[newPrefObj.key] = deepCopy(newPrefObj.value);

        if (!deepEqual(this.get(newPrefObj.key, prefs), newPrefObj)) {
          // Add the pref to |prefs|.
          cr.exportPath(newPrefObj.key, newPrefObj, prefs);
          // If this.prefs already exists, notify listeners of the change.
          if (prefs == this.prefs)
            this.notifyPath('prefs.' + newPrefObj.key, newPrefObj);
        }
      }, this);
      if (!this.prefs)
        this.prefs = prefs;
    },

    /**
     * Given a 'property-changed' path, returns the key of the preference the
     * path refers to. E.g., if the path of the changed property is
     * 'prefs.search.suggest_enabled.value', the key of the pref that changed is
     * 'search.suggest_enabled'.
     * @param {string} path
     * @return {string}
     * @private
     */
    getPrefKeyFromPath_: function(path) {
      // Skip the first token, which refers to the member variable (this.prefs).
      var parts = path.split('.');
      assert(parts.shift() == 'prefs');

      for (let i = 1; i <= parts.length; i++) {
        let key = parts.slice(0, i).join('.');
        // The lastPrefValues_ keys match the pref keys.
        if (this.lastPrefValues_.hasOwnProperty(key))
          return key;
      }
      return '';
    },

    /**
     * Resets the element so it can be re-initialized with a new prefs state.
     */
    resetForTesting: function() {
      this.prefs = undefined;
      this.lastPrefValues_ = {};
      this.initialized_ = false;
    },
  });
})();