1// Copyright 2014 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5/** 6 * @fileoverview A class for managing all enumerated gnubby devices. 7 */ 8'use strict'; 9 10/** 11 * @typedef {{ 12 * namespace: string, 13 * device: number 14 * }} 15 */ 16var GnubbyDeviceId; 17 18/** 19 * @typedef {{ 20 * isSharedAccess: boolean, 21 * enumerate: function(function(Array)), 22 * deviceToDeviceId: function(*): GnubbyDeviceId, 23 * open: function(Gnubbies, number, *, function(number, GnubbyDevice=)) 24 * }} 25 */ 26var GnubbyNamespaceImpl; 27 28/** 29 * Manager of opened devices. 30 * @constructor 31 */ 32function Gnubbies() { 33 /** @private {Object.<string, Array>} */ 34 this.devs_ = {}; 35 this.pendingEnumerate = []; // clients awaiting an enumerate 36 /** 37 * The distinct namespaces registered in this Gnubbies instance, in order of 38 * registration. 39 * @private {Array.<string>} 40 */ 41 this.namespaces_ = []; 42 /** @private {Object.<string, GnubbyNamespaceImpl>} */ 43 this.impl_ = {}; 44 /** @private {Object.<string, Object.<number, !GnubbyDevice>>} */ 45 this.openDevs_ = {}; 46 /** @private {Object.<string, Object.<number, *>>} */ 47 this.pendingOpens_ = {}; // clients awaiting an open 48} 49 50/** 51 * Registers a new gnubby namespace, i.e. an implementation of the 52 * enumerate/open functions for all devices within a namespace. 53 * @param {string} namespace The namespace of the numerator, e.g. 'usb'. 54 * @param {GnubbyNamespaceImpl} impl The implementation. 55 */ 56Gnubbies.prototype.registerNamespace = function(namespace, impl) { 57 if (!this.impl_.hasOwnProperty(namespace)) { 58 this.namespaces_.push(namespace); 59 } 60 this.impl_[namespace] = impl; 61}; 62 63/** 64 * @param {GnubbyDeviceId} id The device id. 65 * @return {boolean} Whether the device is a shared access device. 66 */ 67Gnubbies.prototype.isSharedAccess = function(id) { 68 if (!this.impl_.hasOwnProperty(id.namespace)) return false; 69 return this.impl_[id.namespace].isSharedAccess; 70}; 71 72/** 73 * @param {GnubbyDeviceId} which The device to remove. 74 */ 75Gnubbies.prototype.removeOpenDevice = function(which) { 76 if (this.openDevs_[which.namespace] && 77 this.openDevs_[which.namespace].hasOwnProperty(which.device)) { 78 delete this.openDevs_[which.namespace][which.device]; 79 } 80}; 81 82/** Close all enumerated devices. */ 83Gnubbies.prototype.closeAll = function() { 84 if (this.inactivityTimer) { 85 this.inactivityTimer.clearTimeout(); 86 this.inactivityTimer = undefined; 87 } 88 // Close and stop talking to any gnubbies we have enumerated. 89 for (var namespace in this.openDevs_) { 90 for (var dev in this.openDevs_[namespace]) { 91 var deviceId = Number(dev); 92 this.openDevs_[namespace][deviceId].destroy(); 93 } 94 } 95 this.devs_ = {}; 96 this.openDevs_ = {}; 97}; 98 99/** 100 * @param {function(number, Array.<GnubbyDeviceId>)} cb Called back with the 101 * result of enumerating. 102 */ 103Gnubbies.prototype.enumerate = function(cb) { 104 if (!cb) { 105 cb = function(rc, indexes) { 106 var msg = 'defaultEnumerateCallback(' + rc; 107 if (indexes) { 108 msg += ', ['; 109 for (var i = 0; i < indexes.length; i++) { 110 msg += JSON.stringify(indexes[i]); 111 } 112 msg += ']'; 113 } 114 msg += ')'; 115 console.log(UTIL_fmt(msg)); 116 }; 117 } 118 119 if (!this.namespaces_.length) { 120 cb(-GnubbyDevice.OK, []); 121 return; 122 } 123 124 var namespacesEnumerated = 0; 125 var self = this; 126 127 /** 128 * @param {string} namespace The namespace that was enumerated. 129 * @param {Array.<GnubbyDeviceId>} existingDeviceIds Previously enumerated 130 * device IDs (from other namespaces), if any. 131 * @param {Array} devs The devices in the namespace. 132 */ 133 function enumerated(namespace, existingDeviceIds, devs) { 134 namespacesEnumerated++; 135 var lastNamespace = (namespacesEnumerated == self.namespaces_.length); 136 137 if (chrome.runtime.lastError) { 138 console.warn(UTIL_fmt('lastError: ' + chrome.runtime.lastError)); 139 console.log(chrome.runtime.lastError); 140 devs = []; 141 } 142 143 console.log(UTIL_fmt('Enumerated ' + devs.length + ' gnubbies')); 144 console.log(devs); 145 146 var presentDevs = {}; 147 var deviceIds = []; 148 var deviceToDeviceId = self.impl_[namespace].deviceToDeviceId; 149 for (var i = 0; i < devs.length; ++i) { 150 var deviceId = deviceToDeviceId(devs[i]); 151 deviceIds.push(deviceId); 152 presentDevs[deviceId.device] = devs[i]; 153 } 154 155 var toRemove = []; 156 for (var dev in self.openDevs_[namespace]) { 157 if (!presentDevs.hasOwnProperty(dev)) { 158 toRemove.push(dev); 159 } 160 } 161 162 for (var i = 0; i < toRemove.length; i++) { 163 dev = toRemove[i]; 164 if (self.openDevs_[namespace][dev]) { 165 self.openDevs_[namespace][dev].destroy(); 166 delete self.openDevs_[namespace][dev]; 167 } 168 } 169 170 self.devs_[namespace] = devs; 171 existingDeviceIds.push.apply(existingDeviceIds, deviceIds); 172 if (lastNamespace) { 173 while (self.pendingEnumerate.length != 0) { 174 var cb = self.pendingEnumerate.shift(); 175 cb(-GnubbyDevice.OK, existingDeviceIds); 176 } 177 } 178 } 179 180 var deviceIds = []; 181 function makeEnumerateCb(namespace) { 182 return function(devs) { 183 enumerated(namespace, deviceIds, devs); 184 } 185 } 186 187 this.pendingEnumerate.push(cb); 188 if (this.pendingEnumerate.length == 1) { 189 for (var i = 0; i < this.namespaces_.length; i++) { 190 var namespace = this.namespaces_[i]; 191 var enumerator = this.impl_[namespace].enumerate; 192 enumerator(makeEnumerateCb(namespace)); 193 } 194 } 195}; 196 197/** 198 * Amount of time past last activity to set the inactivity timer to, in millis. 199 * @const 200 */ 201Gnubbies.INACTIVITY_TIMEOUT_MARGIN_MILLIS = 30000; 202 203/** 204 * @param {number|undefined} opt_timeoutMillis Timeout in milliseconds 205 */ 206Gnubbies.prototype.resetInactivityTimer = function(opt_timeoutMillis) { 207 var millis = opt_timeoutMillis ? 208 opt_timeoutMillis + Gnubbies.INACTIVITY_TIMEOUT_MARGIN_MILLIS : 209 Gnubbies.INACTIVITY_TIMEOUT_MARGIN_MILLIS; 210 if (!this.inactivityTimer) { 211 this.inactivityTimer = 212 new CountdownTimer(millis, this.inactivityTimeout_.bind(this)); 213 } else if (millis > this.inactivityTimer.millisecondsUntilExpired()) { 214 this.inactivityTimer.clearTimeout(); 215 this.inactivityTimer.setTimeout(millis, this.inactivityTimeout_.bind(this)); 216 } 217}; 218 219/** 220 * Called when the inactivity timeout expires. 221 * @private 222 */ 223Gnubbies.prototype.inactivityTimeout_ = function() { 224 this.inactivityTimer = undefined; 225 for (var namespace in this.openDevs_) { 226 for (var dev in this.openDevs_[namespace]) { 227 var deviceId = Number(dev); 228 console.warn(namespace + ' device ' + deviceId + 229 ' still open after inactivity, closing'); 230 this.openDevs_[namespace][deviceId].destroy(); 231 } 232 } 233}; 234 235/** 236 * Opens and adds a new client of the specified device. 237 * @param {GnubbyDeviceId} which Which device to open. 238 * @param {*} who Client of the device. 239 * @param {function(number, GnubbyDevice=)} cb Called back with the result of 240 * opening the device. 241 */ 242Gnubbies.prototype.addClient = function(which, who, cb) { 243 this.resetInactivityTimer(); 244 245 var self = this; 246 247 function opened(gnubby, who, cb) { 248 if (gnubby.closing) { 249 // Device is closing or already closed. 250 self.removeClient(gnubby, who); 251 if (cb) { cb(-GnubbyDevice.NODEVICE); } 252 } else { 253 gnubby.registerClient(who); 254 if (cb) { cb(-GnubbyDevice.OK, gnubby); } 255 } 256 } 257 258 function notifyOpenResult(rc) { 259 if (self.pendingOpens_[which.namespace]) { 260 while (self.pendingOpens_[which.namespace][which.device].length != 0) { 261 var client = self.pendingOpens_[which.namespace][which.device].shift(); 262 client.cb(rc); 263 } 264 delete self.pendingOpens_[which.namespace][which.device]; 265 } 266 } 267 268 var dev = null; 269 var deviceToDeviceId = this.impl_[which.namespace].deviceToDeviceId; 270 if (this.devs_[which.namespace]) { 271 for (var i = 0; i < this.devs_[which.namespace].length; i++) { 272 var device = this.devs_[which.namespace][i]; 273 if (deviceToDeviceId(device).device == which.device) { 274 dev = device; 275 break; 276 } 277 } 278 } 279 if (!dev) { 280 // Index out of bounds. Device does not exist in current enumeration. 281 this.removeClient(null, who); 282 if (cb) { cb(-GnubbyDevice.NODEVICE); } 283 return; 284 } 285 286 function openCb(rc, opt_gnubby) { 287 if (rc) { 288 notifyOpenResult(rc); 289 return; 290 } 291 if (!opt_gnubby) { 292 notifyOpenResult(-GnubbyDevice.NODEVICE); 293 return; 294 } 295 var gnubby = /** @type {!GnubbyDevice} */ (opt_gnubby); 296 if (!self.openDevs_[which.namespace]) { 297 self.openDevs_[which.namespace] = {}; 298 } 299 self.openDevs_[which.namespace][which.device] = gnubby; 300 while (self.pendingOpens_[which.namespace][which.device].length != 0) { 301 var client = self.pendingOpens_[which.namespace][which.device].shift(); 302 opened(gnubby, client.who, client.cb); 303 } 304 delete self.pendingOpens_[which.namespace][which.device]; 305 } 306 307 if (this.openDevs_[which.namespace] && 308 this.openDevs_[which.namespace].hasOwnProperty(which.device)) { 309 var gnubby = this.openDevs_[which.namespace][which.device]; 310 opened(gnubby, who, cb); 311 } else { 312 var opener = {who: who, cb: cb}; 313 if (!this.pendingOpens_.hasOwnProperty(which.namespace)) { 314 this.pendingOpens_[which.namespace] = {}; 315 } 316 if (this.pendingOpens_[which.namespace].hasOwnProperty(which.device)) { 317 this.pendingOpens_[which.namespace][which.device].push(opener); 318 } else { 319 this.pendingOpens_[which.namespace][which.device] = [opener]; 320 var openImpl = this.impl_[which.namespace].open; 321 openImpl(this, which.device, dev, openCb); 322 } 323 } 324}; 325 326/** 327 * Removes a client from a low-level gnubby. 328 * @param {GnubbyDevice} whichDev The gnubby. 329 * @param {*} who The client. 330 */ 331Gnubbies.prototype.removeClient = function(whichDev, who) { 332 console.log(UTIL_fmt('Gnubbies.removeClient()')); 333 334 this.resetInactivityTimer(); 335 336 // De-register client from all known devices. 337 for (var namespace in this.openDevs_) { 338 for (var devId in this.openDevs_[namespace]) { 339 var deviceId = Number(devId); 340 var dev = this.openDevs_[namespace][deviceId]; 341 if (dev.hasClient(who)) { 342 if (whichDev && dev != whichDev) { 343 console.warn('Gnubby attached to more than one device!?'); 344 } 345 if (!dev.deregisterClient(who)) { 346 dev.destroy(); 347 } 348 } 349 } 350 } 351}; 352