- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / renderer / resources / extensions / event.js
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
3 // found in the LICENSE file.
4
5   var eventNatives = requireNative('event_natives');
6   var logging = requireNative('logging');
7   var schemaRegistry = requireNative('schema_registry');
8   var sendRequest = require('sendRequest').sendRequest;
9   var utils = require('utils');
10   var validate = require('schemaUtils').validate;
11   var unloadEvent = require('unload_event');
12
13   // Schemas for the rule-style functions on the events API that
14   // only need to be generated occasionally, so populate them lazily.
15   var ruleFunctionSchemas = {
16     // These values are set lazily:
17     // addRules: {},
18     // getRules: {},
19     // removeRules: {}
20   };
21
22   // This function ensures that |ruleFunctionSchemas| is populated.
23   function ensureRuleSchemasLoaded() {
24     if (ruleFunctionSchemas.addRules)
25       return;
26     var eventsSchema = schemaRegistry.GetSchema("events");
27     var eventType = utils.lookup(eventsSchema.types, 'id', 'events.Event');
28
29     ruleFunctionSchemas.addRules =
30         utils.lookup(eventType.functions, 'name', 'addRules');
31     ruleFunctionSchemas.getRules =
32         utils.lookup(eventType.functions, 'name', 'getRules');
33     ruleFunctionSchemas.removeRules =
34         utils.lookup(eventType.functions, 'name', 'removeRules');
35   }
36
37   // A map of event names to the event object that is registered to that name.
38   var attachedNamedEvents = {};
39
40   // An array of all attached event objects, used for detaching on unload.
41   var allAttachedEvents = [];
42
43   // A map of functions that massage event arguments before they are dispatched.
44   // Key is event name, value is function.
45   var eventArgumentMassagers = {};
46
47   // An attachment strategy for events that aren't attached to the browser.
48   // This applies to events with the "unmanaged" option and events without
49   // names.
50   var NullAttachmentStrategy = function(event) {
51     this.event_ = event;
52   };
53   NullAttachmentStrategy.prototype.onAddedListener =
54       function(listener) {
55   };
56   NullAttachmentStrategy.prototype.onRemovedListener =
57       function(listener) {
58   };
59   NullAttachmentStrategy.prototype.detach = function(manual) {
60   };
61   NullAttachmentStrategy.prototype.getListenersByIDs = function(ids) {
62     // |ids| is for filtered events only.
63     return this.event_.listeners_;
64   };
65
66   // Handles adding/removing/dispatching listeners for unfiltered events.
67   var UnfilteredAttachmentStrategy = function(event) {
68     this.event_ = event;
69   };
70
71   UnfilteredAttachmentStrategy.prototype.onAddedListener =
72       function(listener) {
73     // Only attach / detach on the first / last listener removed.
74     if (this.event_.listeners_.length == 0)
75       eventNatives.AttachEvent(this.event_.eventName_);
76   };
77
78   UnfilteredAttachmentStrategy.prototype.onRemovedListener =
79       function(listener) {
80     if (this.event_.listeners_.length == 0)
81       this.detach(true);
82   };
83
84   UnfilteredAttachmentStrategy.prototype.detach = function(manual) {
85     eventNatives.DetachEvent(this.event_.eventName_, manual);
86   };
87
88   UnfilteredAttachmentStrategy.prototype.getListenersByIDs = function(ids) {
89     // |ids| is for filtered events only.
90     return this.event_.listeners_;
91   };
92
93   var FilteredAttachmentStrategy = function(event) {
94     this.event_ = event;
95     this.listenerMap_ = {};
96   };
97
98   FilteredAttachmentStrategy.idToEventMap = {};
99
100   FilteredAttachmentStrategy.prototype.onAddedListener = function(listener) {
101     var id = eventNatives.AttachFilteredEvent(this.event_.eventName_,
102                                               listener.filters || {});
103     if (id == -1)
104       throw new Error("Can't add listener");
105     listener.id = id;
106     this.listenerMap_[id] = listener;
107     FilteredAttachmentStrategy.idToEventMap[id] = this.event_;
108   };
109
110   FilteredAttachmentStrategy.prototype.onRemovedListener = function(listener) {
111     this.detachListener(listener, true);
112   };
113
114   FilteredAttachmentStrategy.prototype.detachListener =
115       function(listener, manual) {
116     if (listener.id == undefined)
117       throw new Error("listener.id undefined - '" + listener + "'");
118     var id = listener.id;
119     delete this.listenerMap_[id];
120     delete FilteredAttachmentStrategy.idToEventMap[id];
121     eventNatives.DetachFilteredEvent(id, manual);
122   };
123
124   FilteredAttachmentStrategy.prototype.detach = function(manual) {
125     for (var i in this.listenerMap_)
126       this.detachListener(this.listenerMap_[i], manual);
127   };
128
129   FilteredAttachmentStrategy.prototype.getListenersByIDs = function(ids) {
130     var result = [];
131     for (var i = 0; i < ids.length; i++)
132       $Array.push(result, this.listenerMap_[ids[i]]);
133     return result;
134   };
135
136   function parseEventOptions(opt_eventOptions) {
137     function merge(dest, src) {
138       for (var k in src) {
139         if (!$Object.hasOwnProperty(dest, k)) {
140           dest[k] = src[k];
141         }
142       }
143     }
144
145     var options = opt_eventOptions || {};
146     merge(options, {
147       // Event supports adding listeners with filters ("filtered events"), for
148       // example as used in the webNavigation API.
149       //
150       // event.addListener(listener, [filter1, filter2]);
151       supportsFilters: false,
152
153       // Events supports vanilla events. Most APIs use these.
154       //
155       // event.addListener(listener);
156       supportsListeners: true,
157
158       // Event supports adding rules ("declarative events") rather than
159       // listeners, for example as used in the declarativeWebRequest API.
160       //
161       // event.addRules([rule1, rule2]);
162       supportsRules: false,
163
164       // Event is unmanaged in that the browser has no knowledge of its
165       // existence; it's never invoked, doesn't keep the renderer alive, and
166       // the bindings system has no knowledge of it.
167       //
168       // Both events created by user code (new chrome.Event()) and messaging
169       // events are unmanaged, though in the latter case the browser *does*
170       // interact indirectly with them via IPCs written by hand.
171       unmanaged: false,
172     });
173     return options;
174   };
175
176   // Event object.  If opt_eventName is provided, this object represents
177   // the unique instance of that named event, and dispatching an event
178   // with that name will route through this object's listeners. Note that
179   // opt_eventName is required for events that support rules.
180   //
181   // Example:
182   //   var Event = require('event_bindings').Event;
183   //   chrome.tabs.onChanged = new Event("tab-changed");
184   //   chrome.tabs.onChanged.addListener(function(data) { alert(data); });
185   //   Event.dispatch("tab-changed", "hi");
186   // will result in an alert dialog that says 'hi'.
187   //
188   // If opt_eventOptions exists, it is a dictionary that contains the boolean
189   // entries "supportsListeners" and "supportsRules".
190   var Event = function(opt_eventName, opt_argSchemas, opt_eventOptions) {
191     this.eventName_ = opt_eventName;
192     this.argSchemas_ = opt_argSchemas;
193     this.listeners_ = [];
194     this.eventOptions_ = parseEventOptions(opt_eventOptions);
195
196     if (!this.eventName_) {
197       if (this.eventOptions_.supportsRules)
198         throw new Error("Events that support rules require an event name.");
199       // Events without names cannot be managed by the browser by definition
200       // (the browser has no way of identifying them).
201       this.eventOptions_.unmanaged = true;
202     }
203
204     // Track whether the event has been destroyed to help track down the cause
205     // of http://crbug.com/258526.
206     // This variable will eventually hold the stack trace of the destroy call.
207     // TODO(kalman): Delete this and replace with more sound logic that catches
208     // when events are used without being *attached*.
209     this.destroyed_ = null;
210
211     if (this.eventOptions_.unmanaged)
212       this.attachmentStrategy_ = new NullAttachmentStrategy(this);
213     else if (this.eventOptions_.supportsFilters)
214       this.attachmentStrategy_ = new FilteredAttachmentStrategy(this);
215     else
216       this.attachmentStrategy_ = new UnfilteredAttachmentStrategy(this);
217   };
218
219   // callback is a function(args, dispatch). args are the args we receive from
220   // dispatchEvent(), and dispatch is a function(args) that dispatches args to
221   // its listeners.
222   function registerArgumentMassager(name, callback) {
223     if (eventArgumentMassagers[name])
224       throw new Error("Massager already registered for event: " + name);
225     eventArgumentMassagers[name] = callback;
226   }
227
228   // Dispatches a named event with the given argument array. The args array is
229   // the list of arguments that will be sent to the event callback.
230   function dispatchEvent(name, args, filteringInfo) {
231     var listenerIDs = [];
232
233     if (filteringInfo)
234       listenerIDs = eventNatives.MatchAgainstEventFilter(name, filteringInfo);
235
236     var event = attachedNamedEvents[name];
237     if (!event)
238       return;
239
240     var dispatchArgs = function(args) {
241       var result = event.dispatch_(args, listenerIDs);
242       if (result)
243         logging.DCHECK(!result.validationErrors, result.validationErrors);
244       return result;
245     };
246
247     if (eventArgumentMassagers[name])
248       eventArgumentMassagers[name](args, dispatchArgs);
249     else
250       dispatchArgs(args);
251   }
252
253   // Registers a callback to be called when this event is dispatched.
254   Event.prototype.addListener = function(cb, filters) {
255     if (!this.eventOptions_.supportsListeners)
256       throw new Error("This event does not support listeners.");
257     if (this.eventOptions_.maxListeners &&
258         this.getListenerCount() >= this.eventOptions_.maxListeners) {
259       throw new Error("Too many listeners for " + this.eventName_);
260     }
261     if (filters) {
262       if (!this.eventOptions_.supportsFilters)
263         throw new Error("This event does not support filters.");
264       if (filters.url && !(filters.url instanceof Array))
265         throw new Error("filters.url should be an array.");
266       if (filters.serviceType &&
267           !(typeof filters.serviceType === 'string')) {
268         throw new Error("filters.serviceType should be a string.")
269       }
270     }
271     var listener = {callback: cb, filters: filters};
272     this.attach_(listener);
273     $Array.push(this.listeners_, listener);
274   };
275
276   Event.prototype.attach_ = function(listener) {
277     this.attachmentStrategy_.onAddedListener(listener);
278
279     if (this.listeners_.length == 0) {
280       allAttachedEvents[allAttachedEvents.length] = this;
281       if (this.eventName_) {
282         if (attachedNamedEvents[this.eventName_]) {
283           throw new Error("Event '" + this.eventName_ +
284                           "' is already attached.");
285         }
286         attachedNamedEvents[this.eventName_] = this;
287       }
288     }
289   };
290
291   // Unregisters a callback.
292   Event.prototype.removeListener = function(cb) {
293     if (!this.eventOptions_.supportsListeners)
294       throw new Error("This event does not support listeners.");
295
296     var idx = this.findListener_(cb);
297     if (idx == -1)
298       return;
299
300     var removedListener = $Array.splice(this.listeners_, idx, 1)[0];
301     this.attachmentStrategy_.onRemovedListener(removedListener);
302
303     if (this.listeners_.length == 0) {
304       var i = allAttachedEvents.indexOf(this);
305       if (i >= 0)
306         delete allAttachedEvents[i];
307       if (this.eventName_) {
308         if (!attachedNamedEvents[this.eventName_])
309           throw new Error("Event '" + this.eventName_ + "' is not attached.");
310         delete attachedNamedEvents[this.eventName_];
311       }
312     }
313   };
314
315   // Test if the given callback is registered for this event.
316   Event.prototype.hasListener = function(cb) {
317     if (!this.eventOptions_.supportsListeners)
318       throw new Error("This event does not support listeners.");
319     return this.findListener_(cb) > -1;
320   };
321
322   // Test if any callbacks are registered for this event.
323   Event.prototype.hasListeners = function() {
324     return this.getListenerCount() > 0;
325   };
326
327   // Return the number of listeners on this event.
328   Event.prototype.getListenerCount = function() {
329     if (!this.eventOptions_.supportsListeners)
330       throw new Error("This event does not support listeners.");
331     return this.listeners_.length;
332   };
333
334   // Returns the index of the given callback if registered, or -1 if not
335   // found.
336   Event.prototype.findListener_ = function(cb) {
337     for (var i = 0; i < this.listeners_.length; i++) {
338       if (this.listeners_[i].callback == cb) {
339         return i;
340       }
341     }
342
343     return -1;
344   };
345
346   Event.prototype.dispatch_ = function(args, listenerIDs) {
347     if (this.destroyed_) {
348       throw new Error(this.eventName_ + ' was already destroyed at: ' +
349                       this.destroyed_);
350     }
351     if (!this.eventOptions_.supportsListeners)
352       throw new Error("This event does not support listeners.");
353
354     if (this.argSchemas_ && logging.DCHECK_IS_ON()) {
355       try {
356         validate(args, this.argSchemas_);
357       } catch (e) {
358         e.message += ' in ' + this.eventName_;
359         throw e;
360       }
361     }
362
363     // Make a copy of the listeners in case the listener list is modified
364     // while dispatching the event.
365     var listeners = $Array.slice(
366         this.attachmentStrategy_.getListenersByIDs(listenerIDs));
367
368     var results = [];
369     for (var i = 0; i < listeners.length; i++) {
370       try {
371         var result = this.dispatchToListener(listeners[i].callback, args);
372         if (result !== undefined)
373           $Array.push(results, result);
374       } catch (e) {
375         console.error('Error in event handler for ' +
376                       (this.eventName_ ? this.eventName_ : '(unknown)') +
377                       ': ' + e.stack);
378       }
379     }
380     if (results.length)
381       return {results: results};
382   }
383
384   // Can be overridden to support custom dispatching.
385   Event.prototype.dispatchToListener = function(callback, args) {
386     return $Function.apply(callback, null, args);
387   }
388
389   // Dispatches this event object to all listeners, passing all supplied
390   // arguments to this function each listener.
391   Event.prototype.dispatch = function(varargs) {
392     return this.dispatch_($Array.slice(arguments), undefined);
393   };
394
395   // Detaches this event object from its name.
396   Event.prototype.detach_ = function() {
397     this.attachmentStrategy_.detach(false);
398   };
399
400   Event.prototype.destroy_ = function() {
401     this.listeners_.length = 0;
402     this.detach_();
403     this.destroyed_ = new Error().stack;
404   };
405
406   Event.prototype.addRules = function(rules, opt_cb) {
407     if (!this.eventOptions_.supportsRules)
408       throw new Error("This event does not support rules.");
409
410     // Takes a list of JSON datatype identifiers and returns a schema fragment
411     // that verifies that a JSON object corresponds to an array of only these
412     // data types.
413     function buildArrayOfChoicesSchema(typesList) {
414       return {
415         'type': 'array',
416         'items': {
417           'choices': typesList.map(function(el) {return {'$ref': el};})
418         }
419       };
420     };
421
422     // Validate conditions and actions against specific schemas of this
423     // event object type.
424     // |rules| is an array of JSON objects that follow the Rule type of the
425     // declarative extension APIs. |conditions| is an array of JSON type
426     // identifiers that are allowed to occur in the conditions attribute of each
427     // rule. Likewise, |actions| is an array of JSON type identifiers that are
428     // allowed to occur in the actions attribute of each rule.
429     function validateRules(rules, conditions, actions) {
430       var conditionsSchema = buildArrayOfChoicesSchema(conditions);
431       var actionsSchema = buildArrayOfChoicesSchema(actions);
432       $Array.forEach(rules, function(rule) {
433         validate([rule.conditions], [conditionsSchema]);
434         validate([rule.actions], [actionsSchema]);
435       });
436     };
437
438     if (!this.eventOptions_.conditions || !this.eventOptions_.actions) {
439       throw new Error('Event ' + this.eventName_ + ' misses conditions or ' +
440                       'actions in the API specification.');
441     }
442
443     validateRules(rules,
444                   this.eventOptions_.conditions,
445                   this.eventOptions_.actions);
446
447     ensureRuleSchemasLoaded();
448     // We remove the first parameter from the validation to give the user more
449     // meaningful error messages.
450     validate([rules, opt_cb],
451              $Array.splice(
452                  $Array.slice(ruleFunctionSchemas.addRules.parameters), 1));
453     sendRequest("events.addRules", [this.eventName_, rules, opt_cb],
454                 ruleFunctionSchemas.addRules.parameters);
455   }
456
457   Event.prototype.removeRules = function(ruleIdentifiers, opt_cb) {
458     if (!this.eventOptions_.supportsRules)
459       throw new Error("This event does not support rules.");
460     ensureRuleSchemasLoaded();
461     // We remove the first parameter from the validation to give the user more
462     // meaningful error messages.
463     validate([ruleIdentifiers, opt_cb],
464              $Array.splice(
465                  $Array.slice(ruleFunctionSchemas.removeRules.parameters), 1));
466     sendRequest("events.removeRules",
467                 [this.eventName_, ruleIdentifiers, opt_cb],
468                 ruleFunctionSchemas.removeRules.parameters);
469   }
470
471   Event.prototype.getRules = function(ruleIdentifiers, cb) {
472     if (!this.eventOptions_.supportsRules)
473       throw new Error("This event does not support rules.");
474     ensureRuleSchemasLoaded();
475     // We remove the first parameter from the validation to give the user more
476     // meaningful error messages.
477     validate([ruleIdentifiers, cb],
478              $Array.splice(
479                  $Array.slice(ruleFunctionSchemas.getRules.parameters), 1));
480
481     sendRequest("events.getRules",
482                 [this.eventName_, ruleIdentifiers, cb],
483                 ruleFunctionSchemas.getRules.parameters);
484   }
485
486   unloadEvent.addListener(function() {
487     for (var i = 0; i < allAttachedEvents.length; ++i) {
488       var event = allAttachedEvents[i];
489       if (event)
490         event.detach_();
491     }
492   });
493
494   // NOTE: Event is (lazily) exposed as chrome.Event from dispatcher.cc.
495   exports.Event = Event;
496
497   exports.dispatchEvent = dispatchEvent;
498   exports.parseEventOptions = parseEventOptions;
499   exports.registerArgumentMassager = registerArgumentMassager;