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
->url().is_valid());
59 return crx_file::id_util::IdIsValid(extension_id
)
61 : script_context
->url().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
));
107 v8::Local
<v8::String
> window_exposed(
108 v8::String::NewFromUtf8(isolate
, "windowExposedByDefault"));
109 if (object
->Has(window_exposed
)) {
110 v8::Local
<v8::Value
> window_exposed_value(object
->Get(window_exposed
));
111 info
.SetWindowExposedByDefault(
112 window_exposed_value
.As
<v8::Boolean
>()->Value());
118 // Add a filter to |event_name| in |extension_id|, returning true if it
119 // was the first filter for that event in that extension.
120 bool AddFilter(const std::string
& event_name
,
121 const std::string
& extension_id
,
122 const base::DictionaryValue
& filter
) {
123 FilteredEventListenerKey
key(extension_id
, event_name
);
124 FilteredEventListenerCounts
& all_counts
= g_filtered_listener_counts
.Get();
125 FilteredEventListenerCounts::const_iterator counts
= all_counts
.find(key
);
126 if (counts
== all_counts
.end()) {
127 counts
= all_counts
.insert(key
, make_scoped_ptr(new ValueCounter())).first
;
129 return counts
->second
->Add(filter
);
132 // Remove a filter from |event_name| in |extension_id|, returning true if it
133 // was the last filter for that event in that extension.
134 bool RemoveFilter(const std::string
& event_name
,
135 const std::string
& extension_id
,
136 base::DictionaryValue
* filter
) {
137 FilteredEventListenerKey
key(extension_id
, event_name
);
138 FilteredEventListenerCounts
& all_counts
= g_filtered_listener_counts
.Get();
139 FilteredEventListenerCounts::const_iterator counts
= all_counts
.find(key
);
140 if (counts
== all_counts
.end())
142 // Note: Remove() returns true if it removed the last filter equivalent to
143 // |filter|. If there are more equivalent filters, or if there weren't any in
144 // the first place, it returns false.
145 if (counts
->second
->Remove(*filter
)) {
146 if (counts
->second
->is_empty())
147 all_counts
.erase(counts
); // Clean up if there are no more filters.
155 EventBindings::EventBindings(ScriptContext
* context
)
156 : ObjectBackedNativeHandler(context
) {
157 RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler
,
158 base::Unretained(this)));
159 RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler
,
160 base::Unretained(this)));
162 "AttachFilteredEvent",
163 base::Bind(&EventBindings::AttachFilteredEvent
, base::Unretained(this)));
164 RouteFunction("DetachFilteredEvent",
165 base::Bind(&EventBindings::DetachFilteredEventHandler
,
166 base::Unretained(this)));
167 RouteFunction("MatchAgainstEventFilter",
168 base::Bind(&EventBindings::MatchAgainstEventFilter
,
169 base::Unretained(this)));
171 // It's safe to use base::Unretained here because |context| will always
173 context
->AddInvalidationObserver(
174 base::Bind(&EventBindings::OnInvalidated
, base::Unretained(this)));
177 EventBindings::~EventBindings() {}
179 void EventBindings::AttachEventHandler(
180 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
181 CHECK_EQ(1, args
.Length());
182 CHECK(args
[0]->IsString());
183 AttachEvent(*v8::String::Utf8Value(args
[0]));
186 void EventBindings::AttachEvent(const std::string
& event_name
) {
187 if (!context()->HasAccessOrThrowError(event_name
))
190 // Record the attachment for this context so that events can be detached when
191 // the context is destroyed.
193 // Ideally we'd CHECK that it's not already attached, however that's not
194 // possible because extensions can create and attach events themselves. Very
195 // silly, but that's the way it is. For an example of this, see
196 // chrome/test/data/extensions/api_test/events/background.js.
197 attached_event_names_
.insert(event_name
);
199 const std::string
& extension_id
= context()->GetExtensionID();
200 if (IncrementEventListenerCount(context(), event_name
) == 1) {
201 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener(
202 extension_id
, context()->url(), event_name
));
205 // This is called the first time the page has added a listener. Since
206 // the background page is the only lazy page, we know this is the first
207 // time this listener has been registered.
208 if (ExtensionFrameHelper::IsContextForEventPage(context())) {
209 content::RenderThread::Get()->Send(
210 new ExtensionHostMsg_AddLazyListener(extension_id
, event_name
));
214 void EventBindings::DetachEventHandler(
215 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
216 CHECK_EQ(2, args
.Length());
217 CHECK(args
[0]->IsString());
218 CHECK(args
[1]->IsBoolean());
219 DetachEvent(*v8::String::Utf8Value(args
[0]), args
[1]->BooleanValue());
222 void EventBindings::DetachEvent(const std::string
& event_name
, bool is_manual
) {
223 // See comment in AttachEvent().
224 attached_event_names_
.erase(event_name
);
226 const std::string
& extension_id
= context()->GetExtensionID();
228 if (DecrementEventListenerCount(context(), event_name
) == 0) {
229 content::RenderThread::Get()->Send(new ExtensionHostMsg_RemoveListener(
230 extension_id
, context()->url(), event_name
));
233 // DetachEvent is called when the last listener for the context is
234 // removed. If the context is the background page, and it removes the
235 // last listener manually, then we assume that it is no longer interested
236 // in being awakened for this event.
237 if (is_manual
&& ExtensionFrameHelper::IsContextForEventPage(context())) {
238 content::RenderThread::Get()->Send(
239 new ExtensionHostMsg_RemoveLazyListener(extension_id
, event_name
));
243 // MatcherID AttachFilteredEvent(string event_name, object filter)
244 // event_name - Name of the event to attach.
245 // filter - Which instances of the named event are we interested in.
246 // returns the id assigned to the listener, which will be returned from calls
247 // to MatchAgainstEventFilter where this listener matches.
248 void EventBindings::AttachFilteredEvent(
249 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
250 CHECK_EQ(2, args
.Length());
251 CHECK(args
[0]->IsString());
252 CHECK(args
[1]->IsObject());
254 std::string event_name
= *v8::String::Utf8Value(args
[0]);
255 if (!context()->HasAccessOrThrowError(event_name
))
258 scoped_ptr
<base::DictionaryValue
> filter
;
260 scoped_ptr
<content::V8ValueConverter
> converter(
261 content::V8ValueConverter::create());
262 scoped_ptr
<base::Value
> filter_value(converter
->FromV8Value(
263 v8::Local
<v8::Object
>::Cast(args
[1]), context()->v8_context()));
264 if (!filter_value
|| !filter_value
->IsType(base::Value::TYPE_DICTIONARY
)) {
265 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
268 filter
= base::DictionaryValue::From(filter_value
.Pass());
271 // Hold onto a weak reference to |filter| so that it can be used after passing
272 // ownership to |event_filter|.
273 base::DictionaryValue
* filter_weak
= filter
.get();
274 int id
= g_event_filter
.Get().AddEventMatcher(
275 event_name
, ParseEventMatcher(filter
.Pass()));
276 attached_matcher_ids_
.insert(id
);
278 // Only send IPCs the first time a filter gets added.
279 std::string extension_id
= context()->GetExtensionID();
280 if (AddFilter(event_name
, extension_id
, *filter_weak
)) {
281 bool lazy
= ExtensionFrameHelper::IsContextForEventPage(context());
282 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
283 extension_id
, event_name
, *filter_weak
, lazy
));
286 args
.GetReturnValue().Set(static_cast<int32_t>(id
));
289 void EventBindings::DetachFilteredEventHandler(
290 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
291 CHECK_EQ(2, args
.Length());
292 CHECK(args
[0]->IsInt32());
293 CHECK(args
[1]->IsBoolean());
294 DetachFilteredEvent(args
[0]->Int32Value(), args
[1]->BooleanValue());
297 void EventBindings::DetachFilteredEvent(int matcher_id
, bool is_manual
) {
298 EventFilter
& event_filter
= g_event_filter
.Get();
299 EventMatcher
* event_matcher
= event_filter
.GetEventMatcher(matcher_id
);
301 const std::string
& event_name
= event_filter
.GetEventName(matcher_id
);
303 // Only send IPCs the last time a filter gets removed.
304 std::string extension_id
= context()->GetExtensionID();
305 if (RemoveFilter(event_name
, extension_id
, event_matcher
->value())) {
307 is_manual
&& ExtensionFrameHelper::IsContextForEventPage(context());
308 content::RenderThread::Get()->Send(
309 new ExtensionHostMsg_RemoveFilteredListener(
310 extension_id
, event_name
, *event_matcher
->value(), remove_lazy
));
313 event_filter
.RemoveEventMatcher(matcher_id
);
314 attached_matcher_ids_
.erase(matcher_id
);
317 void EventBindings::MatchAgainstEventFilter(
318 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
319 v8::Isolate
* isolate
= args
.GetIsolate();
320 typedef std::set
<EventFilter::MatcherID
> MatcherIDs
;
321 EventFilter
& event_filter
= g_event_filter
.Get();
322 std::string event_name
= *v8::String::Utf8Value(args
[0]);
323 EventFilteringInfo info
=
324 ParseFromObject(args
[1]->ToObject(isolate
), isolate
);
325 // Only match events routed to this context's RenderFrame or ones that don't
326 // have a routingId in their filter.
327 MatcherIDs matched_event_filters
= event_filter
.MatchEvent(
328 event_name
, info
, context()->GetRenderFrame()->GetRoutingID());
329 v8::Local
<v8::Array
> array(
330 v8::Array::New(isolate
, matched_event_filters
.size()));
332 for (MatcherIDs::iterator it
= matched_event_filters
.begin();
333 it
!= matched_event_filters
.end();
335 array
->Set(v8::Integer::New(isolate
, i
++), v8::Integer::New(isolate
, *it
));
337 args
.GetReturnValue().Set(array
);
340 scoped_ptr
<EventMatcher
> EventBindings::ParseEventMatcher(
341 scoped_ptr
<base::DictionaryValue
> filter
) {
342 return make_scoped_ptr(new EventMatcher(
343 filter
.Pass(), context()->GetRenderFrame()->GetRoutingID()));
346 void EventBindings::OnInvalidated() {
347 // Detach all attached events that weren't attached. Iterate over a copy
348 // because it will be mutated.
349 std::set
<std::string
> attached_event_names_safe
= attached_event_names_
;
350 for (const std::string
& event_name
: attached_event_names_safe
) {
351 DetachEvent(event_name
, false /* is_manual */);
353 DCHECK(attached_event_names_
.empty())
354 << "Events cannot be attached during invalidation";
356 // Same for filtered events.
357 std::set
<int> attached_matcher_ids_safe
= attached_matcher_ids_
;
358 for (int matcher_id
: attached_matcher_ids_safe
) {
359 DetachFilteredEvent(matcher_id
, false /* is_manual */);
361 DCHECK(attached_matcher_ids_
.empty())
362 << "Filtered events cannot be attached during invalidation";
365 } // namespace extensions