Suppression for crbug/241044.
[chromium-blink-merge.git] / chrome / renderer / extensions / event_bindings.cc
blob4d09951c744e2c45e62576a755c711bab6c7561b
1 // Copyright (c) 2012 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 "chrome/renderer/extensions/event_bindings.h"
7 #include <vector>
9 #include "base/bind.h"
10 #include "base/basictypes.h"
11 #include "base/lazy_instance.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/message_loop.h"
14 #include "chrome/common/extensions/background_info.h"
15 #include "chrome/common/extensions/extension.h"
16 #include "chrome/common/extensions/extension_messages.h"
17 #include "chrome/common/extensions/extension_set.h"
18 #include "chrome/common/extensions/value_counter.h"
19 #include "chrome/common/url_constants.h"
20 #include "chrome/renderer/extensions/chrome_v8_context.h"
21 #include "chrome/renderer/extensions/chrome_v8_context_set.h"
22 #include "chrome/renderer/extensions/chrome_v8_extension.h"
23 #include "chrome/renderer/extensions/dispatcher.h"
24 #include "chrome/renderer/extensions/event_bindings.h"
25 #include "chrome/renderer/extensions/extension_helper.h"
26 #include "chrome/renderer/extensions/user_script_slave.h"
27 #include "content/public/renderer/render_thread.h"
28 #include "content/public/renderer/v8_value_converter.h"
29 #include "extensions/common/event_filter.h"
30 #include "extensions/common/view_type.h"
31 #include "googleurl/src/gurl.h"
32 #include "grit/renderer_resources.h"
33 #include "third_party/WebKit/Source/Platform/chromium/public/WebURL.h"
34 #include "third_party/WebKit/Source/Platform/chromium/public/WebURLRequest.h"
35 #include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
36 #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
37 #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
38 #include "v8/include/v8.h"
40 using WebKit::WebFrame;
41 using WebKit::WebURL;
42 using content::RenderThread;
44 namespace extensions {
46 namespace {
48 // A map of event names to the number of contexts listening to that event.
49 // We notify the browser about event listeners when we transition between 0
50 // and 1.
51 typedef std::map<std::string, int> EventListenerCounts;
53 // A map of extension IDs to listener counts for that extension.
54 base::LazyInstance<std::map<std::string, EventListenerCounts> >
55 g_listener_counts = LAZY_INSTANCE_INITIALIZER;
57 // A map of event names to a (filter -> count) map. The map is used to keep
58 // track of which filters are in effect for which events.
59 // We notify the browser about filtered event listeners when we transition
60 // between 0 and 1.
61 typedef std::map<std::string, linked_ptr<ValueCounter> >
62 FilteredEventListenerCounts;
64 // A map of extension IDs to filtered listener counts for that extension.
65 base::LazyInstance<std::map<std::string, FilteredEventListenerCounts> >
66 g_filtered_listener_counts = LAZY_INSTANCE_INITIALIZER;
68 base::LazyInstance<EventFilter> g_event_filter = LAZY_INSTANCE_INITIALIZER;
70 // TODO(koz): Merge this into EventBindings.
71 class ExtensionImpl : public ChromeV8Extension {
72 public:
73 explicit ExtensionImpl(Dispatcher* dispatcher,
74 v8::Handle<v8::Context> v8_context)
75 : ChromeV8Extension(dispatcher, v8_context) {
76 RouteFunction("AttachEvent",
77 base::Bind(&ExtensionImpl::AttachEvent, base::Unretained(this)));
78 RouteFunction("DetachEvent",
79 base::Bind(&ExtensionImpl::DetachEvent, base::Unretained(this)));
80 RouteFunction("AttachFilteredEvent",
81 base::Bind(&ExtensionImpl::AttachFilteredEvent,
82 base::Unretained(this)));
83 RouteFunction("DetachFilteredEvent",
84 base::Bind(&ExtensionImpl::DetachFilteredEvent,
85 base::Unretained(this)));
86 RouteFunction("MatchAgainstEventFilter",
87 base::Bind(&ExtensionImpl::MatchAgainstEventFilter,
88 base::Unretained(this)));
91 virtual ~ExtensionImpl() {}
93 // Attach an event name to an object.
94 v8::Handle<v8::Value> AttachEvent(const v8::Arguments& args) {
95 DCHECK(args.Length() == 1);
96 // TODO(erikkay) should enforce that event name is a string in the bindings
97 DCHECK(args[0]->IsString() || args[0]->IsUndefined());
99 if (args[0]->IsString()) {
100 std::string event_name = *v8::String::AsciiValue(args[0]->ToString());
101 const ChromeV8ContextSet& context_set = dispatcher_->v8_context_set();
102 ChromeV8Context* context = context_set.GetByV8Context(v8_context());
103 CHECK(context);
105 if (!dispatcher_->CheckContextAccessToExtensionAPI(event_name, context))
106 return v8::Undefined();
108 std::string extension_id = context->GetExtensionID();
109 EventListenerCounts& listener_counts =
110 g_listener_counts.Get()[extension_id];
111 if (++listener_counts[event_name] == 1) {
112 content::RenderThread::Get()->Send(
113 new ExtensionHostMsg_AddListener(extension_id, event_name));
116 // This is called the first time the page has added a listener. Since
117 // the background page is the only lazy page, we know this is the first
118 // time this listener has been registered.
119 if (IsLazyBackgroundPage(GetRenderView(), context->extension())) {
120 content::RenderThread::Get()->Send(
121 new ExtensionHostMsg_AddLazyListener(extension_id, event_name));
124 return v8::Undefined();
127 v8::Handle<v8::Value> DetachEvent(const v8::Arguments& args) {
128 DCHECK(args.Length() == 2);
129 // TODO(erikkay) should enforce that event name is a string in the bindings
130 DCHECK(args[0]->IsString() || args[0]->IsUndefined());
132 if (args[0]->IsString() && args[1]->IsBoolean()) {
133 std::string event_name = *v8::String::AsciiValue(args[0]->ToString());
134 bool is_manual = args[1]->BooleanValue();
136 const ChromeV8ContextSet& context_set = dispatcher_->v8_context_set();
137 ChromeV8Context* context = context_set.GetByV8Context(v8_context());
138 if (!context)
139 return v8::Undefined();
141 std::string extension_id = context->GetExtensionID();
142 EventListenerCounts& listener_counts =
143 g_listener_counts.Get()[extension_id];
145 if (--listener_counts[event_name] == 0) {
146 content::RenderThread::Get()->Send(
147 new ExtensionHostMsg_RemoveListener(extension_id, event_name));
150 // DetachEvent is called when the last listener for the context is
151 // removed. If the context is the background page, and it removes the
152 // last listener manually, then we assume that it is no longer interested
153 // in being awakened for this event.
154 if (is_manual && IsLazyBackgroundPage(GetRenderView(),
155 context->extension())) {
156 content::RenderThread::Get()->Send(
157 new ExtensionHostMsg_RemoveLazyListener(extension_id, event_name));
160 return v8::Undefined();
163 // MatcherID AttachFilteredEvent(string event_name, object filter)
164 // event_name - Name of the event to attach.
165 // filter - Which instances of the named event are we interested in.
166 // returns the id assigned to the listener, which will be returned from calls
167 // to MatchAgainstEventFilter where this listener matches.
168 v8::Handle<v8::Value> AttachFilteredEvent(const v8::Arguments& args) {
169 DCHECK_EQ(2, args.Length());
170 DCHECK(args[0]->IsString());
171 DCHECK(args[1]->IsObject());
173 const ChromeV8ContextSet& context_set = dispatcher_->v8_context_set();
174 ChromeV8Context* context = context_set.GetByV8Context(v8_context());
175 DCHECK(context);
176 if (!context)
177 return v8::Integer::New(-1);
179 std::string event_name = *v8::String::AsciiValue(args[0]);
180 // This method throws an exception if it returns false.
181 if (!dispatcher_->CheckContextAccessToExtensionAPI(event_name, context))
182 return v8::Undefined();
184 std::string extension_id = context->GetExtensionID();
185 if (extension_id.empty())
186 return v8::Integer::New(-1);
188 scoped_ptr<base::DictionaryValue> filter;
189 scoped_ptr<content::V8ValueConverter> converter(
190 content::V8ValueConverter::create());
192 base::DictionaryValue* filter_dict = NULL;
193 base::Value* filter_value =
194 converter->FromV8Value(args[1]->ToObject(), context->v8_context());
195 if (!filter_value)
196 return v8::Integer::New(-1);
197 if (!filter_value->GetAsDictionary(&filter_dict)) {
198 delete filter_value;
199 return v8::Integer::New(-1);
202 filter.reset(filter_dict);
203 EventFilter& event_filter = g_event_filter.Get();
204 int id = event_filter.AddEventMatcher(event_name, ParseEventMatcher(
205 filter.get()));
207 // Only send IPCs the first time a filter gets added.
208 if (AddFilter(event_name, extension_id, filter.get())) {
209 bool lazy = IsLazyBackgroundPage(GetRenderView(), context->extension());
210 content::RenderThread::Get()->Send(
211 new ExtensionHostMsg_AddFilteredListener(extension_id, event_name,
212 *filter, lazy));
215 return v8::Integer::New(id);
218 // Add a filter to |event_name| in |extension_id|, returning true if it
219 // was the first filter for that event in that extension.
220 static bool AddFilter(const std::string& event_name,
221 const std::string& extension_id,
222 base::DictionaryValue* filter) {
223 FilteredEventListenerCounts& counts =
224 g_filtered_listener_counts.Get()[extension_id];
225 FilteredEventListenerCounts::iterator it = counts.find(event_name);
226 if (it == counts.end())
227 counts[event_name].reset(new ValueCounter);
229 int result = counts[event_name]->Add(*filter);
230 return 1 == result;
233 // Remove a filter from |event_name| in |extension_id|, returning true if it
234 // was the last filter for that event in that extension.
235 static bool RemoveFilter(const std::string& event_name,
236 const std::string& extension_id,
237 base::DictionaryValue* filter) {
238 FilteredEventListenerCounts& counts =
239 g_filtered_listener_counts.Get()[extension_id];
240 FilteredEventListenerCounts::iterator it = counts.find(event_name);
241 if (it == counts.end())
242 return false;
243 return 0 == it->second->Remove(*filter);
246 // void DetachFilteredEvent(int id, bool manual)
247 // id - Id of the event to detach.
248 // manual - false if this is part of the extension unload process where all
249 // listeners are automatically detached.
250 v8::Handle<v8::Value> DetachFilteredEvent(const v8::Arguments& args) {
251 DCHECK_EQ(2, args.Length());
252 DCHECK(args[0]->IsInt32());
253 DCHECK(args[1]->IsBoolean());
254 bool is_manual = args[1]->BooleanValue();
255 const ChromeV8ContextSet& context_set = dispatcher_->v8_context_set();
256 ChromeV8Context* context = context_set.GetByV8Context(v8_context());
257 if (!context)
258 return v8::Undefined();
260 std::string extension_id = context->GetExtensionID();
261 if (extension_id.empty())
262 return v8::Undefined();
264 int matcher_id = args[0]->Int32Value();
265 EventFilter& event_filter = g_event_filter.Get();
266 EventMatcher* event_matcher =
267 event_filter.GetEventMatcher(matcher_id);
269 const std::string& event_name = event_filter.GetEventName(matcher_id);
271 // Only send IPCs the last time a filter gets removed.
272 if (RemoveFilter(event_name, extension_id, event_matcher->value())) {
273 bool lazy = is_manual && IsLazyBackgroundPage(GetRenderView(),
274 context->extension());
275 content::RenderThread::Get()->Send(
276 new ExtensionHostMsg_RemoveFilteredListener(extension_id, event_name,
277 *event_matcher->value(),
278 lazy));
281 event_filter.RemoveEventMatcher(matcher_id);
283 return v8::Undefined();
286 v8::Handle<v8::Value> MatchAgainstEventFilter(const v8::Arguments& args) {
287 typedef std::set<EventFilter::MatcherID> MatcherIDs;
289 EventFilter& event_filter = g_event_filter.Get();
290 std::string event_name = *v8::String::AsciiValue(args[0]->ToString());
291 EventFilteringInfo info = ParseFromObject(args[1]->ToObject());
292 MatcherIDs matched_event_filters = event_filter.MatchEvent(
293 event_name, info);
294 v8::Handle<v8::Array> array(v8::Array::New(matched_event_filters.size()));
295 int i = 0;
296 for (MatcherIDs::iterator it = matched_event_filters.begin();
297 it != matched_event_filters.end(); ++it) {
298 array->Set(v8::Integer::New(i++), v8::Integer::New(*it));
300 return array;
303 static EventFilteringInfo ParseFromObject(v8::Handle<v8::Object> object) {
304 EventFilteringInfo info;
305 v8::Handle<v8::String> url(v8::String::New("url"));
306 if (object->Has(url)) {
307 v8::Handle<v8::Value> url_value(object->Get(url));
308 info.SetURL(GURL(*v8::String::AsciiValue(url_value)));
310 return info;
313 private:
314 static bool IsLazyBackgroundPage(content::RenderView* render_view,
315 const Extension* extension) {
316 if (!render_view)
317 return false;
318 ExtensionHelper* helper = ExtensionHelper::Get(render_view);
319 return (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
320 helper->view_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
323 static scoped_ptr<EventMatcher> ParseEventMatcher(
324 base::DictionaryValue* filter_dict) {
325 return scoped_ptr<EventMatcher>(new EventMatcher(
326 scoped_ptr<base::DictionaryValue>(filter_dict->DeepCopy())));
330 } // namespace
332 // static
333 ChromeV8Extension* EventBindings::Create(Dispatcher* dispatcher,
334 v8::Handle<v8::Context> context) {
335 return new ExtensionImpl(dispatcher, context);
338 } // namespace extensions