Revert "Fix broken channel icon in chrome://help on CrOS" and try again
[chromium-blink-merge.git] / extensions / browser / event_router.h
blobc7fad750d94e837900c67c7be7ca18d5b1a5f733
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 #ifndef EXTENSIONS_BROWSER_EVENT_ROUTER_H_
6 #define EXTENSIONS_BROWSER_EVENT_ROUTER_H_
8 #include <map>
9 #include <set>
10 #include <string>
11 #include <utility>
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/containers/hash_tables.h"
16 #include "base/memory/linked_ptr.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/scoped_observer.h"
19 #include "base/values.h"
20 #include "components/keyed_service/core/keyed_service.h"
21 #include "content/public/browser/notification_observer.h"
22 #include "content/public/browser/notification_registrar.h"
23 #include "content/public/browser/render_process_host_observer.h"
24 #include "extensions/browser/event_listener_map.h"
25 #include "extensions/browser/extension_event_histogram_value.h"
26 #include "extensions/browser/extension_registry_observer.h"
27 #include "extensions/common/event_filtering_info.h"
28 #include "ipc/ipc_sender.h"
29 #include "url/gurl.h"
31 class GURL;
32 class PrefService;
34 namespace content {
35 class BrowserContext;
36 class RenderProcessHost;
39 namespace extensions {
40 class ActivityLog;
41 class Extension;
42 class ExtensionHost;
43 class ExtensionPrefs;
44 class ExtensionRegistry;
46 struct Event;
47 struct EventDispatchInfo;
48 struct EventListenerInfo;
50 class EventRouter : public KeyedService,
51 public content::NotificationObserver,
52 public ExtensionRegistryObserver,
53 public EventListenerMap::Delegate,
54 public content::RenderProcessHostObserver {
55 public:
56 // These constants convey the state of our knowledge of whether we're in
57 // a user-caused gesture as part of DispatchEvent.
58 enum UserGestureState {
59 USER_GESTURE_UNKNOWN = 0,
60 USER_GESTURE_ENABLED = 1,
61 USER_GESTURE_NOT_ENABLED = 2,
64 // The pref key for the list of event names for which an extension has
65 // registered from its lazy background page.
66 static const char kRegisteredEvents[];
68 // Observers register interest in events with a particular name and are
69 // notified when a listener is added or removed. Observers are matched by
70 // the base name of the event (e.g. adding an event listener for event name
71 // "foo.onBar/123" will trigger observers registered for "foo.onBar").
72 class Observer {
73 public:
74 // Called when a listener is added.
75 virtual void OnListenerAdded(const EventListenerInfo& details) {}
76 // Called when a listener is removed.
77 virtual void OnListenerRemoved(const EventListenerInfo& details) {}
80 // Gets the EventRouter for |browser_context|.
81 static EventRouter* Get(content::BrowserContext* browser_context);
83 // Converts event names like "foo.onBar/123" into "foo.onBar". Event names
84 // without a "/" are returned unchanged.
85 static std::string GetBaseEventName(const std::string& full_event_name);
87 // Sends an event via ipc_sender to the given extension. Can be called on any
88 // thread.
90 // It is very rare to call this function directly. Instead use the instance
91 // methods BroadcastEvent or DispatchEventToExtension.
92 static void DispatchEventToSender(IPC::Sender* ipc_sender,
93 void* browser_context_id,
94 const std::string& extension_id,
95 events::HistogramValue histogram_value,
96 const std::string& event_name,
97 scoped_ptr<base::ListValue> event_args,
98 UserGestureState user_gesture,
99 const EventFilteringInfo& info);
101 // An EventRouter is shared between |browser_context| and its associated
102 // incognito context. |extension_prefs| may be NULL in tests.
103 EventRouter(content::BrowserContext* browser_context,
104 ExtensionPrefs* extension_prefs);
105 ~EventRouter() override;
107 // Add or remove an extension as an event listener for |event_name|.
109 // Note that multiple extensions can share a process due to process
110 // collapsing. Also, a single extension can have 2 processes if it is a split
111 // mode extension.
112 void AddEventListener(const std::string& event_name,
113 content::RenderProcessHost* process,
114 const std::string& extension_id);
115 void RemoveEventListener(const std::string& event_name,
116 content::RenderProcessHost* process,
117 const std::string& extension_id);
119 // Add or remove a URL as an event listener for |event_name|.
120 void AddEventListenerForURL(const std::string& event_name,
121 content::RenderProcessHost* process,
122 const GURL& listener_url);
123 void RemoveEventListenerForURL(const std::string& event_name,
124 content::RenderProcessHost* process,
125 const GURL& listener_url);
127 EventListenerMap& listeners() { return listeners_; }
129 // Registers an observer to be notified when an event listener for
130 // |event_name| is added or removed. There can currently be only one observer
131 // for each distinct |event_name|.
132 void RegisterObserver(Observer* observer,
133 const std::string& event_name);
135 // Unregisters an observer from all events.
136 void UnregisterObserver(Observer* observer);
138 // Add or remove the extension as having a lazy background page that listens
139 // to the event. The difference from the above methods is that these will be
140 // remembered even after the process goes away. We use this list to decide
141 // which extension pages to load when dispatching an event.
142 void AddLazyEventListener(const std::string& event_name,
143 const std::string& extension_id);
144 void RemoveLazyEventListener(const std::string& event_name,
145 const std::string& extension_id);
147 // If |add_lazy_listener| is true also add the lazy version of this listener.
148 void AddFilteredEventListener(const std::string& event_name,
149 content::RenderProcessHost* process,
150 const std::string& extension_id,
151 const base::DictionaryValue& filter,
152 bool add_lazy_listener);
154 // If |remove_lazy_listener| is true also remove the lazy version of this
155 // listener.
156 void RemoveFilteredEventListener(const std::string& event_name,
157 content::RenderProcessHost* process,
158 const std::string& extension_id,
159 const base::DictionaryValue& filter,
160 bool remove_lazy_listener);
162 // Returns true if there is at least one listener for the given event.
163 bool HasEventListener(const std::string& event_name);
165 // Returns true if the extension is listening to the given event.
166 bool ExtensionHasEventListener(const std::string& extension_id,
167 const std::string& event_name);
169 // Return or set the list of events for which the given extension has
170 // registered.
171 std::set<std::string> GetRegisteredEvents(const std::string& extension_id);
172 void SetRegisteredEvents(const std::string& extension_id,
173 const std::set<std::string>& events);
175 // Broadcasts an event to every listener registered for that event.
176 virtual void BroadcastEvent(scoped_ptr<Event> event);
178 // Dispatches an event to the given extension.
179 virtual void DispatchEventToExtension(const std::string& extension_id,
180 scoped_ptr<Event> event);
182 // Dispatches |event| to the given extension as if the extension has a lazy
183 // listener for it. NOTE: This should be used rarely, for dispatching events
184 // to extensions that haven't had a chance to add their own listeners yet, eg:
185 // newly installed extensions.
186 void DispatchEventWithLazyListener(const std::string& extension_id,
187 scoped_ptr<Event> event);
189 // Record the Event Ack from the renderer. (One less event in-flight.)
190 void OnEventAck(content::BrowserContext* context,
191 const std::string& extension_id);
193 // Reports UMA for an event dispatched to |extension| with histogram value
194 // |histogram_value|. Must be called on the UI thread.
196 // |did_enqueue| should be true if the event was queued waiting for a process
197 // to start, like an event page.
198 void ReportEvent(events::HistogramValue histogram_value,
199 const Extension* extension,
200 bool did_enqueue);
202 private:
203 friend class EventRouterTest;
205 // The extension and process that contains the event listener for a given
206 // event.
207 struct ListenerProcess;
209 // A map between an event name and a set of extensions that are listening
210 // to that event.
211 typedef std::map<std::string, std::set<ListenerProcess> > ListenerMap;
213 // An identifier for an event dispatch that is used to prevent double dispatch
214 // due to race conditions between the direct and lazy dispatch paths.
215 typedef std::pair<const content::BrowserContext*, std::string>
216 EventDispatchIdentifier;
218 // TODO(gdk): Document this.
219 static void DispatchExtensionMessage(
220 IPC::Sender* ipc_sender,
221 void* browser_context_id,
222 const std::string& extension_id,
223 int event_id,
224 const std::string& event_name,
225 base::ListValue* event_args,
226 UserGestureState user_gesture,
227 const extensions::EventFilteringInfo& info);
229 void Observe(int type,
230 const content::NotificationSource& source,
231 const content::NotificationDetails& details) override;
232 // ExtensionRegistryObserver implementation.
233 void OnExtensionLoaded(content::BrowserContext* browser_context,
234 const Extension* extension) override;
235 void OnExtensionUnloaded(content::BrowserContext* browser_context,
236 const Extension* extension,
237 UnloadedExtensionInfo::Reason reason) override;
239 // Returns true if the given listener map contains a event listeners for
240 // the given event. If |extension_id| is non-empty, we also check that that
241 // extension is one of the listeners.
242 bool HasEventListenerImpl(const ListenerMap& listeners,
243 const std::string& extension_id,
244 const std::string& event_name);
246 // Shared by all event dispatch methods. If |restrict_to_extension_id| is
247 // empty, the event is broadcast. An event that just came off the pending
248 // list may not be delayed again.
249 void DispatchEventImpl(const std::string& restrict_to_extension_id,
250 const linked_ptr<Event>& event);
252 // Ensures that all lazy background pages that are interested in the given
253 // event are loaded, and queues the event if the page is not ready yet.
254 // Inserts an EventDispatchIdentifier into |already_dispatched| for each lazy
255 // event dispatch that is queued.
256 void DispatchLazyEvent(const std::string& extension_id,
257 const linked_ptr<Event>& event,
258 std::set<EventDispatchIdentifier>* already_dispatched,
259 const base::DictionaryValue* listener_filter);
261 // Dispatches the event to the specified extension or URL running in
262 // |process|.
263 void DispatchEventToProcess(const std::string& extension_id,
264 const GURL& listener_url,
265 content::RenderProcessHost* process,
266 const linked_ptr<Event>& event,
267 const base::DictionaryValue* listener_filter,
268 bool did_enqueue);
270 // Returns false when the event is scoped to a context and the listening
271 // extension does not have access to events from that context. Also fills
272 // |event_args| with the proper arguments to send, which may differ if
273 // the event crosses the incognito boundary.
274 bool CanDispatchEventToBrowserContext(content::BrowserContext* context,
275 const Extension* extension,
276 const linked_ptr<Event>& event);
278 // Possibly loads given extension's background page in preparation to
279 // dispatch an event. Returns true if the event was queued for subsequent
280 // dispatch, false otherwise.
281 bool MaybeLoadLazyBackgroundPageToDispatchEvent(
282 content::BrowserContext* context,
283 const Extension* extension,
284 const linked_ptr<Event>& event,
285 const base::DictionaryValue* listener_filter);
287 // Adds a filter to an event.
288 void AddFilterToEvent(const std::string& event_name,
289 const std::string& extension_id,
290 const base::DictionaryValue* filter);
292 // Removes a filter from an event.
293 void RemoveFilterFromEvent(const std::string& event_name,
294 const std::string& extension_id,
295 const base::DictionaryValue* filter);
297 // Returns the dictionary of event filters that the given extension has
298 // registered.
299 const base::DictionaryValue* GetFilteredEvents(
300 const std::string& extension_id);
302 // Track the dispatched events that have not yet sent an ACK from the
303 // renderer.
304 void IncrementInFlightEvents(content::BrowserContext* context,
305 const Extension* extension,
306 int event_id,
307 const std::string& event_name);
309 // static
310 static void DoDispatchEventToSenderBookkeepingOnUI(
311 void* browser_context_id,
312 const std::string& extension_id,
313 int event_id,
314 events::HistogramValue histogram_value,
315 const std::string& event_name);
317 void DispatchPendingEvent(const linked_ptr<Event>& event,
318 ExtensionHost* host);
320 // Implementation of EventListenerMap::Delegate.
321 void OnListenerAdded(const EventListener* listener) override;
322 void OnListenerRemoved(const EventListener* listener) override;
324 // RenderProcessHostObserver implementation.
325 void RenderProcessExited(content::RenderProcessHost* host,
326 base::TerminationStatus status,
327 int exit_code) override;
328 void RenderProcessHostDestroyed(content::RenderProcessHost* host) override;
330 content::BrowserContext* browser_context_;
332 // The ExtensionPrefs associated with |browser_context_|. May be NULL in
333 // tests.
334 ExtensionPrefs* extension_prefs_;
336 content::NotificationRegistrar registrar_;
338 ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
339 extension_registry_observer_;
341 EventListenerMap listeners_;
343 // Map from base event name to observer.
344 typedef base::hash_map<std::string, Observer*> ObserverMap;
345 ObserverMap observers_;
347 std::set<content::RenderProcessHost*> observed_process_set_;
349 DISALLOW_COPY_AND_ASSIGN(EventRouter);
352 struct Event {
353 // This callback should return true if the event should be dispatched to the
354 // given context and extension, and false otherwise.
355 typedef base::Callback<bool(content::BrowserContext*,
356 const Extension*,
357 Event*,
358 const base::DictionaryValue*)>
359 WillDispatchCallback;
361 // The identifier for the event, for histograms. In most cases this
362 // correlates 1:1 with |event_name|, in some cases events will generate
363 // their own names, but they cannot generate their own identifier.
364 events::HistogramValue histogram_value;
366 // The event to dispatch.
367 std::string event_name;
369 // Arguments to send to the event listener.
370 scoped_ptr<base::ListValue> event_args;
372 // If non-NULL, then the event will not be sent to other BrowserContexts
373 // unless the extension has permission (e.g. incognito tab update -> normal
374 // tab only works if extension is allowed incognito access).
375 content::BrowserContext* restrict_to_browser_context;
377 // If not empty, the event is only sent to extensions with host permissions
378 // for this url.
379 GURL event_url;
381 // Whether a user gesture triggered the event.
382 EventRouter::UserGestureState user_gesture;
384 // Extra information used to filter which events are sent to the listener.
385 EventFilteringInfo filter_info;
387 // If specified, this is called before dispatching an event to each
388 // extension. The third argument is a mutable reference to event_args,
389 // allowing the caller to provide different arguments depending on the
390 // extension and profile. This is guaranteed to be called synchronously with
391 // DispatchEvent, so callers don't need to worry about lifetime.
393 // NOTE: the Extension argument to this may be NULL because it's possible for
394 // this event to be dispatched to non-extension processes, like WebUI.
395 WillDispatchCallback will_dispatch_callback;
397 Event(events::HistogramValue histogram_value,
398 const std::string& event_name,
399 scoped_ptr<base::ListValue> event_args);
401 Event(events::HistogramValue histogram_value,
402 const std::string& event_name,
403 scoped_ptr<base::ListValue> event_args,
404 content::BrowserContext* restrict_to_browser_context);
406 Event(events::HistogramValue histogram_value,
407 const std::string& event_name,
408 scoped_ptr<base::ListValue> event_args,
409 content::BrowserContext* restrict_to_browser_context,
410 const GURL& event_url,
411 EventRouter::UserGestureState user_gesture,
412 const EventFilteringInfo& info);
414 ~Event();
416 // Makes a deep copy of this instance. Ownership is transferred to the
417 // caller.
418 Event* DeepCopy();
421 struct EventListenerInfo {
422 EventListenerInfo(const std::string& event_name,
423 const std::string& extension_id,
424 const GURL& listener_url,
425 content::BrowserContext* browser_context);
426 // The event name including any sub-event, e.g. "runtime.onStartup" or
427 // "webRequest.onCompleted/123".
428 const std::string event_name;
430 const std::string extension_id;
431 const GURL listener_url;
432 content::BrowserContext* browser_context;
435 } // namespace extensions
437 #endif // EXTENSIONS_BROWSER_EVENT_ROUTER_H_