summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/chromeos/emulator/bluetooth_settings.js
blob: 377f73d7b9de9f830f45987c19c1486601e1d965 (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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// 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.

/**
 * A bluetooth device.
 * @constructor
 */
var BluetoothDevice = function() {
  // The device's address (MAC format, must be unique).
  this.address = '';

  // The label which shows up in the devices list for this device.
  this.alias = '';

  // The text label of the selected device class.
  this.class = 'Computer';

  // The uint32 value of the selected device class.
  this.classValue = 0x104;

  // Whether or not the device shows up in the system tray's observed list of
  // bluetooth devices.
  this.discoverable = false;

  // Whether Chrome OS pairs with this device, or this device tries to pair
  // with Chrome OS.
  this.incoming = false;

  // A trusted device is one which is plugged directly Chrome OS and therefore
  // is paired by default, but not connected.
  this.isTrusted = false;

  // The device's name.This is not the label which shows up in the devices list
  // here or in the system tray--use |.alias| to edit that label.
  this.name = '';

  // The designated path for the device. Must be unique.
  this.path = '';

  // Whether or not the device is paired with Chrome OS.
  this.paired = false;

  // The label of the selected pairing method option.
  this.pairingMethod = 'None';

  // The text containing a PIN key or passkey for pairing.
  this.pairingAuthToken = '';

  // The label of the selected pairing action option.
  this.pairingAction = '';
};

Polymer({
  is: 'bluetooth-settings',

  properties: {
    /**
     * The title to be displayed in a heading element for the element.
     */
    title: {type: String},

    /**
     * A set of bluetooth devices.
     * @type !Array<!BluetoothDevice>
     */
    devices: {type: Array, value: function() { return []; }},

    /**
     * A set of predefined bluetooth devices.
     * @type !Array<!Bluetooth>
     */
    predefinedDevices: {type: Array, value: function() { return []; }},

    /**
     * A bluetooth device object which is currently being edited.
     * @type {BluetoothDevice}
     */
    currentEditableObject: {
      type: Object,
      value: function() { return {}; }
    },

    /**
     * The index of the bluetooth device object which is currently being edited.
     * This is initially set to -1 (i.e. no device selected) because not custom
     * devices exist when the page loads.
     */
    currentEditIndex: {type: Number, value: function() { return -1; }},

    /**
     * A set of options for the possible bluetooth device classes/types.
     * Object |value| attribute comes from values in the WebUI, set in
     * setDeviceClassOptions.
     * @type !Array<! {text: string, value: int} >
     */
    deviceClassOptions: {
      type: Array,
      value: function() {
        return [
          {text: 'Unknown', value: 0},
          {text: 'Mouse', value: 0x2580},
          {text: 'Keyboard', value: 0x2540},
          {text: 'Audio', value: 0x240408},
          {text: 'Phone', value: 0x7a020c},
          {text: 'Computer', value: 0x104}
        ];
      }
    },

    /**
     * A set of strings representing the method to be used for
     * authenticating a device during a pair request.
     * @type !Array<string>
     */
    deviceAuthenticationMethods: {
      type: Array,
      value: function() { return []; }
    },

    /**
     * A set of strings representing the actions which can be done when
     * a secure device is paired/requests a pair.
     * @type !Array<string>
     */
    deviceAuthenticationActions: {
      type: Array,
      value: function() { return []; }
    },
  },

  /**
   * Contains keys for all the device paths which have been discovered. Used
   * to look up whether or not a device is listed already.
   * @type {Object}
   */
  devicePaths: {},

  ready: function() { this.title = 'Bluetooth'; },

  initialize: function() {
    if (!this.initialized) {
      this.initialized = true;
      chrome.send('requestBluetoothInfo');
    }
  },

  observers: ['currentEditableObjectChanged(currentEditableObject.*)'],

  /**
   * Called when a property of the currently editable object is edited.
   * Sets the corresponding property for the object in |this.devices|.
   * @param {Object} obj An object containing event information (ex. which
   *     property of |this.currentEditableObject| was changed, what its value
   *     is, etc.)
   */
  currentEditableObjectChanged: function(obj) {
    if (this.currentEditIndex >= 0) {
      var prop = obj.path.split('.')[1];
      this.set('devices.' + this.currentEditIndex.toString() + '.' + prop,
               obj.value);
    }
  },

  /**
   * Called when the device edit modal is opened. Re-validates necessary input
   * fields.
   */
  editDialogOpened: function() {
    this.validateAddress();
    this.validatePath();
  },

  handleAddressInput: function() {
    this.autoFormatAddress();
    this.validateAddress();
  },

  autoFormatAddress: function() {
    var input = this.$.deviceAddressInput;
    var regex = /([a-f0-9]{2})([a-f0-9]{2})/i;
    // Remove things that aren't hex characters from the string.
    var val = input.value.replace(/[^a-f0-9]/ig, '');

    // Insert a ':' in the middle of every four hex characters.
    while (regex.test(val))
      val = val.replace(regex, '$1:$2');

    input.value = val;
  },

  /**
   * Called on-input from an input element and on edit modal open.
   * Validates whether or not the
   * input's content matches a regular expression. If the input's value
   * satisfies the regex, then make sure that the address is not already
   * in use.
   */
  validateAddress: function() {
    var input = this.$.deviceAddressInput;
    var val = input.value;
    var exists = false;
    var addressRegex = RegExp('^([\\da-fA-F]{2}:){5}[\\da-fA-F]{2}$');
    if (addressRegex.test(val)) {
      for (var i = 0; i < this.predefinedDevices.length; ++i) {
        if (this.predefinedDevices[i].address == val) {
          exists = true;
          break;
        }
      }

      if (!exists) {
        for (var i = 0; i < this.devices.length; ++i) {
          if (this.devices[i].address == val && i != this.currentEditIndex) {
            exists = true;
            break;
          }
        }
      }

      if (exists) {
        input.invalid = true;
        input.errorMessage = 'This address is already being used.';
      } else {
        input.invalid = false;
      }
    } else {
      input.invalid = true;
      input.errorMessage = 'Invalid address.';
    }
  },

  /**
   * Makes sure that a path is not already used.
   */
  validatePath: function() {
    var input = this.$.devicePathInput;
    var val = input.value;
    var exists = false;

    for (var i = 0; i < this.predefinedDevices.length; ++i) {
      if (this.predefinedDevices[i].path == val) {
        exists = true;
        break;
      }
    }

    if (!exists) {
      for (var i = 0; i < this.devices.length; ++i) {
        if (this.devices[i].path == val && i != this.currentEditIndex) {
          exists = true;
          break;
        }
      }
    }

    if (exists) {
      input.invalid = true;
      input.errorMessage = 'This path is already being used.';
    } else {
      input.invalid = false;
    }
  },

  /**
   * Checks whether or not the PIN/passkey input field should be shown.
   * It should only be shown when the pair method is not 'None' or empty.
   * @param {string} pairMethod The label of the selected pair method option
   *     for a particular device.
   * @return {boolean} Whether the PIN/passkey input field should be shown.
   */
  showAuthToken: function(pairMethod) {
    return pairMethod && pairMethod != 'None';
  },

  /**
   * Called by the WebUI which provides a list of devices which are connected
   * to the main adapter.
   * @param {!Array<!BluetoothDevice>} devices A list of bluetooth devices.
   */
  updateBluetoothInfo: function(predefinedDevices, loadedCustomDevices,
                                pairingMethodOptions, pairingActionOptions) {
    this.predefinedDevices = this.loadDevicesFromList(predefinedDevices, true);
    this.devices = this.loadDevicesFromList(loadedCustomDevices, false);
    this.deviceAuthenticationMethods = pairingMethodOptions;
    this.deviceAuthenticationActions = pairingActionOptions;
  },

  /**
   * Builds complete BluetoothDevice objects for each element in |devices_list|.
   * @param {!Array<!BluetoothDevice>} devices_list A list of incomplete
   *     BluetoothDevice provided by the C++ WebUI.
   * @param {boolean} predefined Whether or not the device is a predefined one.
   */
  loadDevicesFromList: function(devices, predefined) {
    /** @type {!Array<!BluetoothDevice>} */ var deviceList = [];

    for (var i = 0; i < devices.length; ++i) {
      if (this.devicePaths[devices[i].path] != undefined) continue;

      // Get the label for the device class which should be selected.
      devices[i].class = this.getTextForDeviceClass(devices[i].classValue);
      devices[i].pairingAuthToken = devices[i].pairingAuthToken.toString();
      deviceList.push(devices[i]);
      this.devicePaths[devices[i].path] = {
        predefined: predefined,
        index: deviceList.length - 1
      };
    }

    return deviceList;
  },

  /**
   * Called when a device is paired from the Tray. Checks the paired box for
   * the device with path |path|.
   */
  devicePairedFromTray: function(path) {
    var obj = this.devicePaths[path];

    if (obj == undefined) return;

    var index = obj.index;
    var devicePath = (obj.predefined ? 'predefinedDevices.' : 'devices.');
    devicePath += obj.index.toString();
    this.set(devicePath + '.paired', true);
  },

  /**
   * On-change handler for a checkbox in the device list. Pairs/unpairs the
   * device associated with the box checked/unchecked.
   * @param {Event} event Contains event data. |event.model.index| is the index
   *     of the item which the target is contained in.
   */
  pairDevice: function(event) {
    var index = event.model.index;
    var predefined =
        /** @type {boolean} */ (event.target.dataset.predefined == 'true');
    var device =
        predefined ? this.predefinedDevices[index] : this.devices[index];

    if (event.target.checked) {
      var devicePath = (predefined ? 'predefinedDevices.' : 'devices.');
      devicePath += index.toString();
      this.set(devicePath + '.discoverable', true);

      // Send device info to the WebUI.
      chrome.send('requestBluetoothPair', [device]);
      this.devicePaths[device.path] = {predefined: predefined, index: index};

      var devicePath = (predefined ? 'predefinedDevices.' : 'devices.');
      devicePath += index.toString();
      this.set(devicePath + '.paired', false);
    } else {
      chrome.send('removeBluetoothDevice', [device.path]);

      var devicePath = (predefined ? 'predefinedDevices.' : 'devices.');
      devicePath += index.toString();
      this.set(devicePath + '.discoverable', false);
    }
  },

  /**
   * Called from Chrome OS back-end when a pair request fails.
   * @param {string} path The path of the device which failed to pair.
   */
  pairFailed: function(path) {
    var obj = this.devicePaths[path];

    if (obj == undefined) return;

    var devicePath = (obj.predefined ? 'predefinedDevices.' : 'devices.');
    devicePath += obj.index.toString();
    this.set(devicePath + '.paired', false);
  },

  /**
   * On-change event handler for a checkbox in the device list.
   * @param {Event} event Contains event data. |event.model.index| is the index
   *     of the item which the target is contained in.
   */
  discoverDevice: function(event) {
    var index = event.model.index;
    var predefined =
        /** @type {boolean} */ (event.target.dataset.predefined == 'true');
    var device =
        predefined ? this.predefinedDevices[index] : this.devices[index];

    if (event.target.checked) {
      device.classValue = this.getValueForDeviceClass(device.class);

      // Send device info to WebUI.
      chrome.send('requestBluetoothDiscover', [device]);

      this.devicePaths[device.path] = {predefined: predefined, index: index};
    } else {
      chrome.send('removeBluetoothDevice', [device.path]);

      var devicePath = (predefined ? 'predefinedDevices.' : 'devices.');
      devicePath += index.toString();
      this.set(devicePath + '.paired', false);
    }
  },

  // Adds a new device with default settings to the list of devices.
  appendNewDevice: function() {
    var newDevice = new BluetoothDevice();
    newDevice.alias = 'New Device';
    this.push('devices', newDevice);
  },

  /**
   * This is called when a new device is discovered by the main adapter.
   * The device is only added to the view's list if it is not already in
   * the list (i.e. its path has not yet been recorded in |devicePaths|).
   * @param {BluetoothDevice} device A bluetooth device.
   */
  addBluetoothDevice: function(device) {
    if (this.devicePaths[device.path] != undefined) {
      var obj = this.devicePaths[device.path];
      var devicePath = (obj.predefined ? 'predefinedDevices.' : 'devices.');
      devicePath += obj.index.toString();
      this.set(devicePath + '.discoverable', true);
      return;
    }

    device.class = this.getTextForDeviceClass(device.classValue);
    device.discoverable = true;
    this.push('devices', device);
    this.devicePaths[device.path] = {
      predefined: false,
      index: this.devices.length - 1
    };
  },

  /**
   * Called on "copy" button from the device list clicked. Creates a copy of
   * the selected device and adds it to the "custom" devices list.
   * @param {Event} event Contains event data. |event.model.index| is the index
   *     of the item which the target is contained in.
   */
  copyDevice: function(event) {
    var predefined = (event.target.dataset.predefined == 'true');
    var index = event.model.index;
    var copyDevice =
        predefined ? this.predefinedDevices[index] : this.devices[index];
    // Create a deep copy of the selected device.
    var newDevice = new BluetoothDevice();
    Object.assign(newDevice, copyDevice);
    newDevice.path = '';
    newDevice.address = '';
    newDevice.name += ' (Copy)';
    newDevice.alias += ' (Copy)';
    newDevice.discoverable = false;
    newDevice.paired = false;
    this.push('devices', newDevice);
  },

  /**
   * Shows a modal dialog to edit the selected device's properties.
   * @param {Event} event Contains event data. |event.model.index| is the index
   *     of the item which the target is contained in.
   */
  showEditModal: function(event) {
    var index = event.model.index;
    this.currentEditIndex = index;
    this.currentEditableObject = this.devices[index];
    this.$.editModal.toggle();
  },

  /**
   * A click handler for the delete button on bluetooth devices.
   * @param {Event} event Contains event data. |event.model.index| is the index
   *     of the item which the target is contained in.
   */
  deleteDevice: function(event) {
    var index = event.model.index;
    var device = this.devices[index];

    chrome.send('removeBluetoothDevice', [device.path]);

    this.devicePaths[device.path] = undefined;
    this.splice('devices', index, 1);
  },

  /**
   * This function is called when a device is removed from the main bluetooth
   * adapter's device list. It sets that device's |.discoverable| and |.paired|
   * attributes to false.
   * @param {string} path A bluetooth device's path.
   */
  deviceRemovedFromMainAdapter: function(path) {
    if (this.devicePaths[path] == undefined) return;

    var obj = this.devicePaths[path];
    var devicePath = (obj.predefined ? 'predefinedDevices.' : 'devices.');
    devicePath += obj.index.toString();
    this.set(devicePath + '.discoverable', false);
    this.set(devicePath + '.paired', false);
  },

  /**
   * Returns the text for the label that corresponds to |classValue|.
   * @param {number} classValue A number representing the bluetooth class
   *     of a device.
   * @return {string} The label which represents |classValue|.
   */
  getTextForDeviceClass: function(classValue) {
    for (var i = 0; i < this.deviceClassOptions.length; ++i) {
      if (this.deviceClassOptions[i].value == classValue)
        return this.deviceClassOptions[i].text;
    }
  },

  /**
   * Returns the integer value which corresponds with the label |classText|.
   * @param {string} classText The label for a device class option.
   * @return {number} The value which |classText| represents.
   */
  getValueForDeviceClass: function(classText) {
    for (var i = 0; i < this.deviceClassOptions.length; ++i) {
      if (this.deviceClassOptions[i].text == classText)
        return this.deviceClassOptions[i].value;
    }
    return 0;
  },
});