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 "content/public/renderer/render_thread.h"
17 #include "content/public/renderer/render_view.h"
18 #include "content/public/renderer/v8_value_converter.h"
19 #include "extensions/common/event_filter.h"
20 #include "extensions/common/extension.h"
21 #include "extensions/common/extension_messages.h"
22 #include "extensions/common/manifest_handlers/background_info.h"
23 #include "extensions/common/value_counter.h"
24 #include "extensions/renderer/dispatcher.h"
25 #include "extensions/renderer/extension_helper.h"
26 #include "extensions/renderer/object_backed_native_handler.h"
28 #include "v8/include/v8.h"
30 namespace extensions
{
34 // A map of event names to the number of contexts listening to that event.
35 // We notify the browser about event listeners when we transition between 0
37 typedef std::map
<std::string
, int> EventListenerCounts
;
39 // A map of extension IDs to listener counts for that extension.
40 base::LazyInstance
<std::map
<std::string
, EventListenerCounts
> >
41 g_listener_counts
= LAZY_INSTANCE_INITIALIZER
;
43 // A map of event names to a (filter -> count) map. The map is used to keep
44 // track of which filters are in effect for which events.
45 // We notify the browser about filtered event listeners when we transition
47 typedef std::map
<std::string
, linked_ptr
<ValueCounter
> >
48 FilteredEventListenerCounts
;
50 // A map of extension IDs to filtered listener counts for that extension.
51 base::LazyInstance
<std::map
<std::string
, FilteredEventListenerCounts
> >
52 g_filtered_listener_counts
= LAZY_INSTANCE_INITIALIZER
;
54 base::LazyInstance
<EventFilter
> g_event_filter
= LAZY_INSTANCE_INITIALIZER
;
56 bool IsLazyBackgroundPage(content::RenderView
* render_view
,
57 const Extension
* extension
) {
60 ExtensionHelper
* helper
= ExtensionHelper::Get(render_view
);
61 return (extension
&& BackgroundInfo::HasLazyBackgroundPage(extension
) &&
62 helper
->view_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
65 EventFilteringInfo
ParseFromObject(v8::Handle
<v8::Object
> object
,
66 v8::Isolate
* isolate
) {
67 EventFilteringInfo info
;
68 v8::Handle
<v8::String
> url(v8::String::NewFromUtf8(isolate
, "url"));
69 if (object
->Has(url
)) {
70 v8::Handle
<v8::Value
> url_value(object
->Get(url
));
71 info
.SetURL(GURL(*v8::String::Utf8Value(url_value
)));
73 v8::Handle
<v8::String
> instance_id(
74 v8::String::NewFromUtf8(isolate
, "instanceId"));
75 if (object
->Has(instance_id
)) {
76 v8::Handle
<v8::Value
> instance_id_value(object
->Get(instance_id
));
77 info
.SetInstanceID(instance_id_value
->IntegerValue());
79 v8::Handle
<v8::String
> service_type(
80 v8::String::NewFromUtf8(isolate
, "serviceType"));
81 if (object
->Has(service_type
)) {
82 v8::Handle
<v8::Value
> service_type_value(object
->Get(service_type
));
83 info
.SetServiceType(*v8::String::Utf8Value(service_type_value
));
88 // Add a filter to |event_name| in |extension_id|, returning true if it
89 // was the first filter for that event in that extension.
90 bool AddFilter(const std::string
& event_name
,
91 const std::string
& extension_id
,
92 base::DictionaryValue
* filter
) {
93 FilteredEventListenerCounts
& counts
=
94 g_filtered_listener_counts
.Get()[extension_id
];
95 FilteredEventListenerCounts::iterator it
= counts
.find(event_name
);
96 if (it
== counts
.end())
97 counts
[event_name
].reset(new ValueCounter
);
99 int result
= counts
[event_name
]->Add(*filter
);
103 // Remove a filter from |event_name| in |extension_id|, returning true if it
104 // was the last filter for that event in that extension.
105 bool RemoveFilter(const std::string
& event_name
,
106 const std::string
& extension_id
,
107 base::DictionaryValue
* filter
) {
108 FilteredEventListenerCounts
& counts
=
109 g_filtered_listener_counts
.Get()[extension_id
];
110 FilteredEventListenerCounts::iterator it
= counts
.find(event_name
);
111 if (it
== counts
.end())
113 return 0 == it
->second
->Remove(*filter
);
118 EventBindings::EventBindings(Dispatcher
* dispatcher
, ScriptContext
* context
)
119 : ObjectBackedNativeHandler(context
), dispatcher_(dispatcher
) {
122 base::Bind(&EventBindings::AttachEvent
, base::Unretained(this)));
125 base::Bind(&EventBindings::DetachEvent
, base::Unretained(this)));
127 "AttachFilteredEvent",
128 base::Bind(&EventBindings::AttachFilteredEvent
, base::Unretained(this)));
130 "DetachFilteredEvent",
131 base::Bind(&EventBindings::DetachFilteredEvent
, base::Unretained(this)));
132 RouteFunction("MatchAgainstEventFilter",
133 base::Bind(&EventBindings::MatchAgainstEventFilter
,
134 base::Unretained(this)));
137 EventBindings::~EventBindings() {}
139 // Attach an event name to an object.
140 void EventBindings::AttachEvent(
141 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
142 CHECK_EQ(1, args
.Length());
143 CHECK(args
[0]->IsString());
145 std::string event_name
= *v8::String::Utf8Value(args
[0]->ToString());
147 if (!dispatcher_
->CheckContextAccessToExtensionAPI(event_name
, context()))
150 std::string extension_id
= context()->GetExtensionID();
151 EventListenerCounts
& listener_counts
= g_listener_counts
.Get()[extension_id
];
152 if (++listener_counts
[event_name
] == 1) {
153 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener(
154 extension_id
, context()->GetURL(), event_name
));
157 // This is called the first time the page has added a listener. Since
158 // the background page is the only lazy page, we know this is the first
159 // time this listener has been registered.
160 if (IsLazyBackgroundPage(context()->GetRenderView(),
161 context()->extension())) {
162 content::RenderThread::Get()->Send(
163 new ExtensionHostMsg_AddLazyListener(extension_id
, event_name
));
167 void EventBindings::DetachEvent(
168 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
169 CHECK_EQ(2, args
.Length());
170 CHECK(args
[0]->IsString());
171 CHECK(args
[1]->IsBoolean());
173 std::string event_name
= *v8::String::Utf8Value(args
[0]);
174 bool is_manual
= args
[1]->BooleanValue();
176 std::string extension_id
= context()->GetExtensionID();
177 EventListenerCounts
& listener_counts
= g_listener_counts
.Get()[extension_id
];
179 if (--listener_counts
[event_name
] == 0) {
180 content::RenderThread::Get()->Send(new ExtensionHostMsg_RemoveListener(
181 extension_id
, context()->GetURL(), event_name
));
184 // DetachEvent is called when the last listener for the context is
185 // removed. If the context is the background page, and it removes the
186 // last listener manually, then we assume that it is no longer interested
187 // in being awakened for this event.
188 if (is_manual
&& IsLazyBackgroundPage(context()->GetRenderView(),
189 context()->extension())) {
190 content::RenderThread::Get()->Send(
191 new ExtensionHostMsg_RemoveLazyListener(extension_id
, event_name
));
195 // MatcherID AttachFilteredEvent(string event_name, object filter)
196 // event_name - Name of the event to attach.
197 // filter - Which instances of the named event are we interested in.
198 // returns the id assigned to the listener, which will be returned from calls
199 // to MatchAgainstEventFilter where this listener matches.
200 void EventBindings::AttachFilteredEvent(
201 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
202 CHECK_EQ(2, args
.Length());
203 CHECK(args
[0]->IsString());
204 CHECK(args
[1]->IsObject());
206 std::string event_name
= *v8::String::Utf8Value(args
[0]);
208 // This method throws an exception if it returns false.
209 if (!dispatcher_
->CheckContextAccessToExtensionAPI(event_name
, context()))
212 std::string extension_id
= context()->GetExtensionID();
214 scoped_ptr
<base::DictionaryValue
> filter
;
215 scoped_ptr
<content::V8ValueConverter
> converter(
216 content::V8ValueConverter::create());
218 base::DictionaryValue
* filter_dict
= NULL
;
219 base::Value
* filter_value
=
220 converter
->FromV8Value(args
[1]->ToObject(), context()->v8_context());
222 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
225 if (!filter_value
->GetAsDictionary(&filter_dict
)) {
227 args
.GetReturnValue().Set(static_cast<int32_t>(-1));
231 filter
.reset(filter_dict
);
232 EventFilter
& event_filter
= g_event_filter
.Get();
234 event_filter
.AddEventMatcher(event_name
, ParseEventMatcher(filter
.get()));
236 // Only send IPCs the first time a filter gets added.
237 if (AddFilter(event_name
, extension_id
, filter
.get())) {
238 bool lazy
= IsLazyBackgroundPage(context()->GetRenderView(),
239 context()->extension());
240 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
241 extension_id
, event_name
, *filter
, lazy
));
244 args
.GetReturnValue().Set(static_cast<int32_t>(id
));
247 void EventBindings::DetachFilteredEvent(
248 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
249 CHECK_EQ(2, args
.Length());
250 CHECK(args
[0]->IsInt32());
251 CHECK(args
[1]->IsBoolean());
252 bool is_manual
= args
[1]->BooleanValue();
254 std::string extension_id
= context()->GetExtensionID();
256 int matcher_id
= args
[0]->Int32Value();
257 EventFilter
& event_filter
= g_event_filter
.Get();
258 EventMatcher
* event_matcher
= event_filter
.GetEventMatcher(matcher_id
);
260 const std::string
& event_name
= event_filter
.GetEventName(matcher_id
);
262 // Only send IPCs the last time a filter gets removed.
263 if (RemoveFilter(event_name
, extension_id
, event_matcher
->value())) {
264 bool lazy
= is_manual
&& IsLazyBackgroundPage(context()->GetRenderView(),
265 context()->extension());
266 content::RenderThread::Get()->Send(
267 new ExtensionHostMsg_RemoveFilteredListener(
268 extension_id
, event_name
, *event_matcher
->value(), lazy
));
271 event_filter
.RemoveEventMatcher(matcher_id
);
274 void EventBindings::MatchAgainstEventFilter(
275 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
276 v8::Isolate
* isolate
= args
.GetIsolate();
277 typedef std::set
<EventFilter::MatcherID
> MatcherIDs
;
278 EventFilter
& event_filter
= g_event_filter
.Get();
279 std::string event_name
= *v8::String::Utf8Value(args
[0]->ToString());
280 EventFilteringInfo info
= ParseFromObject(args
[1]->ToObject(), isolate
);
281 // Only match events routed to this context's RenderView or ones that don't
282 // have a routingId in their filter.
283 MatcherIDs matched_event_filters
= event_filter
.MatchEvent(
284 event_name
, info
, context()->GetRenderView()->GetRoutingID());
285 v8::Handle
<v8::Array
> array(
286 v8::Array::New(isolate
, matched_event_filters
.size()));
288 for (MatcherIDs::iterator it
= matched_event_filters
.begin();
289 it
!= matched_event_filters
.end();
291 array
->Set(v8::Integer::New(isolate
, i
++), v8::Integer::New(isolate
, *it
));
293 args
.GetReturnValue().Set(array
);
296 scoped_ptr
<EventMatcher
> EventBindings::ParseEventMatcher(
297 base::DictionaryValue
* filter_dict
) {
298 return scoped_ptr
<EventMatcher
>(new EventMatcher(
299 scoped_ptr
<base::DictionaryValue
>(filter_dict
->DeepCopy()),
300 context()->GetRenderView()->GetRoutingID()));
303 } // namespace extensions