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"
12 #include "base/basictypes.h"
13 #include "base/bind.h"
14 #include "base/lazy_instance.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "components/crx_file/id_util.h"
17 #include "content/public/child/v8_value_converter.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/manifest_handlers/background_info.h"
24 #include "extensions/common/value_counter.h"
25 #include "extensions/renderer/dispatcher.h"
26 #include "extensions/renderer/extension_helper.h"
27 #include "extensions/renderer/object_backed_native_handler.h"
29 #include "v8/include/v8.h"
31 namespace extensions
{
35 // A map of event names to the number of contexts listening to that event.
36 // We notify the browser about event listeners when we transition between 0
38 typedef std::map
<std::string
, int> EventListenerCounts
;
40 // A map of extension IDs to listener counts for that extension.
41 base::LazyInstance
<std::map
<std::string
, EventListenerCounts
> >
42 g_listener_counts
= LAZY_INSTANCE_INITIALIZER
;
44 // A map of event names to a (filter -> count) map. The map is used to keep
45 // track of which filters are in effect for which events.
46 // We notify the browser about filtered event listeners when we transition
48 typedef std::map
<std::string
, linked_ptr
<ValueCounter
> >
49 FilteredEventListenerCounts
;
51 // A map of extension IDs to filtered listener counts for that extension.
52 base::LazyInstance
<std::map
<std::string
, FilteredEventListenerCounts
> >
53 g_filtered_listener_counts
= LAZY_INSTANCE_INITIALIZER
;
55 base::LazyInstance
<EventFilter
> g_event_filter
= LAZY_INSTANCE_INITIALIZER
;
57 std::string
GetKeyForScriptContext(ScriptContext
* script_context
) {
58 const std::string
& extension_id
= script_context
->GetExtensionID();
59 CHECK(crx_file::id_util::IdIsValid(extension_id
) ||
60 script_context
->GetURL().is_valid());
61 return crx_file::id_util::IdIsValid(extension_id
)
63 : script_context
->GetURL().spec();
66 // Increments the number of event-listeners for the given |event_name| and
67 // ScriptContext. Returns the count after the increment.
68 int IncrementEventListenerCount(ScriptContext
* script_context
,
69 const std::string
& event_name
) {
70 return ++g_listener_counts
71 .Get()[GetKeyForScriptContext(script_context
)][event_name
];
74 // Decrements the number of event-listeners for the given |event_name| and
75 // ScriptContext. Returns the count after the increment.
76 int DecrementEventListenerCount(ScriptContext
* script_context
,
77 const std::string
& event_name
) {
78 return --g_listener_counts
79 .Get()[GetKeyForScriptContext(script_context
)][event_name
];
82 bool IsLazyBackgroundPage(content::RenderView
* render_view
,
83 const Extension
* extension
) {
86 ExtensionHelper
* helper
= ExtensionHelper::Get(render_view
);
87 return (extension
&& BackgroundInfo::HasLazyBackgroundPage(extension
) &&
88 helper
->view_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
91 EventFilteringInfo
ParseFromObject(v8::Handle
<v8::Object
> object
,
92 v8::Isolate
* isolate
) {
93 EventFilteringInfo info
;
94 v8::Handle
<v8::String
> url(v8::String::NewFromUtf8(isolate
, "url"));
95 if (object
->Has(url
)) {
96 v8::Handle
<v8::Value
> url_value(object
->Get(url
));
97 info
.SetURL(GURL(*v8::String::Utf8Value(url_value
)));
99 v8::Handle
<v8::String
> instance_id(
100 v8::String::NewFromUtf8(isolate
, "instanceId"));
101 if (object
->Has(instance_id
)) {
102 v8::Handle
<v8::Value
> instance_id_value(object
->Get(instance_id
));
103 info
.SetInstanceID(instance_id_value
->IntegerValue());
105 v8::Handle
<v8::String
> service_type(
106 v8::String::NewFromUtf8(isolate
, "serviceType"));
107 if (object
->Has(service_type
)) {
108 v8::Handle
<v8::Value
> service_type_value(object
->Get(service_type
));
109 info
.SetServiceType(*v8::String::Utf8Value(service_type_value
));
114 // Add a filter to |event_name| in |extension_id|, returning true if it
115 // was the first filter for that event in that extension.
116 bool AddFilter(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())
123 counts
[event_name
].reset(new ValueCounter
);
125 int result
= counts
[event_name
]->Add(*filter
);
129 // Remove a filter from |event_name| in |extension_id|, returning true if it
130 // was the last filter for that event in that extension.
131 bool RemoveFilter(const std::string
& event_name
,
132 const std::string
& extension_id
,
133 base::DictionaryValue
* filter
) {
134 FilteredEventListenerCounts
& counts
=
135 g_filtered_listener_counts
.Get()[extension_id
];
136 FilteredEventListenerCounts::iterator it
= counts
.find(event_name
);
137 if (it
== counts
.end())
139 return 0 == it
->second
->Remove(*filter
);
144 EventBindings::EventBindings(Dispatcher
* dispatcher
, ScriptContext
* context
)
145 : ObjectBackedNativeHandler(context
), dispatcher_(dispatcher
) {
148 base::Bind(&EventBindings::AttachEvent
, base::Unretained(this)));
151 base::Bind(&EventBindings::DetachEvent
, base::Unretained(this)));
153 "AttachFilteredEvent",
154 base::Bind(&EventBindings::AttachFilteredEvent
, base::Unretained(this)));
156 "DetachFilteredEvent",
157 base::Bind(&EventBindings::DetachFilteredEvent
, base::Unretained(this)));
158 RouteFunction("MatchAgainstEventFilter",
159 base::Bind(&EventBindings::MatchAgainstEventFilter
,
160 base::Unretained(this)));
163 EventBindings::~EventBindings() {}
165 // Attach an event name to an object.
166 void EventBindings::AttachEvent(
167 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
168 CHECK_EQ(1, args
.Length());
169 CHECK(args
[0]->IsString());
171 std::string event_name
= *v8::String::Utf8Value(args
[0]);
173 if (!dispatcher_
->CheckContextAccessToExtensionAPI(event_name
, context()))
176 const std::string
& extension_id
= context()->GetExtensionID();
177 if (IncrementEventListenerCount(context(), event_name
) == 1) {
178 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener(
179 extension_id
, context()->GetURL(), event_name
));
182 // This is called the first time the page has added a listener. Since
183 // the background page is the only lazy page, we know this is the first
184 // time this listener has been registered.
185 if (IsLazyBackgroundPage(context()->GetRenderView(),
186 context()->extension())) {
187 content::RenderThread::Get()->Send(
188 new ExtensionHostMsg_AddLazyListener(extension_id
, event_name
));
192 void EventBindings::DetachEvent(
193 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
194 CHECK_EQ(2, args
.Length());
195 CHECK(args
[0]->IsString());
196 CHECK(args
[1]->IsBoolean());
198 std::string event_name
= *v8::String::Utf8Value(args
[0]);
199 bool is_manual
= args
[1]->BooleanValue();
201 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
&& IsLazyBackgroundPage(context()->GetRenderView(),
212 context()->extension())) {
213 content::RenderThread::Get()->Send(
214 new ExtensionHostMsg_RemoveLazyListener(extension_id
, event_name
));
218 // MatcherID AttachFilteredEvent(string event_name, object filter)
219 // event_name - Name of the event to attach.
220 // filter - Which instances of the named event are we interested in.
221 // returns the id assigned to the listener, which will be returned from calls
222 // to MatchAgainstEventFilter where this listener matches.
223 void EventBindings::AttachFilteredEvent(
224 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
225 CHECK_EQ(2, args
.Length());
226 CHECK(args
[0]->IsString());
227 CHECK(args
[1]->IsObject());
229 std::string event_name
= *v8::String::Utf8Value(args
[0]);
231 // This method throws an exception if it returns false.
232 if (!dispatcher_
->CheckContextAccessToExtensionAPI(event_name
, context()))
235 std::string extension_id
= context()->GetExtensionID();
237 scoped_ptr
<base::DictionaryValue
> filter
;
238 scoped_ptr
<content::V8ValueConverter
> converter(
239 content::V8ValueConverter::create());
241 base::DictionaryValue
* filter_dict
= NULL
;
242 base::Value
* filter_value
= converter
->FromV8Value(
243 v8::Local
<v8::Object
>::Cast(args
[1]), context()->v8_context());
245 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
248 if (!filter_value
->GetAsDictionary(&filter_dict
)) {
250 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
254 filter
.reset(filter_dict
);
255 EventFilter
& event_filter
= g_event_filter
.Get();
257 event_filter
.AddEventMatcher(event_name
, ParseEventMatcher(filter
.get()));
259 // Only send IPCs the first time a filter gets added.
260 if (AddFilter(event_name
, extension_id
, filter
.get())) {
261 bool lazy
= IsLazyBackgroundPage(context()->GetRenderView(),
262 context()->extension());
263 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
264 extension_id
, event_name
, *filter
, lazy
));
267 args
.GetReturnValue().Set(static_cast<int32_t>(id
));
270 void EventBindings::DetachFilteredEvent(
271 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
272 CHECK_EQ(2, args
.Length());
273 CHECK(args
[0]->IsInt32());
274 CHECK(args
[1]->IsBoolean());
275 bool is_manual
= args
[1]->BooleanValue();
277 std::string extension_id
= context()->GetExtensionID();
279 int matcher_id
= args
[0]->Int32Value();
280 EventFilter
& event_filter
= g_event_filter
.Get();
281 EventMatcher
* event_matcher
= event_filter
.GetEventMatcher(matcher_id
);
283 const std::string
& event_name
= event_filter
.GetEventName(matcher_id
);
285 // Only send IPCs the last time a filter gets removed.
286 if (RemoveFilter(event_name
, extension_id
, event_matcher
->value())) {
287 bool lazy
= is_manual
&& IsLazyBackgroundPage(context()->GetRenderView(),
288 context()->extension());
289 content::RenderThread::Get()->Send(
290 new ExtensionHostMsg_RemoveFilteredListener(
291 extension_id
, event_name
, *event_matcher
->value(), lazy
));
294 event_filter
.RemoveEventMatcher(matcher_id
);
297 void EventBindings::MatchAgainstEventFilter(
298 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
299 v8::Isolate
* isolate
= args
.GetIsolate();
300 typedef std::set
<EventFilter::MatcherID
> MatcherIDs
;
301 EventFilter
& event_filter
= g_event_filter
.Get();
302 std::string event_name
= *v8::String::Utf8Value(args
[0]);
303 EventFilteringInfo info
=
304 ParseFromObject(args
[1]->ToObject(isolate
), isolate
);
305 // Only match events routed to this context's RenderView or ones that don't
306 // have a routingId in their filter.
307 MatcherIDs matched_event_filters
= event_filter
.MatchEvent(
308 event_name
, info
, context()->GetRenderView()->GetRoutingID());
309 v8::Handle
<v8::Array
> array(
310 v8::Array::New(isolate
, matched_event_filters
.size()));
312 for (MatcherIDs::iterator it
= matched_event_filters
.begin();
313 it
!= matched_event_filters
.end();
315 array
->Set(v8::Integer::New(isolate
, i
++), v8::Integer::New(isolate
, *it
));
317 args
.GetReturnValue().Set(array
);
320 scoped_ptr
<EventMatcher
> EventBindings::ParseEventMatcher(
321 base::DictionaryValue
* filter_dict
) {
322 return scoped_ptr
<EventMatcher
>(new EventMatcher(
323 scoped_ptr
<base::DictionaryValue
>(filter_dict
->DeepCopy()),
324 context()->GetRenderView()->GetRoutingID()));
327 } // namespace extensions