OLD | NEW |
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 eventBindingsNatives = requireNative('event_bindings'); | 5 var eventBindingsNatives = requireNative('event_bindings'); |
6 var AttachEvent = eventBindingsNatives.AttachEvent; | 6 var AttachEvent = eventBindingsNatives.AttachEvent; |
7 var DetachEvent = eventBindingsNatives.DetachEvent; | 7 var DetachEvent = eventBindingsNatives.DetachEvent; |
| 8 var AttachFilteredEvent = eventBindingsNatives.AttachFilteredEvent; |
| 9 var DetachFilteredEvent = eventBindingsNatives.DetachFilteredEvent; |
| 10 var MatchAgainstEventFilter = eventBindingsNatives.MatchAgainstEventFilter; |
8 var sendRequest = require('sendRequest').sendRequest; | 11 var sendRequest = require('sendRequest').sendRequest; |
9 var utils = require('utils'); | 12 var utils = require('utils'); |
10 var validate = require('schemaUtils').validate; | 13 var validate = require('schemaUtils').validate; |
11 | 14 |
12 var chromeHidden = requireNative('chrome_hidden').GetChromeHidden(); | 15 var chromeHidden = requireNative('chrome_hidden').GetChromeHidden(); |
13 var GetExtensionAPIDefinition = | 16 var GetExtensionAPIDefinition = |
14 requireNative('apiDefinitions').GetExtensionAPIDefinition; | 17 requireNative('apiDefinitions').GetExtensionAPIDefinition; |
15 | 18 |
16 // Schemas for the rule-style functions on the events API that | 19 // Schemas for the rule-style functions on the events API that |
17 // only need to be generated occasionally, so populate them lazily. | 20 // only need to be generated occasionally, so populate them lazily. |
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
68 $Array.prototype.toJSON = customizedArrayToJSON; | 71 $Array.prototype.toJSON = customizedArrayToJSON; |
69 } | 72 } |
70 } | 73 } |
71 }; | 74 }; |
72 | 75 |
73 this.parse = function(thing) { | 76 this.parse = function(thing) { |
74 return $jsonParse(thing); | 77 return $jsonParse(thing); |
75 }; | 78 }; |
76 })(); | 79 })(); |
77 | 80 |
| 81 // Handles adding/removing/dispatching listeners for unfiltered events. |
| 82 var UnfilteredAttachmentStrategy = function(event) { |
| 83 this.event_ = event; |
| 84 }; |
| 85 |
| 86 UnfilteredAttachmentStrategy.prototype.onAddedListener = |
| 87 function(listener) { |
| 88 // Only attach / detach on the first / last listener removed. |
| 89 if (this.event_.listeners_.length == 0) |
| 90 AttachEvent(this.event_.eventName_); |
| 91 }; |
| 92 |
| 93 UnfilteredAttachmentStrategy.prototype.onRemovedListener = |
| 94 function(listener) { |
| 95 if (this.event_.listeners_.length == 0) |
| 96 this.detach(true); |
| 97 }; |
| 98 |
| 99 UnfilteredAttachmentStrategy.prototype.detach = function(manual) { |
| 100 var i = allAttachedEvents.indexOf(this.event_); |
| 101 if (i >= 0) |
| 102 delete allAttachedEvents[i]; |
| 103 DetachEvent(this.event_.eventName_, manual); |
| 104 }; |
| 105 |
| 106 UnfilteredAttachmentStrategy.prototype.getListenersByIDs = function(ids) { |
| 107 return this.event_.listeners_; |
| 108 }; |
| 109 |
| 110 var FilteredAttachmentStrategy = function(event) { |
| 111 this.event_ = event; |
| 112 this.listenerMap_ = {}; |
| 113 }; |
| 114 |
| 115 FilteredAttachmentStrategy.idToEventMap = {}; |
| 116 |
| 117 FilteredAttachmentStrategy.prototype.onAddedListener = function(listener) { |
| 118 var id = AttachFilteredEvent(this.event_.eventName_, |
| 119 listener.filters || {}); |
| 120 listener.id = id; |
| 121 this.listenerMap_[id] = listener; |
| 122 FilteredAttachmentStrategy.idToEventMap[id] = this.event_; |
| 123 }; |
| 124 |
| 125 FilteredAttachmentStrategy.prototype.onRemovedListener = function(listener) { |
| 126 this.detachListener(listener, true); |
| 127 }; |
| 128 |
| 129 FilteredAttachmentStrategy.prototype.detachListener = |
| 130 function(listener, manual) { |
| 131 if (listener.id == undefined) |
| 132 throw new Error("listener.id undefined - '" + listener + "'"); |
| 133 var id = listener.id; |
| 134 delete this.listenerMap_[id]; |
| 135 delete FilteredAttachmentStrategy.idToEventMap[id]; |
| 136 DetachFilteredEvent(id, manual); |
| 137 }; |
| 138 |
| 139 FilteredAttachmentStrategy.prototype.detach = function(manual) { |
| 140 for (var i in this.listenerMap_) |
| 141 this.detachListener(this.listenerMap_[i], manual); |
| 142 }; |
| 143 |
| 144 FilteredAttachmentStrategy.prototype.getListenersByIDs = function(ids) { |
| 145 var result = []; |
| 146 for (var i = 0; i < ids.length; i++) |
| 147 result.push(this.listenerMap_[ids[i]]); |
| 148 return result; |
| 149 }; |
| 150 |
78 // Event object. If opt_eventName is provided, this object represents | 151 // Event object. If opt_eventName is provided, this object represents |
79 // the unique instance of that named event, and dispatching an event | 152 // the unique instance of that named event, and dispatching an event |
80 // with that name will route through this object's listeners. Note that | 153 // with that name will route through this object's listeners. Note that |
81 // opt_eventName is required for events that support rules. | 154 // opt_eventName is required for events that support rules. |
82 // | 155 // |
83 // Example: | 156 // Example: |
84 // chrome.tabs.onChanged = new chrome.Event("tab-changed"); | 157 // chrome.tabs.onChanged = new chrome.Event("tab-changed"); |
85 // chrome.tabs.onChanged.addListener(function(data) { alert(data); }); | 158 // chrome.tabs.onChanged.addListener(function(data) { alert(data); }); |
86 // chromeHidden.Event.dispatch("tab-changed", "hi"); | 159 // chromeHidden.Event.dispatch("tab-changed", "hi"); |
87 // will result in an alert dialog that says 'hi'. | 160 // will result in an alert dialog that says 'hi'. |
88 // | 161 // |
89 // If opt_eventOptions exists, it is a dictionary that contains the boolean | 162 // If opt_eventOptions exists, it is a dictionary that contains the boolean |
90 // entries "supportsListeners" and "supportsRules". | 163 // entries "supportsListeners" and "supportsRules". |
91 chrome.Event = function(opt_eventName, opt_argSchemas, opt_eventOptions) { | 164 chrome.Event = function(opt_eventName, opt_argSchemas, opt_eventOptions) { |
92 this.eventName_ = opt_eventName; | 165 this.eventName_ = opt_eventName; |
93 this.listeners_ = []; | 166 this.listeners_ = []; |
94 this.eventOptions_ = opt_eventOptions || | 167 this.eventOptions_ = opt_eventOptions || |
95 {"supportsListeners": true, "supportsRules": false}; | 168 {supportsFilters: false, |
| 169 supportsListeners: true, |
| 170 supportsRules: false, |
| 171 }; |
96 | 172 |
97 if (this.eventOptions_.supportsRules && !opt_eventName) | 173 if (this.eventOptions_.supportsRules && !opt_eventName) |
98 throw new Error("Events that support rules require an event name."); | 174 throw new Error("Events that support rules require an event name."); |
99 | 175 |
| 176 if (this.eventOptions_.supportsFilters) { |
| 177 this.attachmentStrategy_ = new FilteredAttachmentStrategy(this); |
| 178 } else { |
| 179 this.attachmentStrategy_ = new UnfilteredAttachmentStrategy(this); |
| 180 } |
| 181 |
100 // Validate event arguments (the data that is passed to the callbacks) | 182 // Validate event arguments (the data that is passed to the callbacks) |
101 // if we are in debug. | 183 // if we are in debug. |
102 if (opt_argSchemas && | 184 if (opt_argSchemas && |
103 chromeHidden.validateCallbacks) { | 185 chromeHidden.validateCallbacks) { |
104 | 186 |
105 this.validateEventArgs_ = function(args) { | 187 this.validateEventArgs_ = function(args) { |
106 try { | 188 try { |
107 validate(args, opt_argSchemas); | 189 validate(args, opt_argSchemas); |
108 } catch (exception) { | 190 } catch (exception) { |
109 return "Event validation error during " + opt_eventName + " -- " + | 191 return "Event validation error during " + opt_eventName + " -- " + |
(...skipping 19 matching lines...) Expand all Loading... |
129 | 211 |
130 chromeHidden.Event.registerArgumentMassager = function(name, fn) { | 212 chromeHidden.Event.registerArgumentMassager = function(name, fn) { |
131 if (eventArgumentMassagers[name]) | 213 if (eventArgumentMassagers[name]) |
132 throw new Error("Massager already registered for event: " + name); | 214 throw new Error("Massager already registered for event: " + name); |
133 eventArgumentMassagers[name] = fn; | 215 eventArgumentMassagers[name] = fn; |
134 }; | 216 }; |
135 | 217 |
136 // Dispatches a named event with the given JSON array, which is deserialized | 218 // Dispatches a named event with the given JSON array, which is deserialized |
137 // before dispatch. The JSON array is the list of arguments that will be | 219 // before dispatch. The JSON array is the list of arguments that will be |
138 // sent with the event callback. | 220 // sent with the event callback. |
139 chromeHidden.Event.dispatchJSON = function(name, args) { | 221 chromeHidden.Event.dispatchJSON = function(name, args, filteringInfo) { |
| 222 var listenerIDs; |
| 223 |
| 224 if (filteringInfo) { |
| 225 listenerIDs = MatchAgainstEventFilter(name, filteringInfo); |
| 226 } |
140 if (attachedNamedEvents[name]) { | 227 if (attachedNamedEvents[name]) { |
141 if (args) { | 228 if (args) { |
142 // TODO(asargent): This is an antiquity. Until all callers of | 229 // TODO(asargent): This is an antiquity. Until all callers of |
143 // dispatchJSON use actual values, this must remain here to catch the | 230 // dispatchJSON use actual values, this must remain here to catch the |
144 // cases where a caller has hard-coded a JSON string to pass in. | 231 // cases where a caller has hard-coded a JSON string to pass in. |
145 if (typeof(args) == "string") { | 232 if (typeof(args) == "string") { |
146 args = chromeHidden.JSON.parse(args); | 233 args = chromeHidden.JSON.parse(args); |
147 } | 234 } |
148 if (eventArgumentMassagers[name]) | 235 if (eventArgumentMassagers[name]) |
149 eventArgumentMassagers[name](args); | 236 eventArgumentMassagers[name](args); |
150 } | 237 } |
151 var result = attachedNamedEvents[name].dispatch.apply( | 238 var result = attachedNamedEvents[name].dispatch_(args, listenerIDs); |
152 attachedNamedEvents[name], args); | |
153 if (result && result.validationErrors) | 239 if (result && result.validationErrors) |
154 return result.validationErrors; | 240 return result.validationErrors; |
155 } | 241 } |
156 }; | 242 }; |
157 | 243 |
158 // Dispatches a named event with the given arguments, supplied as an array. | 244 // Dispatches a named event with the given arguments, supplied as an array. |
159 chromeHidden.Event.dispatch = function(name, args) { | 245 chromeHidden.Event.dispatch = function(name, args) { |
160 if (attachedNamedEvents[name]) { | 246 if (attachedNamedEvents[name]) { |
161 attachedNamedEvents[name].dispatch.apply( | 247 attachedNamedEvents[name].dispatch.apply( |
162 attachedNamedEvents[name], args); | 248 attachedNamedEvents[name], args); |
163 } | 249 } |
164 }; | 250 }; |
165 | 251 |
166 // Test if a named event has any listeners. | 252 // Test if a named event has any listeners. |
167 chromeHidden.Event.hasListener = function(name) { | 253 chromeHidden.Event.hasListener = function(name) { |
168 return (attachedNamedEvents[name] && | 254 return (attachedNamedEvents[name] && |
169 attachedNamedEvents[name].listeners_.length > 0); | 255 attachedNamedEvents[name].listeners_.length > 0); |
170 }; | 256 }; |
171 | 257 |
172 // Registers a callback to be called when this event is dispatched. | 258 // Registers a callback to be called when this event is dispatched. |
173 chrome.Event.prototype.addListener = function(cb) { | 259 chrome.Event.prototype.addListener = function(cb, filters) { |
174 if (!this.eventOptions_.supportsListeners) | 260 if (!this.eventOptions_.supportsListeners) |
175 throw new Error("This event does not support listeners."); | 261 throw new Error("This event does not support listeners."); |
| 262 if (filters) { |
| 263 if (!this.eventOptions_.supportsFilters) |
| 264 throw new Error("This event does not support filters."); |
| 265 if (filters.url && !(filters.url instanceof Array)) |
| 266 throw new Error("filters.url should be an array"); |
| 267 } |
| 268 var listener = {callback: cb, filters: filters}; |
| 269 this.attach_(listener); |
| 270 this.listeners_.push(listener); |
| 271 }; |
| 272 |
| 273 chrome.Event.prototype.attach_ = function(listener) { |
| 274 this.attachmentStrategy_.onAddedListener(listener); |
176 if (this.listeners_.length == 0) { | 275 if (this.listeners_.length == 0) { |
177 this.attach_(); | 276 allAttachedEvents[allAttachedEvents.length] = this; |
| 277 if (!this.eventName_) |
| 278 return; |
| 279 |
| 280 if (attachedNamedEvents[this.eventName_]) { |
| 281 throw new Error("chrome.Event '" + this.eventName_ + |
| 282 "' is already attached."); |
| 283 } |
| 284 |
| 285 attachedNamedEvents[this.eventName_] = this; |
178 } | 286 } |
179 this.listeners_.push(cb); | |
180 }; | 287 }; |
181 | 288 |
182 // Unregisters a callback. | 289 // Unregisters a callback. |
183 chrome.Event.prototype.removeListener = function(cb) { | 290 chrome.Event.prototype.removeListener = function(cb) { |
184 if (!this.eventOptions_.supportsListeners) | 291 if (!this.eventOptions_.supportsListeners) |
185 throw new Error("This event does not support listeners."); | 292 throw new Error("This event does not support listeners."); |
186 var idx = this.findListener_(cb); | 293 var idx = this.findListener_(cb); |
187 if (idx == -1) { | 294 if (idx == -1) { |
188 return; | 295 return; |
189 } | 296 } |
190 | 297 |
191 this.listeners_.splice(idx, 1); | 298 var removedListener = this.listeners_.splice(idx, 1)[0]; |
| 299 this.attachmentStrategy_.onRemovedListener(removedListener); |
| 300 |
192 if (this.listeners_.length == 0) { | 301 if (this.listeners_.length == 0) { |
193 this.detach_(true); | 302 if (!this.eventName_) |
| 303 return; |
| 304 |
| 305 if (!attachedNamedEvents[this.eventName_]) { |
| 306 throw new Error("chrome.Event '" + this.eventName_ + |
| 307 "' is not attached."); |
| 308 } |
| 309 |
| 310 delete attachedNamedEvents[this.eventName_]; |
194 } | 311 } |
195 }; | 312 }; |
196 | 313 |
197 // Test if the given callback is registered for this event. | 314 // Test if the given callback is registered for this event. |
198 chrome.Event.prototype.hasListener = function(cb) { | 315 chrome.Event.prototype.hasListener = function(cb) { |
199 if (!this.eventOptions_.supportsListeners) | 316 if (!this.eventOptions_.supportsListeners) |
200 throw new Error("This event does not support listeners."); | 317 throw new Error("This event does not support listeners."); |
201 return this.findListener_(cb) > -1; | 318 return this.findListener_(cb) > -1; |
202 }; | 319 }; |
203 | 320 |
204 // Test if any callbacks are registered for this event. | 321 // Test if any callbacks are registered for this event. |
205 chrome.Event.prototype.hasListeners = function() { | 322 chrome.Event.prototype.hasListeners = function() { |
206 if (!this.eventOptions_.supportsListeners) | 323 if (!this.eventOptions_.supportsListeners) |
207 throw new Error("This event does not support listeners."); | 324 throw new Error("This event does not support listeners."); |
208 return this.listeners_.length > 0; | 325 return this.listeners_.length > 0; |
209 }; | 326 }; |
210 | 327 |
211 // Returns the index of the given callback if registered, or -1 if not | 328 // Returns the index of the given callback if registered, or -1 if not |
212 // found. | 329 // found. |
213 chrome.Event.prototype.findListener_ = function(cb) { | 330 chrome.Event.prototype.findListener_ = function(cb) { |
214 for (var i = 0; i < this.listeners_.length; i++) { | 331 for (var i = 0; i < this.listeners_.length; i++) { |
215 if (this.listeners_[i] == cb) { | 332 if (this.listeners_[i].callback == cb) { |
216 return i; | 333 return i; |
217 } | 334 } |
218 } | 335 } |
219 | 336 |
220 return -1; | 337 return -1; |
221 }; | 338 }; |
222 | 339 |
223 // Dispatches this event object to all listeners, passing all supplied | 340 chrome.Event.prototype.dispatch_ = function(args, listenerIDs) { |
224 // arguments to this function each listener. | |
225 chrome.Event.prototype.dispatch = function(varargs) { | |
226 if (!this.eventOptions_.supportsListeners) | 341 if (!this.eventOptions_.supportsListeners) |
227 throw new Error("This event does not support listeners."); | 342 throw new Error("This event does not support listeners."); |
228 var args = Array.prototype.slice.call(arguments); | |
229 var validationErrors = this.validateEventArgs_(args); | 343 var validationErrors = this.validateEventArgs_(args); |
230 if (validationErrors) { | 344 if (validationErrors) { |
231 console.error(validationErrors); | 345 console.error(validationErrors); |
232 return {validationErrors: validationErrors}; | 346 return {validationErrors: validationErrors}; |
233 } | 347 } |
| 348 |
| 349 var listeners = this.attachmentStrategy_.getListenersByIDs(listenerIDs); |
| 350 |
234 var results = []; | 351 var results = []; |
235 for (var i = 0; i < this.listeners_.length; i++) { | 352 for (var i = 0; i < listeners.length; i++) { |
236 try { | 353 try { |
237 var result = this.listeners_[i].apply(null, args); | 354 var result = listeners[i].callback.apply(null, args); |
238 if (result !== undefined) | 355 if (result !== undefined) |
239 results.push(result); | 356 results.push(result); |
240 } catch (e) { | 357 } catch (e) { |
241 console.error("Error in event handler for '" + this.eventName_ + | 358 console.error("Error in event handler for '" + this.eventName_ + |
242 "': " + e.message + ' ' + e.stack); | 359 "': " + e.message + ' ' + e.stack); |
243 } | 360 } |
244 } | 361 } |
245 if (results.length) | 362 if (results.length) |
246 return {results: results}; | 363 return {results: results}; |
247 }; | 364 } |
248 | 365 |
249 // Attaches this event object to its name. Only one object can have a given | 366 // Dispatches this event object to all listeners, passing all supplied |
250 // name. | 367 // arguments to this function each listener. |
251 chrome.Event.prototype.attach_ = function() { | 368 chrome.Event.prototype.dispatch = function(varargs) { |
252 AttachEvent(this.eventName_); | 369 return this.dispatch_(Array.prototype.slice.call(arguments), undefined); |
253 allAttachedEvents[allAttachedEvents.length] = this; | |
254 if (!this.eventName_) | |
255 return; | |
256 | |
257 if (attachedNamedEvents[this.eventName_]) { | |
258 throw new Error("chrome.Event '" + this.eventName_ + | |
259 "' is already attached."); | |
260 } | |
261 | |
262 attachedNamedEvents[this.eventName_] = this; | |
263 }; | 370 }; |
264 | 371 |
265 // Detaches this event object from its name. | 372 // Detaches this event object from its name. |
266 chrome.Event.prototype.detach_ = function(manual) { | 373 chrome.Event.prototype.detach_ = function() { |
267 var i = allAttachedEvents.indexOf(this); | 374 this.attachmentStrategy_.detach(false); |
268 if (i >= 0) | |
269 delete allAttachedEvents[i]; | |
270 DetachEvent(this.eventName_, manual); | |
271 if (!this.eventName_) | |
272 return; | |
273 | |
274 if (!attachedNamedEvents[this.eventName_]) { | |
275 throw new Error("chrome.Event '" + this.eventName_ + | |
276 "' is not attached."); | |
277 } | |
278 | |
279 delete attachedNamedEvents[this.eventName_]; | |
280 }; | 375 }; |
281 | 376 |
282 chrome.Event.prototype.destroy_ = function() { | 377 chrome.Event.prototype.destroy_ = function() { |
283 this.listeners_ = []; | 378 this.listeners_ = []; |
284 this.validateEventArgs_ = []; | 379 this.validateEventArgs_ = []; |
285 this.detach_(false); | 380 this.detach_(false); |
286 }; | 381 }; |
287 | 382 |
288 chrome.Event.prototype.addRules = function(rules, opt_cb) { | 383 chrome.Event.prototype.addRules = function(rules, opt_cb) { |
289 if (!this.eventOptions_.supportsRules) | 384 if (!this.eventOptions_.supportsRules) |
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
356 chromeHidden.onUnload = new chrome.Event(); | 451 chromeHidden.onUnload = new chrome.Event(); |
357 | 452 |
358 chromeHidden.dispatchOnLoad = | 453 chromeHidden.dispatchOnLoad = |
359 chromeHidden.onLoad.dispatch.bind(chromeHidden.onLoad); | 454 chromeHidden.onLoad.dispatch.bind(chromeHidden.onLoad); |
360 | 455 |
361 chromeHidden.dispatchOnUnload = function() { | 456 chromeHidden.dispatchOnUnload = function() { |
362 chromeHidden.onUnload.dispatch(); | 457 chromeHidden.onUnload.dispatch(); |
363 for (var i = 0; i < allAttachedEvents.length; ++i) { | 458 for (var i = 0; i < allAttachedEvents.length; ++i) { |
364 var event = allAttachedEvents[i]; | 459 var event = allAttachedEvents[i]; |
365 if (event) | 460 if (event) |
366 event.detach_(false); | 461 event.detach_(); |
367 } | 462 } |
368 }; | 463 }; |
369 | 464 |
370 chromeHidden.dispatchError = function(msg) { | 465 chromeHidden.dispatchError = function(msg) { |
371 console.error(msg); | 466 console.error(msg); |
372 }; | 467 }; |
373 | 468 |
374 exports.Event = chrome.Event; | 469 exports.Event = chrome.Event; |
OLD | NEW |