summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/settings/prefs/prefs.js
blob: 55626d18faedb09b0224642198242ea39b985a2f (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
/* 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
 * '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.
 */

(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 (let 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) {
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if (keys1.length != keys2.length) {
    return false;
  }

  for (let i = 0; i < keys1.length; i++) {
    const 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) {
  const copy = [];
  for (let 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) {
  const copy = {};
  const keys = Object.keys(obj);
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    copy[key] = deepCopy(obj[key]);
  }
  return copy;
}

Polymer({
  is: 'settings-prefs',

  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 {};
      },
    },
  },

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

  /** @type {SettingsPrivate} */
  settingsApi_: /** @type {SettingsPrivate} */ (chrome.settingsPrivate),

  /** @override */
  created: function() {
    if (!CrSettingsPrefs.deferInitialization) {
      this.initialize();
    }
  },

  /** @override */
  detached: function() {
    CrSettingsPrefs.resetForTesting();
  },

  /**
   * @param {SettingsPrivate=} opt_settingsApi SettingsPrivate implementation
   *     to use (chrome.settingsPrivate by default).
   */
  initialize: function(opt_settingsApi) {
    // Only initialize once (or after resetForTesting() is called).
    if (this.initialized_) {
      return;
    }
    this.initialized_ = true;

    if (opt_settingsApi) {
      this.settingsApi_ = opt_settingsApi;
    }

    /** @private {function(!Array<!chrome.settingsPrivate.PrefObject>)} */
    this.boundPrefsChanged_ = this.onSettingsPrivatePrefsChanged_.bind(this);
    this.settingsApi_.onPrefsChanged.addListener(this.boundPrefsChanged_);
    this.settingsApi_.getAllPrefs(
        this.onSettingsPrivatePrefsFetched_.bind(this));
  },

  /**
   * @param {!{path: string}} e
   * @private
   */
  prefsChanged_: function(e) {
    // |prefs| can be directly set or unset in tests.
    if (!CrSettingsPrefs.isInitialized || e.path == 'prefs') {
      return;
    }

    const key = this.getPrefKeyFromPath_(e.path);
    const prefStoreValue = this.lastPrefValues_[key];

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

    // If settingsPrivate already has this value, ignore it. (Otherwise,
    // a change event from settingsPrivate could make us call
    // settingsPrivate.setPref and potentially trigger an IPC loop.)
    if (!deepEqual(prefStoreValue, prefObj.value)) {
      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) {
      this.refresh(key);
    }
  },

  /**
   * Get the current pref value from chrome.settingsPrivate to ensure the UI
   * stays up to date.
   * @param {string} key
   */
  refresh: function(key) {
    this.settingsApi_.getPref(key, pref => {
      this.updatePrefs_([pref]);
    });
  },

  /**
   * 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.
    const 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).
    const parts = path.split('.');
    assert(parts.shift() == 'prefs', 'Path doesn\'t begin with \'prefs\'');

    for (let i = 1; i <= parts.length; i++) {
      const 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() {
    if (!this.initialized_) {
      return;
    }
    this.prefs = undefined;
    this.lastPrefValues_ = {};
    this.initialized_ = false;
    // Remove the listener added in initialize().
    this.settingsApi_.onPrefsChanged.removeListener(this.boundPrefsChanged_);
    this.settingsApi_ =
        /** @type {SettingsPrivate} */ (chrome.settingsPrivate);
  },
});
})();