Revert of Fix missing GN dependencies. (patchset #4 id:60001 of https://codereview...
[chromium-blink-merge.git] / extensions / browser / event_router.cc
blobafd92d031706df336851d02d55ee5307ab16b53d
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"
7 #include <utility>
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 {
45 namespace {
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
55 // thread.
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)));
66 return;
69 // Notify the ApiActivityMonitor about the event dispatch.
70 BrowserContext* context = static_cast<BrowserContext*>(browser_context_id);
71 if (!ExtensionsBrowserClient::Get()->IsValidContext(context))
72 return;
73 ApiActivityMonitor* monitor =
74 ExtensionsBrowserClient::Get()->GetApiActivityMonitor(context);
75 if (monitor)
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;
82 } // namespace
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)
96 return true;
97 if (process == that.process && extension_id < that.extension_id)
98 return true;
99 return false;
103 // static
104 void EventRouter::DispatchExtensionMessage(IPC::Sender* ipc_sender,
105 void* browser_context_id,
106 const std::string& extension_id,
107 int event_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.
117 ListValue args;
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(
123 MSG_ROUTING_CONTROL,
124 extension_id,
125 kEventBindings,
126 "dispatchEvent",
127 args,
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());
137 // static
138 EventRouter* EventRouter::Get(content::BrowserContext* browser_context) {
139 return ExtensionSystem::Get(browser_context)->event_router();
142 // static
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);
148 // static
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 if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
159 // This is called from WebRequest API.
160 // TODO(lazyboy): Skip this entirely: http://crbug.com/488747.
161 BrowserThread::PostTask(
162 BrowserThread::UI, FROM_HERE,
163 base::Bind(&EventRouter::IncrementInFlightEventsOnUI,
164 browser_context_id, extension_id, event_id, event_name));
165 } else {
166 IncrementInFlightEventsOnUI(browser_context_id, extension_id, event_id,
167 event_name);
170 DispatchExtensionMessage(ipc_sender, browser_context_id, extension_id,
171 event_id, event_name, event_args.get(), user_gesture,
172 info);
175 EventRouter::EventRouter(BrowserContext* browser_context,
176 ExtensionPrefs* extension_prefs)
177 : browser_context_(browser_context),
178 extension_prefs_(extension_prefs),
179 extension_registry_observer_(this),
180 listeners_(this) {
181 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
182 content::NotificationService::AllSources());
183 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
184 content::NotificationService::AllSources());
185 registrar_.Add(this,
186 extensions::NOTIFICATION_EXTENSION_ENABLED,
187 content::Source<BrowserContext>(browser_context_));
188 extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_));
191 EventRouter::~EventRouter() {}
193 void EventRouter::AddEventListener(const std::string& event_name,
194 content::RenderProcessHost* process,
195 const std::string& extension_id) {
196 listeners_.AddListener(EventListener::ForExtension(
197 event_name, extension_id, process, scoped_ptr<DictionaryValue>()));
200 void EventRouter::RemoveEventListener(const std::string& event_name,
201 content::RenderProcessHost* process,
202 const std::string& extension_id) {
203 scoped_ptr<EventListener> listener = EventListener::ForExtension(
204 event_name, extension_id, process, scoped_ptr<DictionaryValue>());
205 listeners_.RemoveListener(listener.get());
208 void EventRouter::AddEventListenerForURL(const std::string& event_name,
209 content::RenderProcessHost* process,
210 const GURL& listener_url) {
211 listeners_.AddListener(EventListener::ForURL(
212 event_name, listener_url, process, scoped_ptr<DictionaryValue>()));
215 void EventRouter::RemoveEventListenerForURL(const std::string& event_name,
216 content::RenderProcessHost* process,
217 const GURL& listener_url) {
218 scoped_ptr<EventListener> listener = EventListener::ForURL(
219 event_name, listener_url, process, scoped_ptr<DictionaryValue>());
220 listeners_.RemoveListener(listener.get());
223 void EventRouter::RegisterObserver(Observer* observer,
224 const std::string& event_name) {
225 // Observing sub-event names like "foo.onBar/123" is not allowed.
226 DCHECK(event_name.find('/') == std::string::npos);
227 observers_[event_name] = observer;
230 void EventRouter::UnregisterObserver(Observer* observer) {
231 std::vector<ObserverMap::iterator> iters_to_remove;
232 for (ObserverMap::iterator iter = observers_.begin();
233 iter != observers_.end(); ++iter) {
234 if (iter->second == observer)
235 iters_to_remove.push_back(iter);
237 for (size_t i = 0; i < iters_to_remove.size(); ++i)
238 observers_.erase(iters_to_remove[i]);
241 void EventRouter::OnListenerAdded(const EventListener* listener) {
242 const EventListenerInfo details(listener->event_name(),
243 listener->extension_id(),
244 listener->listener_url(),
245 listener->GetBrowserContext());
246 std::string base_event_name = GetBaseEventName(listener->event_name());
247 ObserverMap::iterator observer = observers_.find(base_event_name);
248 if (observer != observers_.end())
249 observer->second->OnListenerAdded(details);
252 void EventRouter::OnListenerRemoved(const EventListener* listener) {
253 const EventListenerInfo details(listener->event_name(),
254 listener->extension_id(),
255 listener->listener_url(),
256 listener->GetBrowserContext());
257 std::string base_event_name = GetBaseEventName(listener->event_name());
258 ObserverMap::iterator observer = observers_.find(base_event_name);
259 if (observer != observers_.end())
260 observer->second->OnListenerRemoved(details);
263 void EventRouter::AddLazyEventListener(const std::string& event_name,
264 const std::string& extension_id) {
265 bool is_new = listeners_.AddListener(EventListener::ForExtension(
266 event_name, extension_id, NULL, scoped_ptr<DictionaryValue>()));
268 if (is_new) {
269 std::set<std::string> events = GetRegisteredEvents(extension_id);
270 bool prefs_is_new = events.insert(event_name).second;
271 if (prefs_is_new)
272 SetRegisteredEvents(extension_id, events);
276 void EventRouter::RemoveLazyEventListener(const std::string& event_name,
277 const std::string& extension_id) {
278 scoped_ptr<EventListener> listener = EventListener::ForExtension(
279 event_name, extension_id, NULL, scoped_ptr<DictionaryValue>());
280 bool did_exist = listeners_.RemoveListener(listener.get());
282 if (did_exist) {
283 std::set<std::string> events = GetRegisteredEvents(extension_id);
284 bool prefs_did_exist = events.erase(event_name) > 0;
285 DCHECK(prefs_did_exist);
286 SetRegisteredEvents(extension_id, events);
290 void EventRouter::AddFilteredEventListener(const std::string& event_name,
291 content::RenderProcessHost* process,
292 const std::string& extension_id,
293 const base::DictionaryValue& filter,
294 bool add_lazy_listener) {
295 listeners_.AddListener(EventListener::ForExtension(
296 event_name,
297 extension_id,
298 process,
299 scoped_ptr<DictionaryValue>(filter.DeepCopy())));
301 if (add_lazy_listener) {
302 bool added = listeners_.AddListener(EventListener::ForExtension(
303 event_name,
304 extension_id,
305 NULL,
306 scoped_ptr<DictionaryValue>(filter.DeepCopy())));
308 if (added)
309 AddFilterToEvent(event_name, extension_id, &filter);
313 void EventRouter::RemoveFilteredEventListener(
314 const std::string& event_name,
315 content::RenderProcessHost* process,
316 const std::string& extension_id,
317 const base::DictionaryValue& filter,
318 bool remove_lazy_listener) {
319 scoped_ptr<EventListener> listener = EventListener::ForExtension(
320 event_name,
321 extension_id,
322 process,
323 scoped_ptr<DictionaryValue>(filter.DeepCopy()));
325 listeners_.RemoveListener(listener.get());
327 if (remove_lazy_listener) {
328 listener->MakeLazy();
329 bool removed = listeners_.RemoveListener(listener.get());
331 if (removed)
332 RemoveFilterFromEvent(event_name, extension_id, &filter);
336 bool EventRouter::HasEventListener(const std::string& event_name) {
337 return listeners_.HasListenerForEvent(event_name);
340 bool EventRouter::ExtensionHasEventListener(const std::string& extension_id,
341 const std::string& event_name) {
342 return listeners_.HasListenerForExtension(extension_id, event_name);
345 bool EventRouter::HasEventListenerImpl(const ListenerMap& listener_map,
346 const std::string& extension_id,
347 const std::string& event_name) {
348 ListenerMap::const_iterator it = listener_map.find(event_name);
349 if (it == listener_map.end())
350 return false;
352 const std::set<ListenerProcess>& listeners = it->second;
353 if (extension_id.empty())
354 return !listeners.empty();
356 for (std::set<ListenerProcess>::const_iterator listener = listeners.begin();
357 listener != listeners.end(); ++listener) {
358 if (listener->extension_id == extension_id)
359 return true;
361 return false;
364 std::set<std::string> EventRouter::GetRegisteredEvents(
365 const std::string& extension_id) {
366 std::set<std::string> events;
367 const ListValue* events_value = NULL;
369 if (!extension_prefs_ ||
370 !extension_prefs_->ReadPrefAsList(
371 extension_id, kRegisteredEvents, &events_value)) {
372 return events;
375 for (size_t i = 0; i < events_value->GetSize(); ++i) {
376 std::string event;
377 if (events_value->GetString(i, &event))
378 events.insert(event);
380 return events;
383 void EventRouter::SetRegisteredEvents(const std::string& extension_id,
384 const std::set<std::string>& events) {
385 ListValue* events_value = new ListValue;
386 for (std::set<std::string>::const_iterator iter = events.begin();
387 iter != events.end(); ++iter) {
388 events_value->Append(new base::StringValue(*iter));
390 extension_prefs_->UpdateExtensionPref(
391 extension_id, kRegisteredEvents, events_value);
394 void EventRouter::AddFilterToEvent(const std::string& event_name,
395 const std::string& extension_id,
396 const DictionaryValue* filter) {
397 ExtensionPrefs::ScopedDictionaryUpdate update(
398 extension_prefs_, extension_id, kFilteredEvents);
399 DictionaryValue* filtered_events = update.Get();
400 if (!filtered_events)
401 filtered_events = update.Create();
403 ListValue* filter_list = NULL;
404 if (!filtered_events->GetList(event_name, &filter_list)) {
405 filter_list = new ListValue;
406 filtered_events->SetWithoutPathExpansion(event_name, filter_list);
409 filter_list->Append(filter->DeepCopy());
412 void EventRouter::RemoveFilterFromEvent(const std::string& event_name,
413 const std::string& extension_id,
414 const DictionaryValue* filter) {
415 ExtensionPrefs::ScopedDictionaryUpdate update(
416 extension_prefs_, extension_id, kFilteredEvents);
417 DictionaryValue* filtered_events = update.Get();
418 ListValue* filter_list = NULL;
419 if (!filtered_events ||
420 !filtered_events->GetListWithoutPathExpansion(event_name, &filter_list)) {
421 return;
424 for (size_t i = 0; i < filter_list->GetSize(); i++) {
425 DictionaryValue* filter = NULL;
426 CHECK(filter_list->GetDictionary(i, &filter));
427 if (filter->Equals(filter)) {
428 filter_list->Remove(i, NULL);
429 break;
434 const DictionaryValue* EventRouter::GetFilteredEvents(
435 const std::string& extension_id) {
436 const DictionaryValue* events = NULL;
437 extension_prefs_->ReadPrefAsDictionary(
438 extension_id, kFilteredEvents, &events);
439 return events;
442 void EventRouter::BroadcastEvent(scoped_ptr<Event> event) {
443 DispatchEventImpl(std::string(), linked_ptr<Event>(event.release()));
446 void EventRouter::DispatchEventToExtension(const std::string& extension_id,
447 scoped_ptr<Event> event) {
448 DCHECK(!extension_id.empty());
449 DispatchEventImpl(extension_id, linked_ptr<Event>(event.release()));
452 void EventRouter::DispatchEventWithLazyListener(const std::string& extension_id,
453 scoped_ptr<Event> event) {
454 DCHECK(!extension_id.empty());
455 std::string event_name = event->event_name;
456 bool has_listener = ExtensionHasEventListener(extension_id, event_name);
457 if (!has_listener)
458 AddLazyEventListener(event_name, extension_id);
459 DispatchEventToExtension(extension_id, event.Pass());
460 if (!has_listener)
461 RemoveLazyEventListener(event_name, extension_id);
464 void EventRouter::DispatchEventImpl(const std::string& restrict_to_extension_id,
465 const linked_ptr<Event>& event) {
466 // We don't expect to get events from a completely different browser context.
467 DCHECK(!event->restrict_to_browser_context ||
468 ExtensionsBrowserClient::Get()->IsSameContext(
469 browser_context_, event->restrict_to_browser_context));
471 std::set<const EventListener*> listeners(
472 listeners_.GetEventListeners(*event));
474 std::set<EventDispatchIdentifier> already_dispatched;
476 // We dispatch events for lazy background pages first because attempting to do
477 // so will cause those that are being suspended to cancel that suspension.
478 // As canceling a suspension entails sending an event to the affected
479 // background page, and as that event needs to be delivered before we dispatch
480 // the event we are dispatching here, we dispatch to the lazy listeners here
481 // first.
482 for (std::set<const EventListener*>::iterator it = listeners.begin();
483 it != listeners.end(); it++) {
484 const EventListener* listener = *it;
485 if (restrict_to_extension_id.empty() ||
486 restrict_to_extension_id == listener->extension_id()) {
487 if (listener->IsLazy()) {
488 DispatchLazyEvent(listener->extension_id(), event, &already_dispatched);
493 for (std::set<const EventListener*>::iterator it = listeners.begin();
494 it != listeners.end(); it++) {
495 const EventListener* listener = *it;
496 if (restrict_to_extension_id.empty() ||
497 restrict_to_extension_id == listener->extension_id()) {
498 if (listener->process()) {
499 EventDispatchIdentifier dispatch_id(listener->GetBrowserContext(),
500 listener->extension_id());
501 if (!ContainsKey(already_dispatched, dispatch_id)) {
502 DispatchEventToProcess(listener->extension_id(),
503 listener->listener_url(),
504 listener->process(),
505 event);
512 void EventRouter::DispatchLazyEvent(
513 const std::string& extension_id,
514 const linked_ptr<Event>& event,
515 std::set<EventDispatchIdentifier>* already_dispatched) {
516 // Check both the original and the incognito browser context to see if we
517 // should load a lazy bg page to handle the event. The latter case
518 // occurs in the case of split-mode extensions.
519 const Extension* extension =
520 ExtensionRegistry::Get(browser_context_)->enabled_extensions().GetByID(
521 extension_id);
522 if (!extension)
523 return;
525 if (MaybeLoadLazyBackgroundPageToDispatchEvent(
526 browser_context_, extension, event)) {
527 already_dispatched->insert(std::make_pair(browser_context_, extension_id));
530 ExtensionsBrowserClient* browser_client = ExtensionsBrowserClient::Get();
531 if (browser_client->HasOffTheRecordContext(browser_context_) &&
532 IncognitoInfo::IsSplitMode(extension)) {
533 BrowserContext* incognito_context =
534 browser_client->GetOffTheRecordContext(browser_context_);
535 if (MaybeLoadLazyBackgroundPageToDispatchEvent(
536 incognito_context, extension, event)) {
537 already_dispatched->insert(
538 std::make_pair(incognito_context, extension_id));
543 void EventRouter::DispatchEventToProcess(const std::string& extension_id,
544 const GURL& listener_url,
545 content::RenderProcessHost* process,
546 const linked_ptr<Event>& event) {
547 BrowserContext* listener_context = process->GetBrowserContext();
548 ProcessMap* process_map = ProcessMap::Get(listener_context);
550 // NOTE: |extension| being NULL does not necessarily imply that this event
551 // shouldn't be dispatched. Events can be dispatched to WebUI and webviews as
552 // well. It all depends on what GetMostLikelyContextType returns.
553 const Extension* extension =
554 ExtensionRegistry::Get(browser_context_)->enabled_extensions().GetByID(
555 extension_id);
557 if (!extension && !extension_id.empty()) {
558 // Trying to dispatch an event to an extension that doesn't exist. The
559 // extension could have been removed, but we do not unregister it until the
560 // extension process is unloaded.
561 return;
564 if (extension) {
565 // Extension-specific checks.
566 // Firstly, if the event is for a URL, the Extension must have permission
567 // to access that URL.
568 if (!event->event_url.is_empty() &&
569 event->event_url.host() != extension->id() && // event for self is ok
570 !extension->permissions_data()
571 ->active_permissions()
572 ->HasEffectiveAccessToURL(event->event_url)) {
573 return;
575 // Secondly, if the event is for incognito mode, the Extension must be
576 // enabled in incognito mode.
577 if (!CanDispatchEventToBrowserContext(listener_context, extension, event)) {
578 return;
582 Feature::Context target_context =
583 process_map->GetMostLikelyContextType(extension, process->GetID());
585 // We shouldn't be dispatching an event to a webpage, since all such events
586 // (e.g. messaging) don't go through EventRouter.
587 DCHECK_NE(Feature::WEB_PAGE_CONTEXT, target_context)
588 << "Trying to dispatch event " << event->event_name << " to a webpage,"
589 << " but this shouldn't be possible";
591 Feature::Availability availability =
592 ExtensionAPI::GetSharedInstance()->IsAvailable(
593 event->event_name, extension, target_context, listener_url);
594 if (!availability.is_available()) {
595 // It shouldn't be possible to reach here, because access is checked on
596 // registration. However, for paranoia, check on dispatch as well.
597 NOTREACHED() << "Trying to dispatch event " << event->event_name
598 << " which the target does not have access to: "
599 << availability.message();
600 return;
603 if (!event->will_dispatch_callback.is_null() &&
604 !event->will_dispatch_callback.Run(listener_context, extension,
605 event->event_args.get())) {
606 return;
609 int event_id = g_extension_event_id.GetNext();
610 DispatchExtensionMessage(process, listener_context, extension_id, event_id,
611 event->event_name, event->event_args.get(),
612 event->user_gesture, event->filter_info);
614 if (extension) {
615 IncrementInFlightEvents(listener_context, extension, event_id,
616 event->event_name);
620 bool EventRouter::CanDispatchEventToBrowserContext(
621 BrowserContext* context,
622 const Extension* extension,
623 const linked_ptr<Event>& event) {
624 // Is this event from a different browser context than the renderer (ie, an
625 // incognito tab event sent to a normal process, or vice versa).
626 bool cross_incognito = event->restrict_to_browser_context &&
627 context != event->restrict_to_browser_context;
628 if (!cross_incognito)
629 return true;
630 return ExtensionsBrowserClient::Get()->CanExtensionCrossIncognito(
631 extension, context);
634 bool EventRouter::MaybeLoadLazyBackgroundPageToDispatchEvent(
635 BrowserContext* context,
636 const Extension* extension,
637 const linked_ptr<Event>& event) {
638 if (!CanDispatchEventToBrowserContext(context, extension, event))
639 return false;
641 LazyBackgroundTaskQueue* queue = ExtensionSystem::Get(
642 context)->lazy_background_task_queue();
643 if (queue->ShouldEnqueueTask(context, extension)) {
644 linked_ptr<Event> dispatched_event(event);
646 // If there's a dispatch callback, call it now (rather than dispatch time)
647 // to avoid lifetime issues. Use a separate copy of the event args, so they
648 // last until the event is dispatched.
649 if (!event->will_dispatch_callback.is_null()) {
650 dispatched_event.reset(event->DeepCopy());
651 if (!dispatched_event->will_dispatch_callback.Run(
652 context, extension, dispatched_event->event_args.get())) {
653 // The event has been canceled.
654 return true;
656 // Ensure we don't call it again at dispatch time.
657 dispatched_event->will_dispatch_callback.Reset();
660 queue->AddPendingTask(context, extension->id(),
661 base::Bind(&EventRouter::DispatchPendingEvent,
662 base::Unretained(this), dispatched_event));
663 return true;
666 return false;
669 // static
670 void EventRouter::IncrementInFlightEventsOnUI(void* browser_context_id,
671 const std::string& extension_id,
672 int event_id,
673 const std::string& event_name) {
674 DCHECK_CURRENTLY_ON(BrowserThread::UI);
675 BrowserContext* browser_context =
676 reinterpret_cast<BrowserContext*>(browser_context_id);
677 if (!ExtensionsBrowserClient::Get()->IsValidContext(browser_context))
678 return;
679 EventRouter* event_router = EventRouter::Get(browser_context);
680 if (!event_router)
681 return;
682 const Extension* extension =
683 ExtensionRegistry::Get(browser_context)->enabled_extensions().GetByID(
684 extension_id);
685 if (!extension)
686 return;
687 event_router->IncrementInFlightEvents(browser_context, extension, event_id,
688 event_name);
691 void EventRouter::IncrementInFlightEvents(BrowserContext* context,
692 const Extension* extension,
693 int event_id,
694 const std::string& event_name) {
695 // TODO(chirantan): Turn this on once crbug.com/464513 is fixed.
696 // DCHECK_CURRENTLY_ON(BrowserThread::UI);
698 // Only increment in-flight events if the lazy background page is active,
699 // because that's the only time we'll get an ACK.
700 if (BackgroundInfo::HasLazyBackgroundPage(extension)) {
701 ProcessManager* pm = ProcessManager::Get(context);
702 ExtensionHost* host = pm->GetBackgroundHostForExtension(extension->id());
703 if (host) {
704 pm->IncrementLazyKeepaliveCount(extension);
705 host->OnBackgroundEventDispatched(event_name, event_id);
710 void EventRouter::OnEventAck(BrowserContext* context,
711 const std::string& extension_id) {
712 ProcessManager* pm = ProcessManager::Get(context);
713 ExtensionHost* host = pm->GetBackgroundHostForExtension(extension_id);
714 // The event ACK is routed to the background host, so this should never be
715 // NULL.
716 CHECK(host);
717 // TODO(mpcomplete): We should never get this message unless
718 // HasLazyBackgroundPage is true. Find out why we're getting it anyway.
719 if (host->extension() &&
720 BackgroundInfo::HasLazyBackgroundPage(host->extension()))
721 pm->DecrementLazyKeepaliveCount(host->extension());
724 void EventRouter::DispatchPendingEvent(const linked_ptr<Event>& event,
725 ExtensionHost* host) {
726 if (!host)
727 return;
729 if (listeners_.HasProcessListener(host->render_process_host(),
730 host->extension()->id())) {
731 // URL events cannot be lazy therefore can't be pending, hence the GURL().
732 DispatchEventToProcess(
733 host->extension()->id(), GURL(), host->render_process_host(), event);
737 void EventRouter::Observe(int type,
738 const content::NotificationSource& source,
739 const content::NotificationDetails& details) {
740 switch (type) {
741 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED:
742 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
743 content::RenderProcessHost* renderer =
744 content::Source<content::RenderProcessHost>(source).ptr();
745 // Remove all event listeners associated with this renderer.
746 listeners_.RemoveListenersForProcess(renderer);
747 break;
749 case extensions::NOTIFICATION_EXTENSION_ENABLED: {
750 // If the extension has a lazy background page, make sure it gets loaded
751 // to register the events the extension is interested in.
752 const Extension* extension =
753 content::Details<const Extension>(details).ptr();
754 if (BackgroundInfo::HasLazyBackgroundPage(extension)) {
755 LazyBackgroundTaskQueue* queue = ExtensionSystem::Get(
756 browser_context_)->lazy_background_task_queue();
757 queue->AddPendingTask(browser_context_, extension->id(),
758 base::Bind(&DoNothing));
760 break;
762 default:
763 NOTREACHED();
767 void EventRouter::OnExtensionLoaded(content::BrowserContext* browser_context,
768 const Extension* extension) {
769 // Add all registered lazy listeners to our cache.
770 std::set<std::string> registered_events =
771 GetRegisteredEvents(extension->id());
772 listeners_.LoadUnfilteredLazyListeners(extension->id(), registered_events);
773 const DictionaryValue* filtered_events = GetFilteredEvents(extension->id());
774 if (filtered_events)
775 listeners_.LoadFilteredLazyListeners(extension->id(), *filtered_events);
778 void EventRouter::OnExtensionUnloaded(content::BrowserContext* browser_context,
779 const Extension* extension,
780 UnloadedExtensionInfo::Reason reason) {
781 // Remove all registered listeners from our cache.
782 listeners_.RemoveListenersForExtension(extension->id());
785 Event::Event(const std::string& event_name,
786 scoped_ptr<base::ListValue> event_args)
787 : event_name(event_name),
788 event_args(event_args.Pass()),
789 restrict_to_browser_context(NULL),
790 user_gesture(EventRouter::USER_GESTURE_UNKNOWN) {
791 DCHECK(this->event_args.get());
794 Event::Event(const std::string& event_name,
795 scoped_ptr<base::ListValue> event_args,
796 BrowserContext* restrict_to_browser_context)
797 : event_name(event_name),
798 event_args(event_args.Pass()),
799 restrict_to_browser_context(restrict_to_browser_context),
800 user_gesture(EventRouter::USER_GESTURE_UNKNOWN) {
801 DCHECK(this->event_args.get());
804 Event::Event(const std::string& event_name,
805 scoped_ptr<ListValue> event_args,
806 BrowserContext* restrict_to_browser_context,
807 const GURL& event_url,
808 EventRouter::UserGestureState user_gesture,
809 const EventFilteringInfo& filter_info)
810 : event_name(event_name),
811 event_args(event_args.Pass()),
812 restrict_to_browser_context(restrict_to_browser_context),
813 event_url(event_url),
814 user_gesture(user_gesture),
815 filter_info(filter_info) {
816 DCHECK(this->event_args.get());
819 Event::~Event() {}
821 Event* Event::DeepCopy() {
822 Event* copy = new Event(event_name,
823 scoped_ptr<base::ListValue>(event_args->DeepCopy()),
824 restrict_to_browser_context,
825 event_url,
826 user_gesture,
827 filter_info);
828 copy->will_dispatch_callback = will_dispatch_callback;
829 return copy;
832 EventListenerInfo::EventListenerInfo(const std::string& event_name,
833 const std::string& extension_id,
834 const GURL& listener_url,
835 content::BrowserContext* browser_context)
836 : event_name(event_name),
837 extension_id(extension_id),
838 listener_url(listener_url),
839 browser_context(browser_context) {
842 } // namespace extensions