Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(684)

Side by Side Diff: chrome/renderer/resources/extensions/event.js

Issue 11571014: Lazy load chrome.* APIs (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: more progress Created 7 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 var DCHECK = requireNative('logging').DCHECK; 5 var DCHECK = requireNative('logging').DCHECK;
6 var eventBindingsNatives = requireNative('event_bindings'); 6 var eventBindingsNatives = requireNative('event_bindings');
7 var AttachEvent = eventBindingsNatives.AttachEvent; 7 var AttachEvent = eventBindingsNatives.AttachEvent;
8 var DetachEvent = eventBindingsNatives.DetachEvent; 8 var DetachEvent = eventBindingsNatives.DetachEvent;
9 var AttachFilteredEvent = eventBindingsNatives.AttachFilteredEvent; 9 var AttachFilteredEvent = eventBindingsNatives.AttachFilteredEvent;
10 var DetachFilteredEvent = eventBindingsNatives.DetachFilteredEvent; 10 var DetachFilteredEvent = eventBindingsNatives.DetachFilteredEvent;
11 var MatchAgainstEventFilter = eventBindingsNatives.MatchAgainstEventFilter; 11 var MatchAgainstEventFilter = eventBindingsNatives.MatchAgainstEventFilter;
12 var sendRequest = require('sendRequest').sendRequest; 12 var sendRequest = require('sendRequest').sendRequest;
13 var utils = require('utils'); 13 var utils = require('utils');
14 var validate = require('schemaUtils').validate; 14 var validate = require('schemaUtils').validate;
15 15
16 var chromeHidden = requireNative('chrome_hidden').GetChromeHidden(); 16 var chromeHidden = requireNative('chrome_hidden').GetChromeHidden();
17 var GetExtensionAPIDefinition = 17 var chrome = requireNative('chrome').GetChrome();
18 requireNative('apiDefinitions').GetExtensionAPIDefinition; 18 var schemaRegistry = requireNative('schema_registry');
19 19
20 // Schemas for the rule-style functions on the events API that 20 // Schemas for the rule-style functions on the events API that
21 // only need to be generated occasionally, so populate them lazily. 21 // only need to be generated occasionally, so populate them lazily.
22 var ruleFunctionSchemas = { 22 var ruleFunctionSchemas = {
23 // These values are set lazily: 23 // These values are set lazily:
24 // addRules: {}, 24 // addRules: {},
25 // getRules: {}, 25 // getRules: {},
26 // removeRules: {} 26 // removeRules: {}
27 }; 27 };
28 28
29 // This function ensures that |ruleFunctionSchemas| is populated. 29 // This function ensures that |ruleFunctionSchemas| is populated.
30 function ensureRuleSchemasLoaded() { 30 function ensureRuleSchemasLoaded() {
31 if (ruleFunctionSchemas.addRules) 31 if (ruleFunctionSchemas.addRules)
32 return; 32 return;
33 var eventsSchema = GetExtensionAPIDefinition("events")[0]; 33 var eventsSchema = schemaRegistry.GetSchema("events");
34 var eventType = utils.lookup(eventsSchema.types, 'id', 'events.Event'); 34 var eventType = utils.lookup(eventsSchema.types, 'id', 'events.Event');
35 35
36 ruleFunctionSchemas.addRules = 36 ruleFunctionSchemas.addRules =
37 utils.lookup(eventType.functions, 'name', 'addRules'); 37 utils.lookup(eventType.functions, 'name', 'addRules');
38 ruleFunctionSchemas.getRules = 38 ruleFunctionSchemas.getRules =
39 utils.lookup(eventType.functions, 'name', 'getRules'); 39 utils.lookup(eventType.functions, 'name', 'getRules');
40 ruleFunctionSchemas.removeRules = 40 ruleFunctionSchemas.removeRules =
41 utils.lookup(eventType.functions, 'name', 'removeRules'); 41 utils.lookup(eventType.functions, 'name', 'removeRules');
42 } 42 }
43 43
(...skipping 138 matching lines...) Expand 10 before | Expand all | Expand 10 after
182 // opt_eventName is required for events that support rules. 182 // opt_eventName is required for events that support rules.
183 // 183 //
184 // Example: 184 // Example:
185 // chrome.tabs.onChanged = new chrome.Event("tab-changed"); 185 // chrome.tabs.onChanged = new chrome.Event("tab-changed");
186 // chrome.tabs.onChanged.addListener(function(data) { alert(data); }); 186 // chrome.tabs.onChanged.addListener(function(data) { alert(data); });
187 // chromeHidden.Event.dispatch("tab-changed", "hi"); 187 // chromeHidden.Event.dispatch("tab-changed", "hi");
188 // will result in an alert dialog that says 'hi'. 188 // will result in an alert dialog that says 'hi'.
189 // 189 //
190 // If opt_eventOptions exists, it is a dictionary that contains the boolean 190 // If opt_eventOptions exists, it is a dictionary that contains the boolean
191 // entries "supportsListeners" and "supportsRules". 191 // entries "supportsListeners" and "supportsRules".
192 chrome.Event = function(opt_eventName, opt_argSchemas, opt_eventOptions) { 192 Event = function(opt_eventName, opt_argSchemas, opt_eventOptions) {
193 this.eventName_ = opt_eventName; 193 this.eventName_ = opt_eventName;
194 this.listeners_ = []; 194 this.listeners_ = [];
195 this.eventOptions_ = chromeHidden.parseEventOptions(opt_eventOptions); 195 this.eventOptions_ = chromeHidden.parseEventOptions(opt_eventOptions);
196 196
197 if (this.eventOptions_.supportsRules && !opt_eventName) 197 if (this.eventOptions_.supportsRules && !opt_eventName)
198 throw new Error("Events that support rules require an event name."); 198 throw new Error("Events that support rules require an event name.");
199 199
200 if (this.eventOptions_.supportsFilters) { 200 if (this.eventOptions_.supportsFilters) {
201 this.attachmentStrategy_ = new FilteredAttachmentStrategy(this); 201 this.attachmentStrategy_ = new FilteredAttachmentStrategy(this);
202 } else { 202 } else {
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
257 dispatchArgs(args); 257 dispatchArgs(args);
258 }; 258 };
259 259
260 // Test if a named event has any listeners. 260 // Test if a named event has any listeners.
261 chromeHidden.Event.hasListener = function(name) { 261 chromeHidden.Event.hasListener = function(name) {
262 return (attachedNamedEvents[name] && 262 return (attachedNamedEvents[name] &&
263 attachedNamedEvents[name].listeners_.length > 0); 263 attachedNamedEvents[name].listeners_.length > 0);
264 }; 264 };
265 265
266 // Registers a callback to be called when this event is dispatched. 266 // Registers a callback to be called when this event is dispatched.
267 chrome.Event.prototype.addListener = function(cb, filters) { 267 Event.prototype.addListener = function(cb, filters) {
268 if (!this.eventOptions_.supportsListeners) 268 if (!this.eventOptions_.supportsListeners)
269 throw new Error("This event does not support listeners."); 269 throw new Error("This event does not support listeners.");
270 if (this.eventOptions_.maxListeners && 270 if (this.eventOptions_.maxListeners &&
271 this.getListenerCount() >= this.eventOptions_.maxListeners) 271 this.getListenerCount() >= this.eventOptions_.maxListeners)
272 throw new Error("Too many listeners for " + this.eventName_); 272 throw new Error("Too many listeners for " + this.eventName_);
273 if (filters) { 273 if (filters) {
274 if (!this.eventOptions_.supportsFilters) 274 if (!this.eventOptions_.supportsFilters)
275 throw new Error("This event does not support filters."); 275 throw new Error("This event does not support filters.");
276 if (filters.url && !(filters.url instanceof Array)) 276 if (filters.url && !(filters.url instanceof Array))
277 throw new Error("filters.url should be an array"); 277 throw new Error("filters.url should be an array");
278 } 278 }
279 var listener = {callback: cb, filters: filters}; 279 var listener = {callback: cb, filters: filters};
280 this.attach_(listener); 280 this.attach_(listener);
281 this.listeners_.push(listener); 281 this.listeners_.push(listener);
282 }; 282 };
283 283
284 chrome.Event.prototype.attach_ = function(listener) { 284 Event.prototype.attach_ = function(listener) {
285 this.attachmentStrategy_.onAddedListener(listener); 285 this.attachmentStrategy_.onAddedListener(listener);
286 if (this.listeners_.length == 0) { 286 if (this.listeners_.length == 0) {
287 allAttachedEvents[allAttachedEvents.length] = this; 287 allAttachedEvents[allAttachedEvents.length] = this;
288 if (!this.eventName_) 288 if (!this.eventName_)
289 return; 289 return;
290 290
291 if (attachedNamedEvents[this.eventName_]) { 291 if (attachedNamedEvents[this.eventName_]) {
292 throw new Error("chrome.Event '" + this.eventName_ + 292 throw new Error("chrome.Event '" + this.eventName_ +
293 "' is already attached."); 293 "' is already attached.");
294 } 294 }
295 295
296 attachedNamedEvents[this.eventName_] = this; 296 attachedNamedEvents[this.eventName_] = this;
297 } 297 }
298 }; 298 };
299 299
300 // Unregisters a callback. 300 // Unregisters a callback.
301 chrome.Event.prototype.removeListener = function(cb) { 301 Event.prototype.removeListener = function(cb) {
302 if (!this.eventOptions_.supportsListeners) 302 if (!this.eventOptions_.supportsListeners)
303 throw new Error("This event does not support listeners."); 303 throw new Error("This event does not support listeners.");
304 var idx = this.findListener_(cb); 304 var idx = this.findListener_(cb);
305 if (idx == -1) { 305 if (idx == -1) {
306 return; 306 return;
307 } 307 }
308 308
309 var removedListener = this.listeners_.splice(idx, 1)[0]; 309 var removedListener = this.listeners_.splice(idx, 1)[0];
310 this.attachmentStrategy_.onRemovedListener(removedListener); 310 this.attachmentStrategy_.onRemovedListener(removedListener);
311 311
312 if (this.listeners_.length == 0) { 312 if (this.listeners_.length == 0) {
313 var i = allAttachedEvents.indexOf(this); 313 var i = allAttachedEvents.indexOf(this);
314 if (i >= 0) 314 if (i >= 0)
315 delete allAttachedEvents[i]; 315 delete allAttachedEvents[i];
316 if (!this.eventName_) 316 if (!this.eventName_)
317 return; 317 return;
318 318
319 if (!attachedNamedEvents[this.eventName_]) { 319 if (!attachedNamedEvents[this.eventName_]) {
320 throw new Error("chrome.Event '" + this.eventName_ + 320 throw new Error("chrome.Event '" + this.eventName_ +
321 "' is not attached."); 321 "' is not attached.");
322 } 322 }
323 323
324 delete attachedNamedEvents[this.eventName_]; 324 delete attachedNamedEvents[this.eventName_];
325 } 325 }
326 }; 326 };
327 327
328 // Test if the given callback is registered for this event. 328 // Test if the given callback is registered for this event.
329 chrome.Event.prototype.hasListener = function(cb) { 329 Event.prototype.hasListener = function(cb) {
330 if (!this.eventOptions_.supportsListeners) 330 if (!this.eventOptions_.supportsListeners)
331 throw new Error("This event does not support listeners."); 331 throw new Error("This event does not support listeners.");
332 return this.findListener_(cb) > -1; 332 return this.findListener_(cb) > -1;
333 }; 333 };
334 334
335 // Test if any callbacks are registered for this event. 335 // Test if any callbacks are registered for this event.
336 chrome.Event.prototype.hasListeners = function() { 336 Event.prototype.hasListeners = function() {
337 return this.getListenerCount() > 0; 337 return this.getListenerCount() > 0;
338 }; 338 };
339 339
340 // Return the number of listeners on this event. 340 // Return the number of listeners on this event.
341 chrome.Event.prototype.getListenerCount = function() { 341 Event.prototype.getListenerCount = function() {
342 if (!this.eventOptions_.supportsListeners) 342 if (!this.eventOptions_.supportsListeners)
343 throw new Error("This event does not support listeners."); 343 throw new Error("This event does not support listeners.");
344 return this.listeners_.length; 344 return this.listeners_.length;
345 }; 345 };
346 346
347 // Returns the index of the given callback if registered, or -1 if not 347 // Returns the index of the given callback if registered, or -1 if not
348 // found. 348 // found.
349 chrome.Event.prototype.findListener_ = function(cb) { 349 Event.prototype.findListener_ = function(cb) {
350 for (var i = 0; i < this.listeners_.length; i++) { 350 for (var i = 0; i < this.listeners_.length; i++) {
351 if (this.listeners_[i].callback == cb) { 351 if (this.listeners_[i].callback == cb) {
352 return i; 352 return i;
353 } 353 }
354 } 354 }
355 355
356 return -1; 356 return -1;
357 }; 357 };
358 358
359 chrome.Event.prototype.dispatch_ = function(args, listenerIDs) { 359 Event.prototype.dispatch_ = function(args, listenerIDs) {
360 if (!this.eventOptions_.supportsListeners) 360 if (!this.eventOptions_.supportsListeners)
361 throw new Error("This event does not support listeners."); 361 throw new Error("This event does not support listeners.");
362 var validationErrors = this.validateEventArgs_(args); 362 var validationErrors = this.validateEventArgs_(args);
363 if (validationErrors) { 363 if (validationErrors) {
364 console.error(validationErrors); 364 console.error(validationErrors);
365 return {validationErrors: validationErrors}; 365 return {validationErrors: validationErrors};
366 } 366 }
367 367
368 // Make a copy of the listeners in case the listener list is modified 368 // Make a copy of the listeners in case the listener list is modified
369 // while dispatching the event. 369 // while dispatching the event.
370 var listeners = 370 var listeners =
371 this.attachmentStrategy_.getListenersByIDs(listenerIDs).slice(); 371 this.attachmentStrategy_.getListenersByIDs(listenerIDs).slice();
372 372
373 var results = []; 373 var results = [];
374 for (var i = 0; i < listeners.length; i++) { 374 for (var i = 0; i < listeners.length; i++) {
375 try { 375 try {
376 var result = this.dispatchToListener(listeners[i].callback, args); 376 var result = this.dispatchToListener(listeners[i].callback, args);
377 if (result !== undefined) 377 if (result !== undefined)
378 results.push(result); 378 results.push(result);
379 } catch (e) { 379 } catch (e) {
380 console.error("Error in event handler for '" + this.eventName_ + 380 console.error("Error in event handler for '" + this.eventName_ +
381 "': " + e.message + ' ' + e.stack); 381 "': " + e.message + ' ' + e.stack);
382 } 382 }
383 } 383 }
384 if (results.length) 384 if (results.length)
385 return {results: results}; 385 return {results: results};
386 } 386 }
387 387
388 // Can be overridden to support custom dispatching. 388 // Can be overridden to support custom dispatching.
389 chrome.Event.prototype.dispatchToListener = function(callback, args) { 389 Event.prototype.dispatchToListener = function(callback, args) {
390 return callback.apply(null, args); 390 return callback.apply(null, args);
391 } 391 }
392 392
393 // Dispatches this event object to all listeners, passing all supplied 393 // Dispatches this event object to all listeners, passing all supplied
394 // arguments to this function each listener. 394 // arguments to this function each listener.
395 chrome.Event.prototype.dispatch = function(varargs) { 395 Event.prototype.dispatch = function(varargs) {
396 return this.dispatch_(Array.prototype.slice.call(arguments), undefined); 396 return this.dispatch_(Array.prototype.slice.call(arguments), undefined);
397 }; 397 };
398 398
399 // Detaches this event object from its name. 399 // Detaches this event object from its name.
400 chrome.Event.prototype.detach_ = function() { 400 Event.prototype.detach_ = function() {
401 this.attachmentStrategy_.detach(false); 401 this.attachmentStrategy_.detach(false);
402 }; 402 };
403 403
404 chrome.Event.prototype.destroy_ = function() { 404 Event.prototype.destroy_ = function() {
405 this.listeners_ = []; 405 this.listeners_ = [];
406 this.validateEventArgs_ = []; 406 this.validateEventArgs_ = [];
407 this.detach_(false); 407 this.detach_(false);
408 }; 408 };
409 409
410 chrome.Event.prototype.addRules = function(rules, opt_cb) { 410 Event.prototype.addRules = function(rules, opt_cb) {
411 if (!this.eventOptions_.supportsRules) 411 if (!this.eventOptions_.supportsRules)
412 throw new Error("This event does not support rules."); 412 throw new Error("This event does not support rules.");
413 413
414 // Takes a list of JSON datatype identifiers and returns a schema fragment 414 // Takes a list of JSON datatype identifiers and returns a schema fragment
415 // that verifies that a JSON object corresponds to an array of only these 415 // that verifies that a JSON object corresponds to an array of only these
416 // data types. 416 // data types.
417 function buildArrayOfChoicesSchema(typesList) { 417 function buildArrayOfChoicesSchema(typesList) {
418 return { 418 return {
419 'type': 'array', 419 'type': 'array',
420 'items': { 420 'items': {
(...skipping 29 matching lines...) Expand all
450 450
451 ensureRuleSchemasLoaded(); 451 ensureRuleSchemasLoaded();
452 // We remove the first parameter from the validation to give the user more 452 // We remove the first parameter from the validation to give the user more
453 // meaningful error messages. 453 // meaningful error messages.
454 validate([rules, opt_cb], 454 validate([rules, opt_cb],
455 ruleFunctionSchemas.addRules.parameters.slice().splice(1)); 455 ruleFunctionSchemas.addRules.parameters.slice().splice(1));
456 sendRequest("events.addRules", [this.eventName_, rules, opt_cb], 456 sendRequest("events.addRules", [this.eventName_, rules, opt_cb],
457 ruleFunctionSchemas.addRules.parameters); 457 ruleFunctionSchemas.addRules.parameters);
458 } 458 }
459 459
460 chrome.Event.prototype.removeRules = function(ruleIdentifiers, opt_cb) { 460 Event.prototype.removeRules = function(ruleIdentifiers, opt_cb) {
461 if (!this.eventOptions_.supportsRules) 461 if (!this.eventOptions_.supportsRules)
462 throw new Error("This event does not support rules."); 462 throw new Error("This event does not support rules.");
463 ensureRuleSchemasLoaded(); 463 ensureRuleSchemasLoaded();
464 // We remove the first parameter from the validation to give the user more 464 // We remove the first parameter from the validation to give the user more
465 // meaningful error messages. 465 // meaningful error messages.
466 validate([ruleIdentifiers, opt_cb], 466 validate([ruleIdentifiers, opt_cb],
467 ruleFunctionSchemas.removeRules.parameters.slice().splice(1)); 467 ruleFunctionSchemas.removeRules.parameters.slice().splice(1));
468 sendRequest("events.removeRules", 468 sendRequest("events.removeRules",
469 [this.eventName_, ruleIdentifiers, opt_cb], 469 [this.eventName_, ruleIdentifiers, opt_cb],
470 ruleFunctionSchemas.removeRules.parameters); 470 ruleFunctionSchemas.removeRules.parameters);
471 } 471 }
472 472
473 chrome.Event.prototype.getRules = function(ruleIdentifiers, cb) { 473 Event.prototype.getRules = function(ruleIdentifiers, cb) {
474 if (!this.eventOptions_.supportsRules) 474 if (!this.eventOptions_.supportsRules)
475 throw new Error("This event does not support rules."); 475 throw new Error("This event does not support rules.");
476 ensureRuleSchemasLoaded(); 476 ensureRuleSchemasLoaded();
477 // We remove the first parameter from the validation to give the user more 477 // We remove the first parameter from the validation to give the user more
478 // meaningful error messages. 478 // meaningful error messages.
479 validate([ruleIdentifiers, cb], 479 validate([ruleIdentifiers, cb],
480 ruleFunctionSchemas.getRules.parameters.slice().splice(1)); 480 ruleFunctionSchemas.getRules.parameters.slice().splice(1));
481 481
482 sendRequest("events.getRules", 482 sendRequest("events.getRules",
483 [this.eventName_, ruleIdentifiers, cb], 483 [this.eventName_, ruleIdentifiers, cb],
484 ruleFunctionSchemas.getRules.parameters); 484 ruleFunctionSchemas.getRules.parameters);
485 } 485 }
486 486
487 // Special load events: we don't use the DOM unload because that slows 487 // Special load events: we don't use the DOM unload because that slows
488 // down tab shutdown. On the other hand, onUnload might not always fire, 488 // down tab shutdown. On the other hand, onUnload might not always fire,
489 // since Chrome will terminate renderers on shutdown (SuddenTermination). 489 // since Chrome will terminate renderers on shutdown (SuddenTermination).
490 chromeHidden.onLoad = new chrome.Event(); 490 chromeHidden.onLoad = new Event();
491 chromeHidden.onUnload = new chrome.Event(); 491 chromeHidden.onUnload = new Event();
492 492
493 chromeHidden.dispatchOnLoad = 493 chromeHidden.dispatchOnLoad =
494 chromeHidden.onLoad.dispatch.bind(chromeHidden.onLoad); 494 chromeHidden.onLoad.dispatch.bind(chromeHidden.onLoad);
495 495
496 chromeHidden.dispatchOnUnload = function() { 496 chromeHidden.dispatchOnUnload = function() {
497 chromeHidden.onUnload.dispatch(); 497 chromeHidden.onUnload.dispatch();
498 for (var i = 0; i < allAttachedEvents.length; ++i) { 498 for (var i = 0; i < allAttachedEvents.length; ++i) {
499 var event = allAttachedEvents[i]; 499 var event = allAttachedEvents[i];
500 if (event) 500 if (event)
501 event.detach_(); 501 event.detach_();
502 } 502 }
503 }; 503 };
504 504
505 chromeHidden.dispatchError = function(msg) { 505 chromeHidden.dispatchError = function(msg) {
506 console.error(msg); 506 console.error(msg);
507 }; 507 };
508 508
509 exports.Event = chrome.Event; 509 exports.bindings = Event;
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698