1 // Copyright 2014 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/renderer/event_bindings.h"
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/containers/scoped_ptr_map.h"
13 #include "base/lazy_instance.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "components/crx_file/id_util.h"
16 #include "content/public/child/v8_value_converter.h"
17 #include "content/public/renderer/render_frame.h"
18 #include "content/public/renderer/render_thread.h"
19 #include "content/public/renderer/render_view.h"
20 #include "extensions/common/event_filter.h"
21 #include "extensions/common/extension.h"
22 #include "extensions/common/extension_messages.h"
23 #include "extensions/common/value_counter.h"
24 #include "extensions/renderer/extension_frame_helper.h"
25 #include "extensions/renderer/script_context.h"
28 namespace extensions
{
32 // A map of event names to the number of contexts listening to that event.
33 // We notify the browser about event listeners when we transition between 0
35 typedef std::map
<std::string
, int> EventListenerCounts
;
37 // A map of extension IDs to listener counts for that extension.
38 base::LazyInstance
<std::map
<std::string
, EventListenerCounts
>>
39 g_listener_counts
= LAZY_INSTANCE_INITIALIZER
;
41 // A map of (extension ID, event name) pairs to the filtered listener counts
42 // for that pair. The map is used to keep track of which filters are in effect
43 // for which events. We notify the browser about filtered event listeners when
44 // we transition between 0 and 1.
45 using FilteredEventListenerKey
= std::pair
<std::string
, std::string
>;
46 using FilteredEventListenerCounts
=
47 base::ScopedPtrMap
<FilteredEventListenerKey
, scoped_ptr
<ValueCounter
>>;
48 base::LazyInstance
<FilteredEventListenerCounts
> g_filtered_listener_counts
=
49 LAZY_INSTANCE_INITIALIZER
;
51 base::LazyInstance
<EventFilter
> g_event_filter
= LAZY_INSTANCE_INITIALIZER
;
53 // Gets a unique string key identifier for a ScriptContext.
54 // TODO(kalman): Just use pointer equality...?
55 std::string
GetKeyForScriptContext(ScriptContext
* script_context
) {
56 const std::string
& extension_id
= script_context
->GetExtensionID();
57 CHECK(crx_file::id_util::IdIsValid(extension_id
) ||
58 script_context
->GetURL().is_valid());
59 return crx_file::id_util::IdIsValid(extension_id
)
61 : script_context
->GetURL().spec();
64 // Increments the number of event-listeners for the given |event_name| and
65 // ScriptContext. Returns the count after the increment.
66 int IncrementEventListenerCount(ScriptContext
* script_context
,
67 const std::string
& event_name
) {
68 return ++g_listener_counts
69 .Get()[GetKeyForScriptContext(script_context
)][event_name
];
72 // Decrements the number of event-listeners for the given |event_name| and
73 // ScriptContext. Returns the count after the increment.
74 int DecrementEventListenerCount(ScriptContext
* script_context
,
75 const std::string
& event_name
) {
76 return --g_listener_counts
77 .Get()[GetKeyForScriptContext(script_context
)][event_name
];
80 EventFilteringInfo
ParseFromObject(v8::Local
<v8::Object
> object
,
81 v8::Isolate
* isolate
) {
82 EventFilteringInfo info
;
83 v8::Local
<v8::String
> url(v8::String::NewFromUtf8(isolate
, "url"));
84 if (object
->Has(url
)) {
85 v8::Local
<v8::Value
> url_value(object
->Get(url
));
86 info
.SetURL(GURL(*v8::String::Utf8Value(url_value
)));
88 v8::Local
<v8::String
> instance_id(
89 v8::String::NewFromUtf8(isolate
, "instanceId"));
90 if (object
->Has(instance_id
)) {
91 v8::Local
<v8::Value
> instance_id_value(object
->Get(instance_id
));
92 info
.SetInstanceID(instance_id_value
->IntegerValue());
94 v8::Local
<v8::String
> service_type(
95 v8::String::NewFromUtf8(isolate
, "serviceType"));
96 if (object
->Has(service_type
)) {
97 v8::Local
<v8::Value
> service_type_value(object
->Get(service_type
));
98 info
.SetServiceType(*v8::String::Utf8Value(service_type_value
));
100 v8::Local
<v8::String
> window_types(
101 v8::String::NewFromUtf8(isolate
, "windowType"));
102 if (object
->Has(window_types
)) {
103 v8::Local
<v8::Value
> window_types_value(object
->Get(window_types
));
104 info
.SetWindowType(*v8::String::Utf8Value(window_types_value
));
109 // Add a filter to |event_name| in |extension_id|, returning true if it
110 // was the first filter for that event in that extension.
111 bool AddFilter(const std::string
& event_name
,
112 const std::string
& extension_id
,
113 const base::DictionaryValue
& filter
) {
114 FilteredEventListenerKey
key(extension_id
, event_name
);
115 FilteredEventListenerCounts
& all_counts
= g_filtered_listener_counts
.Get();
116 FilteredEventListenerCounts::const_iterator counts
= all_counts
.find(key
);
117 if (counts
== all_counts
.end()) {
118 counts
= all_counts
.insert(key
, make_scoped_ptr(new ValueCounter())).first
;
120 return counts
->second
->Add(filter
);
123 // Remove a filter from |event_name| in |extension_id|, returning true if it
124 // was the last filter for that event in that extension.
125 bool RemoveFilter(const std::string
& event_name
,
126 const std::string
& extension_id
,
127 base::DictionaryValue
* filter
) {
128 FilteredEventListenerKey
key(extension_id
, event_name
);
129 FilteredEventListenerCounts
& all_counts
= g_filtered_listener_counts
.Get();
130 FilteredEventListenerCounts::const_iterator counts
= all_counts
.find(key
);
131 if (counts
== all_counts
.end())
133 // Note: Remove() returns true if it removed the last filter equivalent to
134 // |filter|. If there are more equivalent filters, or if there weren't any in
135 // the first place, it returns false.
136 if (counts
->second
->Remove(*filter
)) {
137 if (counts
->second
->is_empty())
138 all_counts
.erase(counts
); // Clean up if there are no more filters.
146 EventBindings::EventBindings(ScriptContext
* context
)
147 : ObjectBackedNativeHandler(context
) {
148 RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler
,
149 base::Unretained(this)));
150 RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler
,
151 base::Unretained(this)));
153 "AttachFilteredEvent",
154 base::Bind(&EventBindings::AttachFilteredEvent
, base::Unretained(this)));
155 RouteFunction("DetachFilteredEvent",
156 base::Bind(&EventBindings::DetachFilteredEventHandler
,
157 base::Unretained(this)));
158 RouteFunction("MatchAgainstEventFilter",
159 base::Bind(&EventBindings::MatchAgainstEventFilter
,
160 base::Unretained(this)));
162 // It's safe to use base::Unretained here because |context| will always
164 context
->AddInvalidationObserver(
165 base::Bind(&EventBindings::OnInvalidated
, base::Unretained(this)));
168 EventBindings::~EventBindings() {}
170 void EventBindings::AttachEventHandler(
171 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
172 CHECK_EQ(1, args
.Length());
173 CHECK(args
[0]->IsString());
174 AttachEvent(*v8::String::Utf8Value(args
[0]));
177 void EventBindings::AttachEvent(const std::string
& event_name
) {
178 if (!context()->HasAccessOrThrowError(event_name
))
181 // Record the attachment for this context so that events can be detached when
182 // the context is destroyed.
184 // Ideally we'd CHECK that it's not already attached, however that's not
185 // possible because extensions can create and attach events themselves. Very
186 // silly, but that's the way it is. For an example of this, see
187 // chrome/test/data/extensions/api_test/events/background.js.
188 attached_event_names_
.insert(event_name
);
190 const std::string
& extension_id
= context()->GetExtensionID();
191 if (IncrementEventListenerCount(context(), event_name
) == 1) {
192 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener(
193 extension_id
, context()->GetURL(), event_name
));
196 // This is called the first time the page has added a listener. Since
197 // the background page is the only lazy page, we know this is the first
198 // time this listener has been registered.
199 if (ExtensionFrameHelper::IsContextForEventPage(context())) {
200 content::RenderThread::Get()->Send(
201 new ExtensionHostMsg_AddLazyListener(extension_id
, event_name
));
205 void EventBindings::DetachEventHandler(
206 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
207 CHECK_EQ(2, args
.Length());
208 CHECK(args
[0]->IsString());
209 CHECK(args
[1]->IsBoolean());
210 DetachEvent(*v8::String::Utf8Value(args
[0]), args
[1]->BooleanValue());
213 void EventBindings::DetachEvent(const std::string
& event_name
, bool is_manual
) {
214 // See comment in AttachEvent().
215 attached_event_names_
.erase(event_name
);
217 const std::string
& extension_id
= context()->GetExtensionID();
219 if (DecrementEventListenerCount(context(), event_name
) == 0) {
220 content::RenderThread::Get()->Send(new ExtensionHostMsg_RemoveListener(
221 extension_id
, context()->GetURL(), event_name
));
224 // DetachEvent is called when the last listener for the context is
225 // removed. If the context is the background page, and it removes the
226 // last listener manually, then we assume that it is no longer interested
227 // in being awakened for this event.
228 if (is_manual
&& ExtensionFrameHelper::IsContextForEventPage(context())) {
229 content::RenderThread::Get()->Send(
230 new ExtensionHostMsg_RemoveLazyListener(extension_id
, event_name
));
234 // MatcherID AttachFilteredEvent(string event_name, object filter)
235 // event_name - Name of the event to attach.
236 // filter - Which instances of the named event are we interested in.
237 // returns the id assigned to the listener, which will be returned from calls
238 // to MatchAgainstEventFilter where this listener matches.
239 void EventBindings::AttachFilteredEvent(
240 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
241 CHECK_EQ(2, args
.Length());
242 CHECK(args
[0]->IsString());
243 CHECK(args
[1]->IsObject());
245 std::string event_name
= *v8::String::Utf8Value(args
[0]);
246 if (!context()->HasAccessOrThrowError(event_name
))
249 scoped_ptr
<base::DictionaryValue
> filter
;
251 scoped_ptr
<content::V8ValueConverter
> converter(
252 content::V8ValueConverter::create());
253 scoped_ptr
<base::Value
> filter_value(converter
->FromV8Value(
254 v8::Local
<v8::Object
>::Cast(args
[1]), context()->v8_context()));
255 if (!filter_value
|| !filter_value
->IsType(base::Value::TYPE_DICTIONARY
)) {
256 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
259 filter
.reset(static_cast<base::DictionaryValue
*>(filter_value
.release()));
262 // Hold onto a weak reference to |filter| so that it can be used after passing
263 // ownership to |event_filter|.
264 base::DictionaryValue
* filter_weak
= filter
.get();
265 int id
= g_event_filter
.Get().AddEventMatcher(
266 event_name
, ParseEventMatcher(filter
.Pass()));
267 attached_matcher_ids_
.insert(id
);
269 // Only send IPCs the first time a filter gets added.
270 std::string extension_id
= context()->GetExtensionID();
271 if (AddFilter(event_name
, extension_id
, *filter_weak
)) {
272 bool lazy
= ExtensionFrameHelper::IsContextForEventPage(context());
273 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
274 extension_id
, event_name
, *filter_weak
, lazy
));
277 args
.GetReturnValue().Set(static_cast<int32_t>(id
));
280 void EventBindings::DetachFilteredEventHandler(
281 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
282 CHECK_EQ(2, args
.Length());
283 CHECK(args
[0]->IsInt32());
284 CHECK(args
[1]->IsBoolean());
285 DetachFilteredEvent(args
[0]->Int32Value(), args
[1]->BooleanValue());
288 void EventBindings::DetachFilteredEvent(int matcher_id
, bool is_manual
) {
289 EventFilter
& event_filter
= g_event_filter
.Get();
290 EventMatcher
* event_matcher
= event_filter
.GetEventMatcher(matcher_id
);
292 const std::string
& event_name
= event_filter
.GetEventName(matcher_id
);
294 // Only send IPCs the last time a filter gets removed.
295 std::string extension_id
= context()->GetExtensionID();
296 if (RemoveFilter(event_name
, extension_id
, event_matcher
->value())) {
298 is_manual
&& ExtensionFrameHelper::IsContextForEventPage(context());
299 content::RenderThread::Get()->Send(
300 new ExtensionHostMsg_RemoveFilteredListener(
301 extension_id
, event_name
, *event_matcher
->value(), remove_lazy
));
304 event_filter
.RemoveEventMatcher(matcher_id
);
305 attached_matcher_ids_
.erase(matcher_id
);
308 void EventBindings::MatchAgainstEventFilter(
309 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
310 v8::Isolate
* isolate
= args
.GetIsolate();
311 typedef std::set
<EventFilter::MatcherID
> MatcherIDs
;
312 EventFilter
& event_filter
= g_event_filter
.Get();
313 std::string event_name
= *v8::String::Utf8Value(args
[0]);
314 EventFilteringInfo info
=
315 ParseFromObject(args
[1]->ToObject(isolate
), isolate
);
316 // Only match events routed to this context's RenderFrame or ones that don't
317 // have a routingId in their filter.
318 MatcherIDs matched_event_filters
= event_filter
.MatchEvent(
319 event_name
, info
, context()->GetRenderFrame()->GetRoutingID());
320 v8::Local
<v8::Array
> array(
321 v8::Array::New(isolate
, matched_event_filters
.size()));
323 for (MatcherIDs::iterator it
= matched_event_filters
.begin();
324 it
!= matched_event_filters
.end();
326 array
->Set(v8::Integer::New(isolate
, i
++), v8::Integer::New(isolate
, *it
));
328 args
.GetReturnValue().Set(array
);
331 scoped_ptr
<EventMatcher
> EventBindings::ParseEventMatcher(
332 scoped_ptr
<base::DictionaryValue
> filter
) {
333 return make_scoped_ptr(new EventMatcher(
334 filter
.Pass(), context()->GetRenderFrame()->GetRoutingID()));
337 void EventBindings::OnInvalidated() {
338 // Detach all attached events that weren't attached. Iterate over a copy
339 // because it will be mutated.
340 std::set
<std::string
> attached_event_names_safe
= attached_event_names_
;
341 for (const std::string
& event_name
: attached_event_names_safe
) {
342 DetachEvent(event_name
, false /* is_manual */);
344 DCHECK(attached_event_names_
.empty())
345 << "Events cannot be attached during invalidation";
347 // Same for filtered events.
348 std::set
<int> attached_matcher_ids_safe
= attached_matcher_ids_
;
349 for (int matcher_id
: attached_matcher_ids_safe
) {
350 DetachFilteredEvent(matcher_id
, false /* is_manual */);
352 DCHECK(attached_matcher_ids_
.empty())
353 << "Filtered events cannot be attached during invalidation";
356 } // namespace extensions