Finish refactoring of DomCodeToUsLayoutKeyboardCode().
[chromium-blink-merge.git] / extensions / browser / event_router.h
blob8164d91523b901d56624a39e679a2ee8908e17dc
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"
30 class GURL;
31 class PrefService;
33 namespace content {
34 class BrowserContext;
35 class RenderProcessHost;
38 namespace extensions {
39 class ActivityLog;
40 class Extension;
41 class ExtensionHost;
42 class ExtensionPrefs;
43 class ExtensionRegistry;
45 struct Event;
46 struct EventDispatchInfo;
47 struct EventListenerInfo;
49 class EventRouter : public KeyedService,
50 public content::NotificationObserver,
51 public ExtensionRegistryObserver,
52 public EventListenerMap::Delegate,
53 public content::RenderProcessHostObserver {
54 public:
55 // These constants convey the state of our knowledge of whether we're in
56 // a user-caused gesture as part of DispatchEvent.
57 enum UserGestureState {
58 USER_GESTURE_UNKNOWN = 0,
59 USER_GESTURE_ENABLED = 1,
60 USER_GESTURE_NOT_ENABLED = 2,
63 // The pref key for the list of event names for which an extension has
64 // registered from its lazy background page.
65 static const char kRegisteredEvents[];
67 // Observers register interest in events with a particular name and are
68 // notified when a listener is added or removed. Observers are matched by
69 // the base name of the event (e.g. adding an event listener for event name
70 // "foo.onBar/123" will trigger observers registered for "foo.onBar").
71 class Observer {
72 public:
73 // Called when a listener is added.
74 virtual void OnListenerAdded(const EventListenerInfo& details) {}
75 // Called when a listener is removed.
76 virtual void OnListenerRemoved(const EventListenerInfo& details) {}
79 // Gets the EventRouter for |browser_context|.
80 static EventRouter* Get(content::BrowserContext* browser_context);
82 // Converts event names like "foo.onBar/123" into "foo.onBar". Event names
83 // without a "/" are returned unchanged.
84 static std::string GetBaseEventName(const std::string& full_event_name);
86 // Sends an event via ipc_sender to the given extension. Can be called on any
87 // thread.
88 static void DispatchEvent(IPC::Sender* ipc_sender,
89 void* browser_context_id,
90 const std::string& extension_id,
91 const std::string& event_name,
92 scoped_ptr<base::ListValue> event_args,
93 UserGestureState user_gesture,
94 const EventFilteringInfo& info);
96 // An EventRouter is shared between |browser_context| and its associated
97 // incognito context. |extension_prefs| may be NULL in tests.
98 EventRouter(content::BrowserContext* browser_context,
99 ExtensionPrefs* extension_prefs);
100 ~EventRouter() override;
102 // Add or remove an extension as an event listener for |event_name|.
104 // Note that multiple extensions can share a process due to process
105 // collapsing. Also, a single extension can have 2 processes if it is a split
106 // mode extension.
107 void AddEventListener(const std::string& event_name,
108 content::RenderProcessHost* process,
109 const std::string& extension_id);
110 void RemoveEventListener(const std::string& event_name,
111 content::RenderProcessHost* process,
112 const std::string& extension_id);
114 // Add or remove a URL as an event listener for |event_name|.
115 void AddEventListenerForURL(const std::string& event_name,
116 content::RenderProcessHost* process,
117 const GURL& listener_url);
118 void RemoveEventListenerForURL(const std::string& event_name,
119 content::RenderProcessHost* process,
120 const GURL& listener_url);
122 EventListenerMap& listeners() { return listeners_; }
124 // Registers an observer to be notified when an event listener for
125 // |event_name| is added or removed. There can currently be only one observer
126 // for each distinct |event_name|.
127 void RegisterObserver(Observer* observer,
128 const std::string& event_name);
130 // Unregisters an observer from all events.
131 void UnregisterObserver(Observer* observer);
133 // Add or remove the extension as having a lazy background page that listens
134 // to the event. The difference from the above methods is that these will be
135 // remembered even after the process goes away. We use this list to decide
136 // which extension pages to load when dispatching an event.
137 void AddLazyEventListener(const std::string& event_name,
138 const std::string& extension_id);
139 void RemoveLazyEventListener(const std::string& event_name,
140 const std::string& extension_id);
142 // If |add_lazy_listener| is true also add the lazy version of this listener.
143 void AddFilteredEventListener(const std::string& event_name,
144 content::RenderProcessHost* process,
145 const std::string& extension_id,
146 const base::DictionaryValue& filter,
147 bool add_lazy_listener);
149 // If |remove_lazy_listener| is true also remove the lazy version of this
150 // listener.
151 void RemoveFilteredEventListener(const std::string& event_name,
152 content::RenderProcessHost* process,
153 const std::string& extension_id,
154 const base::DictionaryValue& filter,
155 bool remove_lazy_listener);
157 // Returns true if there is at least one listener for the given event.
158 bool HasEventListener(const std::string& event_name);
160 // Returns true if the extension is listening to the given event.
161 bool ExtensionHasEventListener(const std::string& extension_id,
162 const std::string& event_name);
164 // Return or set the list of events for which the given extension has
165 // registered.
166 std::set<std::string> GetRegisteredEvents(const std::string& extension_id);
167 void SetRegisteredEvents(const std::string& extension_id,
168 const std::set<std::string>& events);
170 // Broadcasts an event to every listener registered for that event.
171 virtual void BroadcastEvent(scoped_ptr<Event> event);
173 // Dispatches an event to the given extension.
174 virtual void DispatchEventToExtension(const std::string& extension_id,
175 scoped_ptr<Event> event);
177 // Dispatches |event| to the given extension as if the extension has a lazy
178 // listener for it. NOTE: This should be used rarely, for dispatching events
179 // to extensions that haven't had a chance to add their own listeners yet, eg:
180 // newly installed extensions.
181 void DispatchEventWithLazyListener(const std::string& extension_id,
182 scoped_ptr<Event> event);
184 // Record the Event Ack from the renderer. (One less event in-flight.)
185 void OnEventAck(content::BrowserContext* context,
186 const std::string& extension_id);
188 private:
189 friend class EventRouterTest;
191 // The extension and process that contains the event listener for a given
192 // event.
193 struct ListenerProcess;
195 // A map between an event name and a set of extensions that are listening
196 // to that event.
197 typedef std::map<std::string, std::set<ListenerProcess> > ListenerMap;
199 // An identifier for an event dispatch that is used to prevent double dispatch
200 // due to race conditions between the direct and lazy dispatch paths.
201 typedef std::pair<const content::BrowserContext*, std::string>
202 EventDispatchIdentifier;
204 // TODO(gdk): Document this.
205 static void DispatchExtensionMessage(
206 IPC::Sender* ipc_sender,
207 void* browser_context_id,
208 const std::string& extension_id,
209 int event_id,
210 const std::string& event_name,
211 base::ListValue* event_args,
212 UserGestureState user_gesture,
213 const extensions::EventFilteringInfo& info);
215 void Observe(int type,
216 const content::NotificationSource& source,
217 const content::NotificationDetails& details) override;
218 // ExtensionRegistryObserver implementation.
219 void OnExtensionLoaded(content::BrowserContext* browser_context,
220 const Extension* extension) override;
221 void OnExtensionUnloaded(content::BrowserContext* browser_context,
222 const Extension* extension,
223 UnloadedExtensionInfo::Reason reason) override;
225 // Returns true if the given listener map contains a event listeners for
226 // the given event. If |extension_id| is non-empty, we also check that that
227 // extension is one of the listeners.
228 bool HasEventListenerImpl(const ListenerMap& listeners,
229 const std::string& extension_id,
230 const std::string& event_name);
232 // Shared by DispatchEvent*. If |restrict_to_extension_id| is empty, the
233 // event is broadcast.
234 // An event that just came off the pending list may not be delayed again.
235 void DispatchEventImpl(const std::string& restrict_to_extension_id,
236 const linked_ptr<Event>& event);
238 // Ensures that all lazy background pages that are interested in the given
239 // event are loaded, and queues the event if the page is not ready yet.
240 // Inserts an EventDispatchIdentifier into |already_dispatched| for each lazy
241 // event dispatch that is queued.
242 void DispatchLazyEvent(const std::string& extension_id,
243 const linked_ptr<Event>& event,
244 std::set<EventDispatchIdentifier>* already_dispatched);
246 // Dispatches the event to the specified extension or URL running in
247 // |process|.
248 void DispatchEventToProcess(const std::string& extension_id,
249 const GURL& listener_url,
250 content::RenderProcessHost* process,
251 const linked_ptr<Event>& event);
253 // Returns false when the event is scoped to a context and the listening
254 // extension does not have access to events from that context. Also fills
255 // |event_args| with the proper arguments to send, which may differ if
256 // the event crosses the incognito boundary.
257 bool CanDispatchEventToBrowserContext(content::BrowserContext* context,
258 const Extension* extension,
259 const linked_ptr<Event>& event);
261 // Possibly loads given extension's background page in preparation to
262 // dispatch an event. Returns true if the event was queued for subsequent
263 // dispatch, false otherwise.
264 bool MaybeLoadLazyBackgroundPageToDispatchEvent(
265 content::BrowserContext* context,
266 const Extension* extension,
267 const linked_ptr<Event>& event);
269 // Adds a filter to an event.
270 void AddFilterToEvent(const std::string& event_name,
271 const std::string& extension_id,
272 const base::DictionaryValue* filter);
274 // Removes a filter from an event.
275 void RemoveFilterFromEvent(const std::string& event_name,
276 const std::string& extension_id,
277 const base::DictionaryValue* filter);
279 // Returns the dictionary of event filters that the given extension has
280 // registered.
281 const base::DictionaryValue* GetFilteredEvents(
282 const std::string& extension_id);
284 // Track the dispatched events that have not yet sent an ACK from the
285 // renderer.
286 void IncrementInFlightEvents(content::BrowserContext* context,
287 const Extension* extension,
288 int event_id,
289 const std::string& event_name);
291 // static
292 static void IncrementInFlightEventsOnUI(void* browser_context_id,
293 const std::string& extension_id,
294 int event_id,
295 const std::string& event_name);
297 void DispatchPendingEvent(const linked_ptr<Event>& event,
298 ExtensionHost* host);
300 // Implementation of EventListenerMap::Delegate.
301 void OnListenerAdded(const EventListener* listener) override;
302 void OnListenerRemoved(const EventListener* listener) override;
304 // RenderProcessHostObserver implementation.
305 void RenderProcessExited(content::RenderProcessHost* host,
306 base::TerminationStatus status,
307 int exit_code) override;
308 void RenderProcessHostDestroyed(content::RenderProcessHost* host) override;
310 content::BrowserContext* browser_context_;
312 // The ExtensionPrefs associated with |browser_context_|. May be NULL in
313 // tests.
314 ExtensionPrefs* extension_prefs_;
316 content::NotificationRegistrar registrar_;
318 ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
319 extension_registry_observer_;
321 EventListenerMap listeners_;
323 // Map from base event name to observer.
324 typedef base::hash_map<std::string, Observer*> ObserverMap;
325 ObserverMap observers_;
327 std::set<content::RenderProcessHost*> observed_process_set_;
329 DISALLOW_COPY_AND_ASSIGN(EventRouter);
332 struct Event {
333 // This callback should return true if the event should be dispatched to the
334 // given context and extension, and false otherwise.
335 typedef base::Callback<bool(content::BrowserContext*,
336 const Extension*,
337 base::ListValue*)> WillDispatchCallback;
339 // The identifier for the event, for histograms. In most cases this
340 // correlates 1:1 with |event_name|, in some cases events will generate
341 // their own names, but they cannot generate their own identifier.
342 events::HistogramValue histogram_value;
344 // The event to dispatch.
345 std::string event_name;
347 // Arguments to send to the event listener.
348 scoped_ptr<base::ListValue> event_args;
350 // If non-NULL, then the event will not be sent to other BrowserContexts
351 // unless the extension has permission (e.g. incognito tab update -> normal
352 // tab only works if extension is allowed incognito access).
353 content::BrowserContext* restrict_to_browser_context;
355 // If not empty, the event is only sent to extensions with host permissions
356 // for this url.
357 GURL event_url;
359 // Whether a user gesture triggered the event.
360 EventRouter::UserGestureState user_gesture;
362 // Extra information used to filter which events are sent to the listener.
363 EventFilteringInfo filter_info;
365 // If specified, this is called before dispatching an event to each
366 // extension. The third argument is a mutable reference to event_args,
367 // allowing the caller to provide different arguments depending on the
368 // extension and profile. This is guaranteed to be called synchronously with
369 // DispatchEvent, so callers don't need to worry about lifetime.
371 // NOTE: the Extension argument to this may be NULL because it's possible for
372 // this event to be dispatched to non-extension processes, like WebUI.
373 WillDispatchCallback will_dispatch_callback;
375 Event(events::HistogramValue histogram_value,
376 const std::string& event_name,
377 scoped_ptr<base::ListValue> event_args);
379 Event(events::HistogramValue histogram_value,
380 const std::string& event_name,
381 scoped_ptr<base::ListValue> event_args,
382 content::BrowserContext* restrict_to_browser_context);
384 Event(events::HistogramValue histogram_value,
385 const std::string& event_name,
386 scoped_ptr<base::ListValue> event_args,
387 content::BrowserContext* restrict_to_browser_context,
388 const GURL& event_url,
389 EventRouter::UserGestureState user_gesture,
390 const EventFilteringInfo& info);
392 ~Event();
394 // Makes a deep copy of this instance. Ownership is transferred to the
395 // caller.
396 Event* DeepCopy();
399 struct EventListenerInfo {
400 EventListenerInfo(const std::string& event_name,
401 const std::string& extension_id,
402 const GURL& listener_url,
403 content::BrowserContext* browser_context);
404 // The event name including any sub-event, e.g. "runtime.onStartup" or
405 // "webRequest.onCompleted/123".
406 const std::string event_name;
408 const std::string extension_id;
409 const GURL listener_url;
410 content::BrowserContext* browser_context;
413 } // namespace extensions
415 #endif // EXTENSIONS_BROWSER_EVENT_ROUTER_H_