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.
5 #include "extensions/browser/event_router.h"
9 #include "base/atomic_sequence_num.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/lazy_instance.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/stl_util.h"
15 #include "base/values.h"
16 #include "content/public/browser/notification_service.h"
17 #include "content/public/browser/render_process_host.h"
18 #include "extensions/browser/api_activity_monitor.h"
19 #include "extensions/browser/extension_host.h"
20 #include "extensions/browser/extension_prefs.h"
21 #include "extensions/browser/extension_registry.h"
22 #include "extensions/browser/extension_system.h"
23 #include "extensions/browser/extensions_browser_client.h"
24 #include "extensions/browser/lazy_background_task_queue.h"
25 #include "extensions/browser/notification_types.h"
26 #include "extensions/browser/process_manager.h"
27 #include "extensions/browser/process_map.h"
28 #include "extensions/common/extension.h"
29 #include "extensions/common/extension_api.h"
30 #include "extensions/common/extension_messages.h"
31 #include "extensions/common/extension_urls.h"
32 #include "extensions/common/features/feature.h"
33 #include "extensions/common/features/feature_provider.h"
34 #include "extensions/common/manifest_handlers/background_info.h"
35 #include "extensions/common/manifest_handlers/incognito_info.h"
36 #include "extensions/common/permissions/permissions_data.h"
38 using base::DictionaryValue
;
39 using base::ListValue
;
40 using content::BrowserContext
;
41 using content::BrowserThread
;
43 namespace extensions
{
47 void DoNothing(ExtensionHost
* host
) {}
49 // A dictionary of event names to lists of filters that this extension has
50 // registered from its lazy background page.
51 const char kFilteredEvents
[] = "filtered_events";
53 // Sends a notification about an event to the API activity monitor and the
54 // ExtensionHost for |extension_id| on the UI thread. Can be called from any
56 void NotifyEventDispatched(void* browser_context_id
,
57 const std::string
& extension_id
,
58 const std::string
& event_name
,
59 scoped_ptr
<ListValue
> args
) {
60 // The ApiActivityMonitor can only be accessed from the UI thread.
61 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
)) {
62 BrowserThread::PostTask(
63 BrowserThread::UI
, FROM_HERE
,
64 base::Bind(&NotifyEventDispatched
, browser_context_id
, extension_id
,
65 event_name
, base::Passed(&args
)));
69 // Notify the ApiActivityMonitor about the event dispatch.
70 BrowserContext
* context
= static_cast<BrowserContext
*>(browser_context_id
);
71 if (!ExtensionsBrowserClient::Get()->IsValidContext(context
))
73 ApiActivityMonitor
* monitor
=
74 ExtensionsBrowserClient::Get()->GetApiActivityMonitor(context
);
76 monitor
->OnApiEventDispatched(extension_id
, event_name
, args
.Pass());
79 // A global identifier used to distinguish extension events.
80 base::StaticAtomicSequenceNumber g_extension_event_id
;
84 const char EventRouter::kRegisteredEvents
[] = "events";
86 struct EventRouter::ListenerProcess
{
87 content::RenderProcessHost
* process
;
88 std::string extension_id
;
90 ListenerProcess(content::RenderProcessHost
* process
,
91 const std::string
& extension_id
)
92 : process(process
), extension_id(extension_id
) {}
94 bool operator<(const ListenerProcess
& that
) const {
95 if (process
< that
.process
)
97 if (process
== that
.process
&& extension_id
< that
.extension_id
)
104 void EventRouter::DispatchExtensionMessage(IPC::Sender
* ipc_sender
,
105 void* browser_context_id
,
106 const std::string
& extension_id
,
108 const std::string
& event_name
,
109 ListValue
* event_args
,
110 UserGestureState user_gesture
,
111 const EventFilteringInfo
& info
) {
112 NotifyEventDispatched(browser_context_id
, extension_id
, event_name
,
113 make_scoped_ptr(event_args
->DeepCopy()));
115 // TODO(chirantan): Make event dispatch a separate IPC so that it doesn't
116 // piggyback off MessageInvoke, which is used for other things.
118 args
.Set(0, new base::StringValue(event_name
));
119 args
.Set(1, event_args
);
120 args
.Set(2, info
.AsValue().release());
121 args
.Set(3, new base::FundamentalValue(event_id
));
122 ipc_sender
->Send(new ExtensionMsg_MessageInvoke(
128 user_gesture
== USER_GESTURE_ENABLED
));
130 // DispatchExtensionMessage does _not_ take ownership of event_args, so we
131 // must ensure that the destruction of args does not attempt to free it.
132 scoped_ptr
<base::Value
> removed_event_args
;
133 args
.Remove(1, &removed_event_args
);
134 ignore_result(removed_event_args
.release());
138 EventRouter
* EventRouter::Get(content::BrowserContext
* browser_context
) {
139 return ExtensionSystem::Get(browser_context
)->event_router();
143 std::string
EventRouter::GetBaseEventName(const std::string
& full_event_name
) {
144 size_t slash_sep
= full_event_name
.find('/');
145 return full_event_name
.substr(0, slash_sep
);
149 void EventRouter::DispatchEvent(IPC::Sender
* ipc_sender
,
150 void* browser_context_id
,
151 const std::string
& extension_id
,
152 const std::string
& event_name
,
153 scoped_ptr
<ListValue
> event_args
,
154 UserGestureState user_gesture
,
155 const EventFilteringInfo
& info
) {
156 int event_id
= g_extension_event_id
.GetNext();
158 DispatchExtensionMessage(ipc_sender
, browser_context_id
, extension_id
,
159 event_id
, event_name
, event_args
.get(), user_gesture
,
162 BrowserThread::PostTask(
163 BrowserThread::UI
, FROM_HERE
,
164 base::Bind(&EventRouter::IncrementInFlightEventsOnUI
, browser_context_id
,
165 extension_id
, event_id
, event_name
));
168 EventRouter::EventRouter(BrowserContext
* browser_context
,
169 ExtensionPrefs
* extension_prefs
)
170 : browser_context_(browser_context
),
171 extension_prefs_(extension_prefs
),
172 extension_registry_observer_(this),
174 registrar_
.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED
,
175 content::NotificationService::AllSources());
176 registrar_
.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED
,
177 content::NotificationService::AllSources());
179 extensions::NOTIFICATION_EXTENSION_ENABLED
,
180 content::Source
<BrowserContext
>(browser_context_
));
181 extension_registry_observer_
.Add(ExtensionRegistry::Get(browser_context_
));
184 EventRouter::~EventRouter() {}
186 void EventRouter::AddEventListener(const std::string
& event_name
,
187 content::RenderProcessHost
* process
,
188 const std::string
& extension_id
) {
189 listeners_
.AddListener(EventListener::ForExtension(
190 event_name
, extension_id
, process
, scoped_ptr
<DictionaryValue
>()));
193 void EventRouter::RemoveEventListener(const std::string
& event_name
,
194 content::RenderProcessHost
* process
,
195 const std::string
& extension_id
) {
196 scoped_ptr
<EventListener
> listener
= EventListener::ForExtension(
197 event_name
, extension_id
, process
, scoped_ptr
<DictionaryValue
>());
198 listeners_
.RemoveListener(listener
.get());
201 void EventRouter::AddEventListenerForURL(const std::string
& event_name
,
202 content::RenderProcessHost
* process
,
203 const GURL
& listener_url
) {
204 listeners_
.AddListener(EventListener::ForURL(
205 event_name
, listener_url
, process
, scoped_ptr
<DictionaryValue
>()));
208 void EventRouter::RemoveEventListenerForURL(const std::string
& event_name
,
209 content::RenderProcessHost
* process
,
210 const GURL
& listener_url
) {
211 scoped_ptr
<EventListener
> listener
= EventListener::ForURL(
212 event_name
, listener_url
, process
, scoped_ptr
<DictionaryValue
>());
213 listeners_
.RemoveListener(listener
.get());
216 void EventRouter::RegisterObserver(Observer
* observer
,
217 const std::string
& event_name
) {
218 // Observing sub-event names like "foo.onBar/123" is not allowed.
219 DCHECK(event_name
.find('/') == std::string::npos
);
220 observers_
[event_name
] = observer
;
223 void EventRouter::UnregisterObserver(Observer
* observer
) {
224 std::vector
<ObserverMap::iterator
> iters_to_remove
;
225 for (ObserverMap::iterator iter
= observers_
.begin();
226 iter
!= observers_
.end(); ++iter
) {
227 if (iter
->second
== observer
)
228 iters_to_remove
.push_back(iter
);
230 for (size_t i
= 0; i
< iters_to_remove
.size(); ++i
)
231 observers_
.erase(iters_to_remove
[i
]);
234 void EventRouter::OnListenerAdded(const EventListener
* listener
) {
235 const EventListenerInfo
details(listener
->event_name(),
236 listener
->extension_id(),
237 listener
->listener_url(),
238 listener
->GetBrowserContext());
239 std::string base_event_name
= GetBaseEventName(listener
->event_name());
240 ObserverMap::iterator observer
= observers_
.find(base_event_name
);
241 if (observer
!= observers_
.end())
242 observer
->second
->OnListenerAdded(details
);
245 void EventRouter::OnListenerRemoved(const EventListener
* listener
) {
246 const EventListenerInfo
details(listener
->event_name(),
247 listener
->extension_id(),
248 listener
->listener_url(),
249 listener
->GetBrowserContext());
250 std::string base_event_name
= GetBaseEventName(listener
->event_name());
251 ObserverMap::iterator observer
= observers_
.find(base_event_name
);
252 if (observer
!= observers_
.end())
253 observer
->second
->OnListenerRemoved(details
);
256 void EventRouter::AddLazyEventListener(const std::string
& event_name
,
257 const std::string
& extension_id
) {
258 bool is_new
= listeners_
.AddListener(EventListener::ForExtension(
259 event_name
, extension_id
, NULL
, scoped_ptr
<DictionaryValue
>()));
262 std::set
<std::string
> events
= GetRegisteredEvents(extension_id
);
263 bool prefs_is_new
= events
.insert(event_name
).second
;
265 SetRegisteredEvents(extension_id
, events
);
269 void EventRouter::RemoveLazyEventListener(const std::string
& event_name
,
270 const std::string
& extension_id
) {
271 scoped_ptr
<EventListener
> listener
= EventListener::ForExtension(
272 event_name
, extension_id
, NULL
, scoped_ptr
<DictionaryValue
>());
273 bool did_exist
= listeners_
.RemoveListener(listener
.get());
276 std::set
<std::string
> events
= GetRegisteredEvents(extension_id
);
277 bool prefs_did_exist
= events
.erase(event_name
) > 0;
278 DCHECK(prefs_did_exist
);
279 SetRegisteredEvents(extension_id
, events
);
283 void EventRouter::AddFilteredEventListener(const std::string
& event_name
,
284 content::RenderProcessHost
* process
,
285 const std::string
& extension_id
,
286 const base::DictionaryValue
& filter
,
287 bool add_lazy_listener
) {
288 listeners_
.AddListener(EventListener::ForExtension(
292 scoped_ptr
<DictionaryValue
>(filter
.DeepCopy())));
294 if (add_lazy_listener
) {
295 bool added
= listeners_
.AddListener(EventListener::ForExtension(
299 scoped_ptr
<DictionaryValue
>(filter
.DeepCopy())));
302 AddFilterToEvent(event_name
, extension_id
, &filter
);
306 void EventRouter::RemoveFilteredEventListener(
307 const std::string
& event_name
,
308 content::RenderProcessHost
* process
,
309 const std::string
& extension_id
,
310 const base::DictionaryValue
& filter
,
311 bool remove_lazy_listener
) {
312 scoped_ptr
<EventListener
> listener
= EventListener::ForExtension(
316 scoped_ptr
<DictionaryValue
>(filter
.DeepCopy()));
318 listeners_
.RemoveListener(listener
.get());
320 if (remove_lazy_listener
) {
321 listener
->MakeLazy();
322 bool removed
= listeners_
.RemoveListener(listener
.get());
325 RemoveFilterFromEvent(event_name
, extension_id
, &filter
);
329 bool EventRouter::HasEventListener(const std::string
& event_name
) {
330 return listeners_
.HasListenerForEvent(event_name
);
333 bool EventRouter::ExtensionHasEventListener(const std::string
& extension_id
,
334 const std::string
& event_name
) {
335 return listeners_
.HasListenerForExtension(extension_id
, event_name
);
338 bool EventRouter::HasEventListenerImpl(const ListenerMap
& listener_map
,
339 const std::string
& extension_id
,
340 const std::string
& event_name
) {
341 ListenerMap::const_iterator it
= listener_map
.find(event_name
);
342 if (it
== listener_map
.end())
345 const std::set
<ListenerProcess
>& listeners
= it
->second
;
346 if (extension_id
.empty())
347 return !listeners
.empty();
349 for (std::set
<ListenerProcess
>::const_iterator listener
= listeners
.begin();
350 listener
!= listeners
.end(); ++listener
) {
351 if (listener
->extension_id
== extension_id
)
357 std::set
<std::string
> EventRouter::GetRegisteredEvents(
358 const std::string
& extension_id
) {
359 std::set
<std::string
> events
;
360 const ListValue
* events_value
= NULL
;
362 if (!extension_prefs_
||
363 !extension_prefs_
->ReadPrefAsList(
364 extension_id
, kRegisteredEvents
, &events_value
)) {
368 for (size_t i
= 0; i
< events_value
->GetSize(); ++i
) {
370 if (events_value
->GetString(i
, &event
))
371 events
.insert(event
);
376 void EventRouter::SetRegisteredEvents(const std::string
& extension_id
,
377 const std::set
<std::string
>& events
) {
378 ListValue
* events_value
= new ListValue
;
379 for (std::set
<std::string
>::const_iterator iter
= events
.begin();
380 iter
!= events
.end(); ++iter
) {
381 events_value
->Append(new base::StringValue(*iter
));
383 extension_prefs_
->UpdateExtensionPref(
384 extension_id
, kRegisteredEvents
, events_value
);
387 void EventRouter::AddFilterToEvent(const std::string
& event_name
,
388 const std::string
& extension_id
,
389 const DictionaryValue
* filter
) {
390 ExtensionPrefs::ScopedDictionaryUpdate
update(
391 extension_prefs_
, extension_id
, kFilteredEvents
);
392 DictionaryValue
* filtered_events
= update
.Get();
393 if (!filtered_events
)
394 filtered_events
= update
.Create();
396 ListValue
* filter_list
= NULL
;
397 if (!filtered_events
->GetList(event_name
, &filter_list
)) {
398 filter_list
= new ListValue
;
399 filtered_events
->SetWithoutPathExpansion(event_name
, filter_list
);
402 filter_list
->Append(filter
->DeepCopy());
405 void EventRouter::RemoveFilterFromEvent(const std::string
& event_name
,
406 const std::string
& extension_id
,
407 const DictionaryValue
* filter
) {
408 ExtensionPrefs::ScopedDictionaryUpdate
update(
409 extension_prefs_
, extension_id
, kFilteredEvents
);
410 DictionaryValue
* filtered_events
= update
.Get();
411 ListValue
* filter_list
= NULL
;
412 if (!filtered_events
||
413 !filtered_events
->GetListWithoutPathExpansion(event_name
, &filter_list
)) {
417 for (size_t i
= 0; i
< filter_list
->GetSize(); i
++) {
418 DictionaryValue
* filter
= NULL
;
419 CHECK(filter_list
->GetDictionary(i
, &filter
));
420 if (filter
->Equals(filter
)) {
421 filter_list
->Remove(i
, NULL
);
427 const DictionaryValue
* EventRouter::GetFilteredEvents(
428 const std::string
& extension_id
) {
429 const DictionaryValue
* events
= NULL
;
430 extension_prefs_
->ReadPrefAsDictionary(
431 extension_id
, kFilteredEvents
, &events
);
435 void EventRouter::BroadcastEvent(scoped_ptr
<Event
> event
) {
436 DispatchEventImpl(std::string(), linked_ptr
<Event
>(event
.release()));
439 void EventRouter::DispatchEventToExtension(const std::string
& extension_id
,
440 scoped_ptr
<Event
> event
) {
441 DCHECK(!extension_id
.empty());
442 DispatchEventImpl(extension_id
, linked_ptr
<Event
>(event
.release()));
445 void EventRouter::DispatchEventWithLazyListener(const std::string
& extension_id
,
446 scoped_ptr
<Event
> event
) {
447 DCHECK(!extension_id
.empty());
448 std::string event_name
= event
->event_name
;
449 bool has_listener
= ExtensionHasEventListener(extension_id
, event_name
);
451 AddLazyEventListener(event_name
, extension_id
);
452 DispatchEventToExtension(extension_id
, event
.Pass());
454 RemoveLazyEventListener(event_name
, extension_id
);
457 void EventRouter::DispatchEventImpl(const std::string
& restrict_to_extension_id
,
458 const linked_ptr
<Event
>& event
) {
459 // We don't expect to get events from a completely different browser context.
460 DCHECK(!event
->restrict_to_browser_context
||
461 ExtensionsBrowserClient::Get()->IsSameContext(
462 browser_context_
, event
->restrict_to_browser_context
));
464 std::set
<const EventListener
*> listeners(
465 listeners_
.GetEventListeners(*event
));
467 std::set
<EventDispatchIdentifier
> already_dispatched
;
469 // We dispatch events for lazy background pages first because attempting to do
470 // so will cause those that are being suspended to cancel that suspension.
471 // As canceling a suspension entails sending an event to the affected
472 // background page, and as that event needs to be delivered before we dispatch
473 // the event we are dispatching here, we dispatch to the lazy listeners here
475 for (std::set
<const EventListener
*>::iterator it
= listeners
.begin();
476 it
!= listeners
.end(); it
++) {
477 const EventListener
* listener
= *it
;
478 if (restrict_to_extension_id
.empty() ||
479 restrict_to_extension_id
== listener
->extension_id()) {
480 if (listener
->IsLazy()) {
481 DispatchLazyEvent(listener
->extension_id(), event
, &already_dispatched
);
486 for (std::set
<const EventListener
*>::iterator it
= listeners
.begin();
487 it
!= listeners
.end(); it
++) {
488 const EventListener
* listener
= *it
;
489 if (restrict_to_extension_id
.empty() ||
490 restrict_to_extension_id
== listener
->extension_id()) {
491 if (listener
->process()) {
492 EventDispatchIdentifier
dispatch_id(listener
->GetBrowserContext(),
493 listener
->extension_id());
494 if (!ContainsKey(already_dispatched
, dispatch_id
)) {
495 DispatchEventToProcess(listener
->extension_id(),
496 listener
->listener_url(),
505 void EventRouter::DispatchLazyEvent(
506 const std::string
& extension_id
,
507 const linked_ptr
<Event
>& event
,
508 std::set
<EventDispatchIdentifier
>* already_dispatched
) {
509 // Check both the original and the incognito browser context to see if we
510 // should load a lazy bg page to handle the event. The latter case
511 // occurs in the case of split-mode extensions.
512 const Extension
* extension
=
513 ExtensionRegistry::Get(browser_context_
)->enabled_extensions().GetByID(
518 if (MaybeLoadLazyBackgroundPageToDispatchEvent(
519 browser_context_
, extension
, event
)) {
520 already_dispatched
->insert(std::make_pair(browser_context_
, extension_id
));
523 ExtensionsBrowserClient
* browser_client
= ExtensionsBrowserClient::Get();
524 if (browser_client
->HasOffTheRecordContext(browser_context_
) &&
525 IncognitoInfo::IsSplitMode(extension
)) {
526 BrowserContext
* incognito_context
=
527 browser_client
->GetOffTheRecordContext(browser_context_
);
528 if (MaybeLoadLazyBackgroundPageToDispatchEvent(
529 incognito_context
, extension
, event
)) {
530 already_dispatched
->insert(
531 std::make_pair(incognito_context
, extension_id
));
536 void EventRouter::DispatchEventToProcess(const std::string
& extension_id
,
537 const GURL
& listener_url
,
538 content::RenderProcessHost
* process
,
539 const linked_ptr
<Event
>& event
) {
540 BrowserContext
* listener_context
= process
->GetBrowserContext();
541 ProcessMap
* process_map
= ProcessMap::Get(listener_context
);
543 // NOTE: |extension| being NULL does not necessarily imply that this event
544 // shouldn't be dispatched. Events can be dispatched to WebUI and webviews as
545 // well. It all depends on what GetMostLikelyContextType returns.
546 const Extension
* extension
=
547 ExtensionRegistry::Get(browser_context_
)->enabled_extensions().GetByID(
550 if (!extension
&& !extension_id
.empty()) {
551 // Trying to dispatch an event to an extension that doesn't exist. The
552 // extension could have been removed, but we do not unregister it until the
553 // extension process is unloaded.
558 // Extension-specific checks.
559 // Firstly, if the event is for a URL, the Extension must have permission
560 // to access that URL.
561 if (!event
->event_url
.is_empty() &&
562 event
->event_url
.host() != extension
->id() && // event for self is ok
563 !extension
->permissions_data()
564 ->active_permissions()
565 ->HasEffectiveAccessToURL(event
->event_url
)) {
568 // Secondly, if the event is for incognito mode, the Extension must be
569 // enabled in incognito mode.
570 if (!CanDispatchEventToBrowserContext(listener_context
, extension
, event
)) {
575 Feature::Context target_context
=
576 process_map
->GetMostLikelyContextType(extension
, process
->GetID());
578 // We shouldn't be dispatching an event to a webpage, since all such events
579 // (e.g. messaging) don't go through EventRouter.
580 DCHECK_NE(Feature::WEB_PAGE_CONTEXT
, target_context
)
581 << "Trying to dispatch event " << event
->event_name
<< " to a webpage,"
582 << " but this shouldn't be possible";
584 Feature::Availability availability
=
585 ExtensionAPI::GetSharedInstance()->IsAvailable(
586 event
->event_name
, extension
, target_context
, listener_url
);
587 if (!availability
.is_available()) {
588 // It shouldn't be possible to reach here, because access is checked on
589 // registration. However, for paranoia, check on dispatch as well.
590 NOTREACHED() << "Trying to dispatch event " << event
->event_name
591 << " which the target does not have access to: "
592 << availability
.message();
596 if (!event
->will_dispatch_callback
.is_null() &&
597 !event
->will_dispatch_callback
.Run(listener_context
, extension
,
598 event
->event_args
.get())) {
602 int event_id
= g_extension_event_id
.GetNext();
603 DispatchExtensionMessage(process
, listener_context
, extension_id
, event_id
,
604 event
->event_name
, event
->event_args
.get(),
605 event
->user_gesture
, event
->filter_info
);
608 IncrementInFlightEvents(listener_context
, extension
, event_id
,
613 bool EventRouter::CanDispatchEventToBrowserContext(
614 BrowserContext
* context
,
615 const Extension
* extension
,
616 const linked_ptr
<Event
>& event
) {
617 // Is this event from a different browser context than the renderer (ie, an
618 // incognito tab event sent to a normal process, or vice versa).
619 bool cross_incognito
= event
->restrict_to_browser_context
&&
620 context
!= event
->restrict_to_browser_context
;
621 if (!cross_incognito
)
623 return ExtensionsBrowserClient::Get()->CanExtensionCrossIncognito(
627 bool EventRouter::MaybeLoadLazyBackgroundPageToDispatchEvent(
628 BrowserContext
* context
,
629 const Extension
* extension
,
630 const linked_ptr
<Event
>& event
) {
631 if (!CanDispatchEventToBrowserContext(context
, extension
, event
))
634 LazyBackgroundTaskQueue
* queue
= ExtensionSystem::Get(
635 context
)->lazy_background_task_queue();
636 if (queue
->ShouldEnqueueTask(context
, extension
)) {
637 linked_ptr
<Event
> dispatched_event(event
);
639 // If there's a dispatch callback, call it now (rather than dispatch time)
640 // to avoid lifetime issues. Use a separate copy of the event args, so they
641 // last until the event is dispatched.
642 if (!event
->will_dispatch_callback
.is_null()) {
643 dispatched_event
.reset(event
->DeepCopy());
644 if (!dispatched_event
->will_dispatch_callback
.Run(
645 context
, extension
, dispatched_event
->event_args
.get())) {
646 // The event has been canceled.
649 // Ensure we don't call it again at dispatch time.
650 dispatched_event
->will_dispatch_callback
.Reset();
653 queue
->AddPendingTask(context
, extension
->id(),
654 base::Bind(&EventRouter::DispatchPendingEvent
,
655 base::Unretained(this), dispatched_event
));
663 void EventRouter::IncrementInFlightEventsOnUI(void* browser_context_id
,
664 const std::string
& extension_id
,
666 const std::string
& event_name
) {
667 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
668 BrowserContext
* browser_context
=
669 reinterpret_cast<BrowserContext
*>(browser_context_id
);
670 if (!ExtensionsBrowserClient::Get()->IsValidContext(browser_context
))
672 EventRouter
* event_router
= EventRouter::Get(browser_context
);
675 const Extension
* extension
=
676 ExtensionRegistry::Get(browser_context
)->enabled_extensions().GetByID(
680 event_router
->IncrementInFlightEvents(browser_context
, extension
, event_id
,
684 void EventRouter::IncrementInFlightEvents(BrowserContext
* context
,
685 const Extension
* extension
,
687 const std::string
& event_name
) {
688 // TODO(chirantan): Turn this on once crbug.com/464513 is fixed.
689 // DCHECK_CURRENTLY_ON(BrowserThread::UI);
691 // Only increment in-flight events if the lazy background page is active,
692 // because that's the only time we'll get an ACK.
693 if (BackgroundInfo::HasLazyBackgroundPage(extension
)) {
694 ProcessManager
* pm
= ProcessManager::Get(context
);
695 ExtensionHost
* host
= pm
->GetBackgroundHostForExtension(extension
->id());
697 pm
->IncrementLazyKeepaliveCount(extension
);
698 host
->OnBackgroundEventDispatched(event_name
, event_id
);
703 void EventRouter::OnEventAck(BrowserContext
* context
,
704 const std::string
& extension_id
) {
705 ProcessManager
* pm
= ProcessManager::Get(context
);
706 ExtensionHost
* host
= pm
->GetBackgroundHostForExtension(extension_id
);
707 // The event ACK is routed to the background host, so this should never be
710 // TODO(mpcomplete): We should never get this message unless
711 // HasLazyBackgroundPage is true. Find out why we're getting it anyway.
712 if (host
->extension() &&
713 BackgroundInfo::HasLazyBackgroundPage(host
->extension()))
714 pm
->DecrementLazyKeepaliveCount(host
->extension());
717 void EventRouter::DispatchPendingEvent(const linked_ptr
<Event
>& event
,
718 ExtensionHost
* host
) {
722 if (listeners_
.HasProcessListener(host
->render_process_host(),
723 host
->extension()->id())) {
724 // URL events cannot be lazy therefore can't be pending, hence the GURL().
725 DispatchEventToProcess(
726 host
->extension()->id(), GURL(), host
->render_process_host(), event
);
730 void EventRouter::Observe(int type
,
731 const content::NotificationSource
& source
,
732 const content::NotificationDetails
& details
) {
734 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED
:
735 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED
: {
736 content::RenderProcessHost
* renderer
=
737 content::Source
<content::RenderProcessHost
>(source
).ptr();
738 // Remove all event listeners associated with this renderer.
739 listeners_
.RemoveListenersForProcess(renderer
);
742 case extensions::NOTIFICATION_EXTENSION_ENABLED
: {
743 // If the extension has a lazy background page, make sure it gets loaded
744 // to register the events the extension is interested in.
745 const Extension
* extension
=
746 content::Details
<const Extension
>(details
).ptr();
747 if (BackgroundInfo::HasLazyBackgroundPage(extension
)) {
748 LazyBackgroundTaskQueue
* queue
= ExtensionSystem::Get(
749 browser_context_
)->lazy_background_task_queue();
750 queue
->AddPendingTask(browser_context_
, extension
->id(),
751 base::Bind(&DoNothing
));
760 void EventRouter::OnExtensionLoaded(content::BrowserContext
* browser_context
,
761 const Extension
* extension
) {
762 // Add all registered lazy listeners to our cache.
763 std::set
<std::string
> registered_events
=
764 GetRegisteredEvents(extension
->id());
765 listeners_
.LoadUnfilteredLazyListeners(extension
->id(), registered_events
);
766 const DictionaryValue
* filtered_events
= GetFilteredEvents(extension
->id());
768 listeners_
.LoadFilteredLazyListeners(extension
->id(), *filtered_events
);
771 void EventRouter::OnExtensionUnloaded(content::BrowserContext
* browser_context
,
772 const Extension
* extension
,
773 UnloadedExtensionInfo::Reason reason
) {
774 // Remove all registered listeners from our cache.
775 listeners_
.RemoveListenersForExtension(extension
->id());
778 Event::Event(const std::string
& event_name
,
779 scoped_ptr
<base::ListValue
> event_args
)
780 : event_name(event_name
),
781 event_args(event_args
.Pass()),
782 restrict_to_browser_context(NULL
),
783 user_gesture(EventRouter::USER_GESTURE_UNKNOWN
) {
784 DCHECK(this->event_args
.get());
787 Event::Event(const std::string
& event_name
,
788 scoped_ptr
<base::ListValue
> event_args
,
789 BrowserContext
* restrict_to_browser_context
)
790 : event_name(event_name
),
791 event_args(event_args
.Pass()),
792 restrict_to_browser_context(restrict_to_browser_context
),
793 user_gesture(EventRouter::USER_GESTURE_UNKNOWN
) {
794 DCHECK(this->event_args
.get());
797 Event::Event(const std::string
& event_name
,
798 scoped_ptr
<ListValue
> event_args
,
799 BrowserContext
* restrict_to_browser_context
,
800 const GURL
& event_url
,
801 EventRouter::UserGestureState user_gesture
,
802 const EventFilteringInfo
& filter_info
)
803 : event_name(event_name
),
804 event_args(event_args
.Pass()),
805 restrict_to_browser_context(restrict_to_browser_context
),
806 event_url(event_url
),
807 user_gesture(user_gesture
),
808 filter_info(filter_info
) {
809 DCHECK(this->event_args
.get());
814 Event
* Event::DeepCopy() {
815 Event
* copy
= new Event(event_name
,
816 scoped_ptr
<base::ListValue
>(event_args
->DeepCopy()),
817 restrict_to_browser_context
,
821 copy
->will_dispatch_callback
= will_dispatch_callback
;
825 EventListenerInfo::EventListenerInfo(const std::string
& event_name
,
826 const std::string
& extension_id
,
827 const GURL
& listener_url
,
828 content::BrowserContext
* browser_context
)
829 : event_name(event_name
),
830 extension_id(extension_id
),
831 listener_url(listener_url
),
832 browser_context(browser_context
) {
835 } // namespace extensions