Fix invalid cast in AppCacheGroup::AddUpdateObserver.
[chromium-blink-merge.git] / extensions / renderer / event_bindings.cc
blobf27d123d9906f1ef7abd684cbdf1bebc2fefbacf
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"
7 #include <map>
8 #include <utility>
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"
26 #include "url/gurl.h"
28 namespace extensions {
30 namespace {
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
34 // and 1.
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->GetURL().is_valid());
59 return crx_file::id_util::IdIsValid(extension_id)
60 ? extension_id
61 : script_context->GetURL().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 return info;
103 // Add a filter to |event_name| in |extension_id|, returning true if it
104 // was the first filter for that event in that extension.
105 bool AddFilter(const std::string& event_name,
106 const std::string& extension_id,
107 const base::DictionaryValue& filter) {
108 FilteredEventListenerKey key(extension_id, event_name);
109 FilteredEventListenerCounts& all_counts = g_filtered_listener_counts.Get();
110 FilteredEventListenerCounts::const_iterator counts = all_counts.find(key);
111 if (counts == all_counts.end()) {
112 counts = all_counts.insert(key, make_scoped_ptr(new ValueCounter())).first;
114 return counts->second->Add(filter);
117 // Remove a filter from |event_name| in |extension_id|, returning true if it
118 // was the last filter for that event in that extension.
119 bool RemoveFilter(const std::string& event_name,
120 const std::string& extension_id,
121 base::DictionaryValue* filter) {
122 FilteredEventListenerKey key(extension_id, event_name);
123 FilteredEventListenerCounts& all_counts = g_filtered_listener_counts.Get();
124 FilteredEventListenerCounts::const_iterator counts = all_counts.find(key);
125 if (counts == all_counts.end())
126 return false;
127 // Note: Remove() returns true if it removed the last filter equivalent to
128 // |filter|. If there are more equivalent filters, or if there weren't any in
129 // the first place, it returns false.
130 if (counts->second->Remove(*filter)) {
131 if (counts->second->is_empty())
132 all_counts.erase(counts); // Clean up if there are no more filters.
133 return true;
135 return false;
138 } // namespace
140 EventBindings::EventBindings(ScriptContext* context)
141 : ObjectBackedNativeHandler(context) {
142 RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler,
143 base::Unretained(this)));
144 RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler,
145 base::Unretained(this)));
146 RouteFunction(
147 "AttachFilteredEvent",
148 base::Bind(&EventBindings::AttachFilteredEvent, base::Unretained(this)));
149 RouteFunction("DetachFilteredEvent",
150 base::Bind(&EventBindings::DetachFilteredEventHandler,
151 base::Unretained(this)));
152 RouteFunction("MatchAgainstEventFilter",
153 base::Bind(&EventBindings::MatchAgainstEventFilter,
154 base::Unretained(this)));
156 // It's safe to use base::Unretained here because |context| will always
157 // outlive us.
158 context->AddInvalidationObserver(
159 base::Bind(&EventBindings::OnInvalidated, base::Unretained(this)));
162 EventBindings::~EventBindings() {}
164 void EventBindings::AttachEventHandler(
165 const v8::FunctionCallbackInfo<v8::Value>& args) {
166 CHECK_EQ(1, args.Length());
167 CHECK(args[0]->IsString());
168 AttachEvent(*v8::String::Utf8Value(args[0]));
171 void EventBindings::AttachEvent(const std::string& event_name) {
172 if (!context()->HasAccessOrThrowError(event_name))
173 return;
175 // Record the attachment for this context so that events can be detached when
176 // the context is destroyed.
178 // Ideally we'd CHECK that it's not already attached, however that's not
179 // possible because extensions can create and attach events themselves. Very
180 // silly, but that's the way it is. For an example of this, see
181 // chrome/test/data/extensions/api_test/events/background.js.
182 attached_event_names_.insert(event_name);
184 const std::string& extension_id = context()->GetExtensionID();
185 if (IncrementEventListenerCount(context(), event_name) == 1) {
186 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener(
187 extension_id, context()->GetURL(), event_name));
190 // This is called the first time the page has added a listener. Since
191 // the background page is the only lazy page, we know this is the first
192 // time this listener has been registered.
193 if (ExtensionFrameHelper::IsContextForEventPage(context())) {
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 && ExtensionFrameHelper::IsContextForEventPage(context())) {
223 content::RenderThread::Get()->Send(
224 new ExtensionHostMsg_RemoveLazyListener(extension_id, event_name));
228 // MatcherID AttachFilteredEvent(string event_name, object filter)
229 // event_name - Name of the event to attach.
230 // filter - Which instances of the named event are we interested in.
231 // returns the id assigned to the listener, which will be returned from calls
232 // to MatchAgainstEventFilter where this listener matches.
233 void EventBindings::AttachFilteredEvent(
234 const v8::FunctionCallbackInfo<v8::Value>& args) {
235 CHECK_EQ(2, args.Length());
236 CHECK(args[0]->IsString());
237 CHECK(args[1]->IsObject());
239 std::string event_name = *v8::String::Utf8Value(args[0]);
240 if (!context()->HasAccessOrThrowError(event_name))
241 return;
243 scoped_ptr<base::DictionaryValue> filter;
245 scoped_ptr<content::V8ValueConverter> converter(
246 content::V8ValueConverter::create());
247 scoped_ptr<base::Value> filter_value(converter->FromV8Value(
248 v8::Local<v8::Object>::Cast(args[1]), context()->v8_context()));
249 if (!filter_value || !filter_value->IsType(base::Value::TYPE_DICTIONARY)) {
250 args.GetReturnValue().Set(static_cast<int32_t>(-1));
251 return;
253 filter.reset(static_cast<base::DictionaryValue*>(filter_value.release()));
256 // Hold onto a weak reference to |filter| so that it can be used after passing
257 // ownership to |event_filter|.
258 base::DictionaryValue* filter_weak = filter.get();
259 int id = g_event_filter.Get().AddEventMatcher(
260 event_name, ParseEventMatcher(filter.Pass()));
261 attached_matcher_ids_.insert(id);
263 // Only send IPCs the first time a filter gets added.
264 std::string extension_id = context()->GetExtensionID();
265 if (AddFilter(event_name, extension_id, *filter_weak)) {
266 bool lazy = ExtensionFrameHelper::IsContextForEventPage(context());
267 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
268 extension_id, event_name, *filter_weak, lazy));
271 args.GetReturnValue().Set(static_cast<int32_t>(id));
274 void EventBindings::DetachFilteredEventHandler(
275 const v8::FunctionCallbackInfo<v8::Value>& args) {
276 CHECK_EQ(2, args.Length());
277 CHECK(args[0]->IsInt32());
278 CHECK(args[1]->IsBoolean());
279 DetachFilteredEvent(args[0]->Int32Value(), args[1]->BooleanValue());
282 void EventBindings::DetachFilteredEvent(int matcher_id, bool is_manual) {
283 EventFilter& event_filter = g_event_filter.Get();
284 EventMatcher* event_matcher = event_filter.GetEventMatcher(matcher_id);
286 const std::string& event_name = event_filter.GetEventName(matcher_id);
288 // Only send IPCs the last time a filter gets removed.
289 std::string extension_id = context()->GetExtensionID();
290 if (RemoveFilter(event_name, extension_id, event_matcher->value())) {
291 bool remove_lazy =
292 is_manual && ExtensionFrameHelper::IsContextForEventPage(context());
293 content::RenderThread::Get()->Send(
294 new ExtensionHostMsg_RemoveFilteredListener(
295 extension_id, event_name, *event_matcher->value(), remove_lazy));
298 event_filter.RemoveEventMatcher(matcher_id);
299 attached_matcher_ids_.erase(matcher_id);
302 void EventBindings::MatchAgainstEventFilter(
303 const v8::FunctionCallbackInfo<v8::Value>& args) {
304 v8::Isolate* isolate = args.GetIsolate();
305 typedef std::set<EventFilter::MatcherID> MatcherIDs;
306 EventFilter& event_filter = g_event_filter.Get();
307 std::string event_name = *v8::String::Utf8Value(args[0]);
308 EventFilteringInfo info =
309 ParseFromObject(args[1]->ToObject(isolate), isolate);
310 // Only match events routed to this context's RenderFrame or ones that don't
311 // have a routingId in their filter.
312 MatcherIDs matched_event_filters = event_filter.MatchEvent(
313 event_name, info, context()->GetRenderFrame()->GetRoutingID());
314 v8::Local<v8::Array> array(
315 v8::Array::New(isolate, matched_event_filters.size()));
316 int i = 0;
317 for (MatcherIDs::iterator it = matched_event_filters.begin();
318 it != matched_event_filters.end();
319 ++it) {
320 array->Set(v8::Integer::New(isolate, i++), v8::Integer::New(isolate, *it));
322 args.GetReturnValue().Set(array);
325 scoped_ptr<EventMatcher> EventBindings::ParseEventMatcher(
326 scoped_ptr<base::DictionaryValue> filter) {
327 return make_scoped_ptr(new EventMatcher(
328 filter.Pass(), context()->GetRenderFrame()->GetRoutingID()));
331 void EventBindings::OnInvalidated() {
332 // Detach all attached events that weren't attached. Iterate over a copy
333 // because it will be mutated.
334 std::set<std::string> attached_event_names_safe = attached_event_names_;
335 for (const std::string& event_name : attached_event_names_safe) {
336 DetachEvent(event_name, false /* is_manual */);
338 DCHECK(attached_event_names_.empty())
339 << "Events cannot be attached during invalidation";
341 // Same for filtered events.
342 std::set<int> attached_matcher_ids_safe = attached_matcher_ids_;
343 for (int matcher_id : attached_matcher_ids_safe) {
344 DetachFilteredEvent(matcher_id, false /* is_manual */);
346 DCHECK(attached_matcher_ids_.empty())
347 << "Filtered events cannot be attached during invalidation";
350 } // namespace extensions