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"
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 "base/message_loop/message_loop.h"
17 #include "chrome/common/extensions/background_info.h"
18 #include "chrome/common/extensions/extension.h"
19 #include "chrome/common/extensions/extension_messages.h"
20 #include "chrome/common/extensions/extension_set.h"
21 #include "chrome/common/extensions/value_counter.h"
22 #include "chrome/common/url_constants.h"
23 #include "chrome/renderer/extensions/chrome_v8_context.h"
24 #include "chrome/renderer/extensions/chrome_v8_context_set.h"
25 #include "chrome/renderer/extensions/chrome_v8_extension.h"
26 #include "chrome/renderer/extensions/dispatcher.h"
27 #include "chrome/renderer/extensions/extension_helper.h"
28 #include "chrome/renderer/extensions/user_script_slave.h"
29 #include "content/public/renderer/render_thread.h"
30 #include "content/public/renderer/render_view.h"
31 #include "content/public/renderer/v8_value_converter.h"
32 #include "extensions/common/event_filter.h"
33 #include "extensions/common/view_type.h"
34 #include "grit/renderer_resources.h"
35 #include "third_party/WebKit/public/platform/WebURL.h"
36 #include "third_party/WebKit/public/platform/WebURLRequest.h"
37 #include "third_party/WebKit/public/web/WebDocument.h"
38 #include "third_party/WebKit/public/web/WebFrame.h"
39 #include "third_party/WebKit/public/web/WebView.h"
41 #include "v8/include/v8.h"
43 using WebKit::WebFrame;
45 using content::RenderThread;
47 namespace extensions {
51 // A map of event names to the number of contexts listening to that event.
52 // We notify the browser about event listeners when we transition between 0
54 typedef std::map<std::string, int> EventListenerCounts;
56 // A map of extension IDs to listener counts for that extension.
57 base::LazyInstance<std::map<std::string, EventListenerCounts> >
58 g_listener_counts = LAZY_INSTANCE_INITIALIZER;
60 // A map of event names to a (filter -> count) map. The map is used to keep
61 // track of which filters are in effect for which events.
62 // We notify the browser about filtered event listeners when we transition
64 typedef std::map<std::string, linked_ptr<ValueCounter> >
65 FilteredEventListenerCounts;
67 // A map of extension IDs to filtered listener counts for that extension.
68 base::LazyInstance<std::map<std::string, FilteredEventListenerCounts> >
69 g_filtered_listener_counts = LAZY_INSTANCE_INITIALIZER;
71 base::LazyInstance<EventFilter> g_event_filter = LAZY_INSTANCE_INITIALIZER;
73 // TODO(koz): Merge this into EventBindings.
74 class ExtensionImpl : public ChromeV8Extension {
76 explicit ExtensionImpl(Dispatcher* dispatcher, ChromeV8Context* context)
77 : ChromeV8Extension(dispatcher, context) {
78 RouteFunction("AttachEvent",
79 base::Bind(&ExtensionImpl::AttachEvent, base::Unretained(this)));
80 RouteFunction("DetachEvent",
81 base::Bind(&ExtensionImpl::DetachEvent, base::Unretained(this)));
82 RouteFunction("AttachFilteredEvent",
83 base::Bind(&ExtensionImpl::AttachFilteredEvent,
84 base::Unretained(this)));
85 RouteFunction("DetachFilteredEvent",
86 base::Bind(&ExtensionImpl::DetachFilteredEvent,
87 base::Unretained(this)));
88 RouteFunction("MatchAgainstEventFilter",
89 base::Bind(&ExtensionImpl::MatchAgainstEventFilter,
90 base::Unretained(this)));
93 virtual ~ExtensionImpl() {}
95 // Attach an event name to an object.
96 void AttachEvent(const v8::FunctionCallbackInfo<v8::Value>& args) {
97 CHECK_EQ(1, args.Length());
98 CHECK(args[0]->IsString());
100 std::string event_name = *v8::String::AsciiValue(args[0]->ToString());
102 if (!dispatcher_->CheckContextAccessToExtensionAPI(event_name, context()))
105 std::string extension_id = context()->GetExtensionID();
106 EventListenerCounts& listener_counts =
107 g_listener_counts.Get()[extension_id];
108 if (++listener_counts[event_name] == 1) {
109 content::RenderThread::Get()->Send(
110 new ExtensionHostMsg_AddListener(extension_id, event_name));
113 // This is called the first time the page has added a listener. Since
114 // the background page is the only lazy page, we know this is the first
115 // time this listener has been registered.
116 if (IsLazyBackgroundPage(GetRenderView(), context()->extension())) {
117 content::RenderThread::Get()->Send(
118 new ExtensionHostMsg_AddLazyListener(extension_id, event_name));
122 void DetachEvent(const v8::FunctionCallbackInfo<v8::Value>& args) {
123 CHECK_EQ(2, args.Length());
124 CHECK(args[0]->IsString());
125 CHECK(args[1]->IsBoolean());
127 std::string event_name = *v8::String::AsciiValue(args[0]);
128 bool is_manual = args[1]->BooleanValue();
130 std::string extension_id = context()->GetExtensionID();
131 EventListenerCounts& listener_counts =
132 g_listener_counts.Get()[extension_id];
134 if (--listener_counts[event_name] == 0) {
135 content::RenderThread::Get()->Send(
136 new ExtensionHostMsg_RemoveListener(extension_id, event_name));
139 // DetachEvent is called when the last listener for the context is
140 // removed. If the context is the background page, and it removes the
141 // last listener manually, then we assume that it is no longer interested
142 // in being awakened for this event.
143 if (is_manual && IsLazyBackgroundPage(GetRenderView(),
144 context()->extension())) {
145 content::RenderThread::Get()->Send(
146 new ExtensionHostMsg_RemoveLazyListener(extension_id, event_name));
150 // MatcherID AttachFilteredEvent(string event_name, object filter)
151 // event_name - Name of the event to attach.
152 // filter - Which instances of the named event are we interested in.
153 // returns the id assigned to the listener, which will be returned from calls
154 // to MatchAgainstEventFilter where this listener matches.
155 void AttachFilteredEvent(const v8::FunctionCallbackInfo<v8::Value>& args) {
156 CHECK_EQ(2, args.Length());
157 CHECK(args[0]->IsString());
158 CHECK(args[1]->IsObject());
160 std::string event_name = *v8::String::AsciiValue(args[0]);
162 // This method throws an exception if it returns false.
163 if (!dispatcher_->CheckContextAccessToExtensionAPI(event_name, context()))
166 std::string extension_id = context()->GetExtensionID();
167 if (extension_id.empty()) {
168 args.GetReturnValue().Set(static_cast<int32_t>(-1));
172 scoped_ptr<base::DictionaryValue> filter;
173 scoped_ptr<content::V8ValueConverter> converter(
174 content::V8ValueConverter::create());
176 base::DictionaryValue* filter_dict = NULL;
177 base::Value* filter_value =
178 converter->FromV8Value(args[1]->ToObject(), context()->v8_context());
180 args.GetReturnValue().Set(static_cast<int32_t>(-1));
183 if (!filter_value->GetAsDictionary(&filter_dict)) {
185 args.GetReturnValue().Set(static_cast<int32_t>(-1));
189 filter.reset(filter_dict);
190 EventFilter& event_filter = g_event_filter.Get();
191 int id = event_filter.AddEventMatcher(event_name, ParseEventMatcher(
194 // Only send IPCs the first time a filter gets added.
195 if (AddFilter(event_name, extension_id, filter.get())) {
196 bool lazy = IsLazyBackgroundPage(GetRenderView(), context()->extension());
197 content::RenderThread::Get()->Send(
198 new ExtensionHostMsg_AddFilteredListener(extension_id, event_name,
202 args.GetReturnValue().Set(static_cast<int32_t>(id));
205 // Add a filter to |event_name| in |extension_id|, returning true if it
206 // was the first filter for that event in that extension.
207 static bool AddFilter(const std::string& event_name,
208 const std::string& extension_id,
209 base::DictionaryValue* filter) {
210 FilteredEventListenerCounts& counts =
211 g_filtered_listener_counts.Get()[extension_id];
212 FilteredEventListenerCounts::iterator it = counts.find(event_name);
213 if (it == counts.end())
214 counts[event_name].reset(new ValueCounter);
216 int result = counts[event_name]->Add(*filter);
220 // Remove a filter from |event_name| in |extension_id|, returning true if it
221 // was the last filter for that event in that extension.
222 static bool RemoveFilter(const std::string& event_name,
223 const std::string& extension_id,
224 base::DictionaryValue* filter) {
225 FilteredEventListenerCounts& counts =
226 g_filtered_listener_counts.Get()[extension_id];
227 FilteredEventListenerCounts::iterator it = counts.find(event_name);
228 if (it == counts.end())
230 return 0 == it->second->Remove(*filter);
233 // void DetachFilteredEvent(int id, bool manual)
234 // id - Id of the event to detach.
235 // manual - false if this is part of the extension unload process where all
236 // listeners are automatically detached.
237 void DetachFilteredEvent(const v8::FunctionCallbackInfo<v8::Value>& args) {
238 CHECK_EQ(2, args.Length());
239 CHECK(args[0]->IsInt32());
240 CHECK(args[1]->IsBoolean());
241 bool is_manual = args[1]->BooleanValue();
243 std::string extension_id = context()->GetExtensionID();
244 if (extension_id.empty())
247 int matcher_id = args[0]->Int32Value();
248 EventFilter& event_filter = g_event_filter.Get();
249 EventMatcher* event_matcher =
250 event_filter.GetEventMatcher(matcher_id);
252 const std::string& event_name = event_filter.GetEventName(matcher_id);
254 // Only send IPCs the last time a filter gets removed.
255 if (RemoveFilter(event_name, extension_id, event_matcher->value())) {
256 bool lazy = is_manual && IsLazyBackgroundPage(GetRenderView(),
257 context()->extension());
258 content::RenderThread::Get()->Send(
259 new ExtensionHostMsg_RemoveFilteredListener(extension_id, event_name,
260 *event_matcher->value(),
264 event_filter.RemoveEventMatcher(matcher_id);
267 void MatchAgainstEventFilter(
268 const v8::FunctionCallbackInfo<v8::Value>& args) {
269 typedef std::set<EventFilter::MatcherID> MatcherIDs;
270 EventFilter& event_filter = g_event_filter.Get();
271 std::string event_name = *v8::String::AsciiValue(args[0]->ToString());
272 EventFilteringInfo info = ParseFromObject(args[1]->ToObject());
273 // Only match events routed to this context's RenderView or ones that don't
274 // have a routingId in their filter.
275 MatcherIDs matched_event_filters = event_filter.MatchEvent(
276 event_name, info, context()->GetRenderView()->GetRoutingID());
277 v8::Handle<v8::Array> array(v8::Array::New(matched_event_filters.size()));
279 for (MatcherIDs::iterator it = matched_event_filters.begin();
280 it != matched_event_filters.end(); ++it) {
281 array->Set(v8::Integer::New(i++), v8::Integer::New(*it));
283 args.GetReturnValue().Set(array);
286 static EventFilteringInfo ParseFromObject(v8::Handle<v8::Object> object) {
287 EventFilteringInfo info;
288 v8::Handle<v8::String> url(v8::String::New("url"));
289 if (object->Has(url)) {
290 v8::Handle<v8::Value> url_value(object->Get(url));
291 info.SetURL(GURL(*v8::String::AsciiValue(url_value)));
293 v8::Handle<v8::String> instance_id(v8::String::New("instanceId"));
294 if (object->Has(instance_id)) {
295 v8::Handle<v8::Value> instance_id_value(object->Get(instance_id));
296 info.SetInstanceID(instance_id_value->IntegerValue());
298 v8::Handle<v8::String> service_type(v8::String::New("serviceType"));
299 if (object->Has(service_type)) {
300 v8::Handle<v8::Value> service_type_value(object->Get(service_type));
301 info.SetServiceType(*v8::String::AsciiValue(service_type_value));
307 static bool IsLazyBackgroundPage(content::RenderView* render_view,
308 const Extension* extension) {
311 ExtensionHelper* helper = ExtensionHelper::Get(render_view);
312 return (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
313 helper->view_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
316 scoped_ptr<EventMatcher> 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()));
327 ChromeV8Extension* EventBindings::Create(Dispatcher* dispatcher,
328 ChromeV8Context* context) {
329 return new ExtensionImpl(dispatcher, context);
332 } // namespace extensions