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"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/lazy_instance.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "components/crx_file/id_util.h"
14 #include "content/public/child/v8_value_converter.h"
15 #include "content/public/renderer/render_thread.h"
16 #include "content/public/renderer/render_view.h"
17 #include "extensions/common/event_filter.h"
18 #include "extensions/common/extension.h"
19 #include "extensions/common/extension_messages.h"
20 #include "extensions/common/manifest_handlers/background_info.h"
21 #include "extensions/common/value_counter.h"
22 #include "extensions/renderer/extension_helper.h"
23 #include "extensions/renderer/script_context.h"
26 namespace extensions
{
30 // A map of event names to the number of contexts listening to that event.
31 // We notify the browser about event listeners when we transition between 0
33 typedef std::map
<std::string
, int> EventListenerCounts
;
35 // A map of extension IDs to listener counts for that extension.
36 base::LazyInstance
<std::map
<std::string
, EventListenerCounts
> >
37 g_listener_counts
= LAZY_INSTANCE_INITIALIZER
;
39 // A map of event names to a (filter -> count) map. The map is used to keep
40 // track of which filters are in effect for which events.
41 // We notify the browser about filtered event listeners when we transition
43 typedef std::map
<std::string
, linked_ptr
<ValueCounter
> >
44 FilteredEventListenerCounts
;
46 // A map of extension IDs to filtered listener counts for that extension.
47 base::LazyInstance
<std::map
<std::string
, FilteredEventListenerCounts
> >
48 g_filtered_listener_counts
= LAZY_INSTANCE_INITIALIZER
;
50 base::LazyInstance
<EventFilter
> g_event_filter
= LAZY_INSTANCE_INITIALIZER
;
52 std::string
GetKeyForScriptContext(ScriptContext
* script_context
) {
53 const std::string
& extension_id
= script_context
->GetExtensionID();
54 CHECK(crx_file::id_util::IdIsValid(extension_id
) ||
55 script_context
->GetURL().is_valid());
56 return crx_file::id_util::IdIsValid(extension_id
)
58 : script_context
->GetURL().spec();
61 // Increments the number of event-listeners for the given |event_name| and
62 // ScriptContext. Returns the count after the increment.
63 int IncrementEventListenerCount(ScriptContext
* script_context
,
64 const std::string
& event_name
) {
65 return ++g_listener_counts
66 .Get()[GetKeyForScriptContext(script_context
)][event_name
];
69 // Decrements the number of event-listeners for the given |event_name| and
70 // ScriptContext. Returns the count after the increment.
71 int DecrementEventListenerCount(ScriptContext
* script_context
,
72 const std::string
& event_name
) {
73 return --g_listener_counts
74 .Get()[GetKeyForScriptContext(script_context
)][event_name
];
77 bool IsLazyBackgroundPage(content::RenderView
* render_view
,
78 const Extension
* extension
) {
81 ExtensionHelper
* helper
= ExtensionHelper::Get(render_view
);
82 return (extension
&& BackgroundInfo::HasLazyBackgroundPage(extension
) &&
83 helper
->view_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
86 EventFilteringInfo
ParseFromObject(v8::Local
<v8::Object
> object
,
87 v8::Isolate
* isolate
) {
88 EventFilteringInfo info
;
89 v8::Local
<v8::String
> url(v8::String::NewFromUtf8(isolate
, "url"));
90 if (object
->Has(url
)) {
91 v8::Local
<v8::Value
> url_value(object
->Get(url
));
92 info
.SetURL(GURL(*v8::String::Utf8Value(url_value
)));
94 v8::Local
<v8::String
> instance_id(
95 v8::String::NewFromUtf8(isolate
, "instanceId"));
96 if (object
->Has(instance_id
)) {
97 v8::Local
<v8::Value
> instance_id_value(object
->Get(instance_id
));
98 info
.SetInstanceID(instance_id_value
->IntegerValue());
100 v8::Local
<v8::String
> service_type(
101 v8::String::NewFromUtf8(isolate
, "serviceType"));
102 if (object
->Has(service_type
)) {
103 v8::Local
<v8::Value
> service_type_value(object
->Get(service_type
));
104 info
.SetServiceType(*v8::String::Utf8Value(service_type_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 base::DictionaryValue
* filter
) {
114 FilteredEventListenerCounts
& counts
=
115 g_filtered_listener_counts
.Get()[extension_id
];
116 FilteredEventListenerCounts::iterator it
= counts
.find(event_name
);
117 if (it
== counts
.end())
118 counts
[event_name
].reset(new ValueCounter
);
120 int result
= counts
[event_name
]->Add(*filter
);
124 // Remove a filter from |event_name| in |extension_id|, returning true if it
125 // was the last filter for that event in that extension.
126 bool RemoveFilter(const std::string
& event_name
,
127 const std::string
& extension_id
,
128 base::DictionaryValue
* filter
) {
129 FilteredEventListenerCounts
& counts
=
130 g_filtered_listener_counts
.Get()[extension_id
];
131 FilteredEventListenerCounts::iterator it
= counts
.find(event_name
);
132 if (it
== counts
.end())
134 return 0 == it
->second
->Remove(*filter
);
139 EventBindings::EventBindings(ScriptContext
* context
)
140 : ObjectBackedNativeHandler(context
) {
141 RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler
,
142 base::Unretained(this)));
143 RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler
,
144 base::Unretained(this)));
146 "AttachFilteredEvent",
147 base::Bind(&EventBindings::AttachFilteredEvent
, base::Unretained(this)));
149 "DetachFilteredEvent",
150 base::Bind(&EventBindings::DetachFilteredEvent
, base::Unretained(this)));
151 RouteFunction("MatchAgainstEventFilter",
152 base::Bind(&EventBindings::MatchAgainstEventFilter
,
153 base::Unretained(this)));
155 // It's safe to use base::Unretained here because |context| will always
157 context
->AddInvalidationObserver(
158 base::Bind(&EventBindings::OnInvalidated
, base::Unretained(this)));
161 EventBindings::~EventBindings() {}
163 void EventBindings::AttachEventHandler(
164 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
165 CHECK_EQ(1, args
.Length());
166 CHECK(args
[0]->IsString());
167 AttachEvent(*v8::String::Utf8Value(args
[0]));
170 void EventBindings::AttachEvent(const std::string
& event_name
) {
171 if (!context()->HasAccessOrThrowError(event_name
))
174 // Record the attachment for this context so that events can be detached when
175 // the context is destroyed.
177 // Ideally we'd CHECK that it's not already attached, however that's not
178 // possible because extensions can create and attach events themselves. Very
179 // silly, but that's the way it is. For an example of this, see
180 // chrome/test/data/extensions/api_test/events/background.js.
181 attached_event_names_
.insert(event_name
);
183 const std::string
& extension_id
= context()->GetExtensionID();
184 if (IncrementEventListenerCount(context(), event_name
) == 1) {
185 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener(
186 extension_id
, context()->GetURL(), event_name
));
189 // This is called the first time the page has added a listener. Since
190 // the background page is the only lazy page, we know this is the first
191 // time this listener has been registered.
192 if (IsLazyBackgroundPage(context()->GetRenderView(),
193 context()->extension())) {
194 content::RenderThread::Get()->Send(
195 new ExtensionHostMsg_AddLazyListener(extension_id
, event_name
));
199 void EventBindings::DetachEventHandler(
200 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
201 CHECK_EQ(2, args
.Length());
202 CHECK(args
[0]->IsString());
203 CHECK(args
[1]->IsBoolean());
204 DetachEvent(*v8::String::Utf8Value(args
[0]), args
[1]->BooleanValue());
207 void EventBindings::DetachEvent(const std::string
& event_name
, bool is_manual
) {
208 // See comment in AttachEvent().
209 attached_event_names_
.erase(event_name
);
211 const std::string
& extension_id
= context()->GetExtensionID();
213 if (DecrementEventListenerCount(context(), event_name
) == 0) {
214 content::RenderThread::Get()->Send(new ExtensionHostMsg_RemoveListener(
215 extension_id
, context()->GetURL(), event_name
));
218 // DetachEvent is called when the last listener for the context is
219 // removed. If the context is the background page, and it removes the
220 // last listener manually, then we assume that it is no longer interested
221 // in being awakened for this event.
222 if (is_manual
&& IsLazyBackgroundPage(context()->GetRenderView(),
223 context()->extension())) {
224 content::RenderThread::Get()->Send(
225 new ExtensionHostMsg_RemoveLazyListener(extension_id
, event_name
));
229 // MatcherID AttachFilteredEvent(string event_name, object filter)
230 // event_name - Name of the event to attach.
231 // filter - Which instances of the named event are we interested in.
232 // returns the id assigned to the listener, which will be returned from calls
233 // to MatchAgainstEventFilter where this listener matches.
234 void EventBindings::AttachFilteredEvent(
235 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
236 CHECK_EQ(2, args
.Length());
237 CHECK(args
[0]->IsString());
238 CHECK(args
[1]->IsObject());
240 std::string event_name
= *v8::String::Utf8Value(args
[0]);
241 if (!context()->HasAccessOrThrowError(event_name
))
244 std::string extension_id
= context()->GetExtensionID();
246 scoped_ptr
<base::DictionaryValue
> filter
;
247 scoped_ptr
<content::V8ValueConverter
> converter(
248 content::V8ValueConverter::create());
250 base::DictionaryValue
* filter_dict
= NULL
;
251 base::Value
* filter_value
= converter
->FromV8Value(
252 v8::Local
<v8::Object
>::Cast(args
[1]), context()->v8_context());
254 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
257 if (!filter_value
->GetAsDictionary(&filter_dict
)) {
259 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
263 filter
.reset(filter_dict
);
264 EventFilter
& event_filter
= g_event_filter
.Get();
266 event_filter
.AddEventMatcher(event_name
, ParseEventMatcher(filter
.get()));
268 // Only send IPCs the first time a filter gets added.
269 if (AddFilter(event_name
, extension_id
, filter
.get())) {
270 bool lazy
= IsLazyBackgroundPage(context()->GetRenderView(),
271 context()->extension());
272 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
273 extension_id
, event_name
, *filter
, lazy
));
276 args
.GetReturnValue().Set(static_cast<int32_t>(id
));
279 void EventBindings::DetachFilteredEvent(
280 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
281 CHECK_EQ(2, args
.Length());
282 CHECK(args
[0]->IsInt32());
283 CHECK(args
[1]->IsBoolean());
284 bool is_manual
= args
[1]->BooleanValue();
286 std::string extension_id
= context()->GetExtensionID();
288 int matcher_id
= args
[0]->Int32Value();
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 if (RemoveFilter(event_name
, extension_id
, event_matcher
->value())) {
296 bool lazy
= is_manual
&& IsLazyBackgroundPage(context()->GetRenderView(),
297 context()->extension());
298 content::RenderThread::Get()->Send(
299 new ExtensionHostMsg_RemoveFilteredListener(
300 extension_id
, event_name
, *event_matcher
->value(), lazy
));
303 event_filter
.RemoveEventMatcher(matcher_id
);
306 void EventBindings::MatchAgainstEventFilter(
307 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
308 v8::Isolate
* isolate
= args
.GetIsolate();
309 typedef std::set
<EventFilter::MatcherID
> MatcherIDs
;
310 EventFilter
& event_filter
= g_event_filter
.Get();
311 std::string event_name
= *v8::String::Utf8Value(args
[0]);
312 EventFilteringInfo info
=
313 ParseFromObject(args
[1]->ToObject(isolate
), isolate
);
314 // Only match events routed to this context's RenderView or ones that don't
315 // have a routingId in their filter.
316 MatcherIDs matched_event_filters
= event_filter
.MatchEvent(
317 event_name
, info
, context()->GetRenderView()->GetRoutingID());
318 v8::Local
<v8::Array
> array(
319 v8::Array::New(isolate
, matched_event_filters
.size()));
321 for (MatcherIDs::iterator it
= matched_event_filters
.begin();
322 it
!= matched_event_filters
.end();
324 array
->Set(v8::Integer::New(isolate
, i
++), v8::Integer::New(isolate
, *it
));
326 args
.GetReturnValue().Set(array
);
329 scoped_ptr
<EventMatcher
> EventBindings::ParseEventMatcher(
330 base::DictionaryValue
* filter_dict
) {
331 return scoped_ptr
<EventMatcher
>(new EventMatcher(
332 scoped_ptr
<base::DictionaryValue
>(filter_dict
->DeepCopy()),
333 context()->GetRenderView()->GetRoutingID()));
336 void EventBindings::OnInvalidated() {
337 // Detach all attached events that weren't attached. Iterate over a copy
338 // because it will be mutated.
339 std::set
<std::string
> attached_event_names_safe
= attached_event_names_
;
340 for (const std::string
& event_name
: attached_event_names_safe
) {
341 DetachEvent(event_name
, false /* is_manual */);
343 DCHECK(attached_event_names_
.empty())
344 << "Events cannot be attached during invalidation";
347 } // namespace extensions