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/value_counter.h"
21 #include "extensions/renderer/extension_frame_helper.h"
22 #include "extensions/renderer/script_context.h"
25 namespace extensions
{
29 // A map of event names to the number of contexts listening to that event.
30 // We notify the browser about event listeners when we transition between 0
32 typedef std::map
<std::string
, int> EventListenerCounts
;
34 // A map of extension IDs to listener counts for that extension.
35 base::LazyInstance
<std::map
<std::string
, EventListenerCounts
> >
36 g_listener_counts
= LAZY_INSTANCE_INITIALIZER
;
38 // A map of event names to a (filter -> count) map. The map is used to keep
39 // track of which filters are in effect for which events.
40 // We notify the browser about filtered event listeners when we transition
42 typedef std::map
<std::string
, linked_ptr
<ValueCounter
> >
43 FilteredEventListenerCounts
;
45 // A map of extension IDs to filtered listener counts for that extension.
46 base::LazyInstance
<std::map
<std::string
, FilteredEventListenerCounts
> >
47 g_filtered_listener_counts
= LAZY_INSTANCE_INITIALIZER
;
49 base::LazyInstance
<EventFilter
> g_event_filter
= LAZY_INSTANCE_INITIALIZER
;
51 std::string
GetKeyForScriptContext(ScriptContext
* script_context
) {
52 const std::string
& extension_id
= script_context
->GetExtensionID();
53 CHECK(crx_file::id_util::IdIsValid(extension_id
) ||
54 script_context
->GetURL().is_valid());
55 return crx_file::id_util::IdIsValid(extension_id
)
57 : script_context
->GetURL().spec();
60 // Increments the number of event-listeners for the given |event_name| and
61 // ScriptContext. Returns the count after the increment.
62 int IncrementEventListenerCount(ScriptContext
* script_context
,
63 const std::string
& event_name
) {
64 return ++g_listener_counts
65 .Get()[GetKeyForScriptContext(script_context
)][event_name
];
68 // Decrements the number of event-listeners for the given |event_name| and
69 // ScriptContext. Returns the count after the increment.
70 int DecrementEventListenerCount(ScriptContext
* script_context
,
71 const std::string
& event_name
) {
72 return --g_listener_counts
73 .Get()[GetKeyForScriptContext(script_context
)][event_name
];
76 EventFilteringInfo
ParseFromObject(v8::Local
<v8::Object
> object
,
77 v8::Isolate
* isolate
) {
78 EventFilteringInfo info
;
79 v8::Local
<v8::String
> url(v8::String::NewFromUtf8(isolate
, "url"));
80 if (object
->Has(url
)) {
81 v8::Local
<v8::Value
> url_value(object
->Get(url
));
82 info
.SetURL(GURL(*v8::String::Utf8Value(url_value
)));
84 v8::Local
<v8::String
> instance_id(
85 v8::String::NewFromUtf8(isolate
, "instanceId"));
86 if (object
->Has(instance_id
)) {
87 v8::Local
<v8::Value
> instance_id_value(object
->Get(instance_id
));
88 info
.SetInstanceID(instance_id_value
->IntegerValue());
90 v8::Local
<v8::String
> service_type(
91 v8::String::NewFromUtf8(isolate
, "serviceType"));
92 if (object
->Has(service_type
)) {
93 v8::Local
<v8::Value
> service_type_value(object
->Get(service_type
));
94 info
.SetServiceType(*v8::String::Utf8Value(service_type_value
));
99 // Add a filter to |event_name| in |extension_id|, returning true if it
100 // was the first filter for that event in that extension.
101 bool AddFilter(const std::string
& event_name
,
102 const std::string
& extension_id
,
103 base::DictionaryValue
* filter
) {
104 FilteredEventListenerCounts
& counts
=
105 g_filtered_listener_counts
.Get()[extension_id
];
106 FilteredEventListenerCounts::iterator it
= counts
.find(event_name
);
107 if (it
== counts
.end())
108 counts
[event_name
].reset(new ValueCounter
);
110 int result
= counts
[event_name
]->Add(*filter
);
114 // Remove a filter from |event_name| in |extension_id|, returning true if it
115 // was the last filter for that event in that extension.
116 bool RemoveFilter(const std::string
& event_name
,
117 const std::string
& extension_id
,
118 base::DictionaryValue
* filter
) {
119 FilteredEventListenerCounts
& counts
=
120 g_filtered_listener_counts
.Get()[extension_id
];
121 FilteredEventListenerCounts::iterator it
= counts
.find(event_name
);
122 if (it
== counts
.end())
124 return 0 == it
->second
->Remove(*filter
);
129 EventBindings::EventBindings(ScriptContext
* context
)
130 : ObjectBackedNativeHandler(context
) {
131 RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler
,
132 base::Unretained(this)));
133 RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler
,
134 base::Unretained(this)));
136 "AttachFilteredEvent",
137 base::Bind(&EventBindings::AttachFilteredEvent
, base::Unretained(this)));
139 "DetachFilteredEvent",
140 base::Bind(&EventBindings::DetachFilteredEvent
, base::Unretained(this)));
141 RouteFunction("MatchAgainstEventFilter",
142 base::Bind(&EventBindings::MatchAgainstEventFilter
,
143 base::Unretained(this)));
145 // It's safe to use base::Unretained here because |context| will always
147 context
->AddInvalidationObserver(
148 base::Bind(&EventBindings::OnInvalidated
, base::Unretained(this)));
151 EventBindings::~EventBindings() {}
153 void EventBindings::AttachEventHandler(
154 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
155 CHECK_EQ(1, args
.Length());
156 CHECK(args
[0]->IsString());
157 AttachEvent(*v8::String::Utf8Value(args
[0]));
160 void EventBindings::AttachEvent(const std::string
& event_name
) {
161 if (!context()->HasAccessOrThrowError(event_name
))
164 // Record the attachment for this context so that events can be detached when
165 // the context is destroyed.
167 // Ideally we'd CHECK that it's not already attached, however that's not
168 // possible because extensions can create and attach events themselves. Very
169 // silly, but that's the way it is. For an example of this, see
170 // chrome/test/data/extensions/api_test/events/background.js.
171 attached_event_names_
.insert(event_name
);
173 const std::string
& extension_id
= context()->GetExtensionID();
174 if (IncrementEventListenerCount(context(), event_name
) == 1) {
175 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener(
176 extension_id
, context()->GetURL(), event_name
));
179 // This is called the first time the page has added a listener. Since
180 // the background page is the only lazy page, we know this is the first
181 // time this listener has been registered.
182 if (ExtensionFrameHelper::IsContextForEventPage(context())) {
183 content::RenderThread::Get()->Send(
184 new ExtensionHostMsg_AddLazyListener(extension_id
, event_name
));
188 void EventBindings::DetachEventHandler(
189 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
190 CHECK_EQ(2, args
.Length());
191 CHECK(args
[0]->IsString());
192 CHECK(args
[1]->IsBoolean());
193 DetachEvent(*v8::String::Utf8Value(args
[0]), args
[1]->BooleanValue());
196 void EventBindings::DetachEvent(const std::string
& event_name
, bool is_manual
) {
197 // See comment in AttachEvent().
198 attached_event_names_
.erase(event_name
);
200 const std::string
& extension_id
= context()->GetExtensionID();
202 if (DecrementEventListenerCount(context(), event_name
) == 0) {
203 content::RenderThread::Get()->Send(new ExtensionHostMsg_RemoveListener(
204 extension_id
, context()->GetURL(), event_name
));
207 // DetachEvent is called when the last listener for the context is
208 // removed. If the context is the background page, and it removes the
209 // last listener manually, then we assume that it is no longer interested
210 // in being awakened for this event.
211 if (is_manual
&& ExtensionFrameHelper::IsContextForEventPage(context())) {
212 content::RenderThread::Get()->Send(
213 new ExtensionHostMsg_RemoveLazyListener(extension_id
, event_name
));
217 // MatcherID AttachFilteredEvent(string event_name, object filter)
218 // event_name - Name of the event to attach.
219 // filter - Which instances of the named event are we interested in.
220 // returns the id assigned to the listener, which will be returned from calls
221 // to MatchAgainstEventFilter where this listener matches.
222 void EventBindings::AttachFilteredEvent(
223 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
224 CHECK_EQ(2, args
.Length());
225 CHECK(args
[0]->IsString());
226 CHECK(args
[1]->IsObject());
228 std::string event_name
= *v8::String::Utf8Value(args
[0]);
229 if (!context()->HasAccessOrThrowError(event_name
))
232 std::string extension_id
= context()->GetExtensionID();
234 scoped_ptr
<base::DictionaryValue
> filter
;
235 scoped_ptr
<content::V8ValueConverter
> converter(
236 content::V8ValueConverter::create());
238 base::DictionaryValue
* filter_dict
= NULL
;
239 base::Value
* filter_value
= converter
->FromV8Value(
240 v8::Local
<v8::Object
>::Cast(args
[1]), context()->v8_context());
242 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
245 if (!filter_value
->GetAsDictionary(&filter_dict
)) {
247 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
251 filter
.reset(filter_dict
);
252 EventFilter
& event_filter
= g_event_filter
.Get();
254 event_filter
.AddEventMatcher(event_name
, ParseEventMatcher(filter
.get()));
256 // Only send IPCs the first time a filter gets added.
257 if (AddFilter(event_name
, extension_id
, filter
.get())) {
258 bool lazy
= ExtensionFrameHelper::IsContextForEventPage(context());
259 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
260 extension_id
, event_name
, *filter
, lazy
));
263 args
.GetReturnValue().Set(static_cast<int32_t>(id
));
266 void EventBindings::DetachFilteredEvent(
267 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
268 CHECK_EQ(2, args
.Length());
269 CHECK(args
[0]->IsInt32());
270 CHECK(args
[1]->IsBoolean());
271 bool is_manual
= args
[1]->BooleanValue();
273 std::string extension_id
= context()->GetExtensionID();
275 int matcher_id
= args
[0]->Int32Value();
276 EventFilter
& event_filter
= g_event_filter
.Get();
277 EventMatcher
* event_matcher
= event_filter
.GetEventMatcher(matcher_id
);
279 const std::string
& event_name
= event_filter
.GetEventName(matcher_id
);
281 // Only send IPCs the last time a filter gets removed.
282 if (RemoveFilter(event_name
, extension_id
, event_matcher
->value())) {
284 is_manual
&& ExtensionFrameHelper::IsContextForEventPage(context());
285 content::RenderThread::Get()->Send(
286 new ExtensionHostMsg_RemoveFilteredListener(
287 extension_id
, event_name
, *event_matcher
->value(), remove_lazy
));
290 event_filter
.RemoveEventMatcher(matcher_id
);
293 void EventBindings::MatchAgainstEventFilter(
294 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
295 v8::Isolate
* isolate
= args
.GetIsolate();
296 typedef std::set
<EventFilter::MatcherID
> MatcherIDs
;
297 EventFilter
& event_filter
= g_event_filter
.Get();
298 std::string event_name
= *v8::String::Utf8Value(args
[0]);
299 EventFilteringInfo info
=
300 ParseFromObject(args
[1]->ToObject(isolate
), isolate
);
301 // Only match events routed to this context's RenderView or ones that don't
302 // have a routingId in their filter.
303 MatcherIDs matched_event_filters
= event_filter
.MatchEvent(
304 event_name
, info
, context()->GetRenderView()->GetRoutingID());
305 v8::Local
<v8::Array
> array(
306 v8::Array::New(isolate
, matched_event_filters
.size()));
308 for (MatcherIDs::iterator it
= matched_event_filters
.begin();
309 it
!= matched_event_filters
.end();
311 array
->Set(v8::Integer::New(isolate
, i
++), v8::Integer::New(isolate
, *it
));
313 args
.GetReturnValue().Set(array
);
316 scoped_ptr
<EventMatcher
> EventBindings::ParseEventMatcher(
317 base::DictionaryValue
* filter_dict
) {
318 return scoped_ptr
<EventMatcher
>(new EventMatcher(
319 scoped_ptr
<base::DictionaryValue
>(filter_dict
->DeepCopy()),
320 context()->GetRenderView()->GetRoutingID()));
323 void EventBindings::OnInvalidated() {
324 // Detach all attached events that weren't attached. Iterate over a copy
325 // because it will be mutated.
326 std::set
<std::string
> attached_event_names_safe
= attached_event_names_
;
327 for (const std::string
& event_name
: attached_event_names_safe
) {
328 DetachEvent(event_name
, false /* is_manual */);
330 DCHECK(attached_event_names_
.empty())
331 << "Events cannot be attached during invalidation";
334 } // namespace extensions