Add test for clicking bookmark star in presence of ctrl-D keybinding
[chromium-blink-merge.git] / extensions / browser / extension_function.cc
bloba1cb84cc64eae1841831f31b951fbb09741ffdcd
1 // Copyright 2013 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/browser/extension_function.h"
7 #include "base/logging.h"
8 #include "base/memory/singleton.h"
9 #include "base/synchronization/lock.h"
10 #include "content/public/browser/notification_source.h"
11 #include "content/public/browser/notification_types.h"
12 #include "content/public/browser/render_frame_host.h"
13 #include "content/public/browser/render_view_host.h"
14 #include "content/public/browser/web_contents.h"
15 #include "content/public/browser/web_contents_observer.h"
16 #include "extensions/browser/extension_function_dispatcher.h"
17 #include "extensions/browser/extension_message_filter.h"
18 #include "extensions/common/error_utils.h"
19 #include "extensions/common/extension_api.h"
20 #include "extensions/common/extension_messages.h"
22 using content::BrowserThread;
23 using content::RenderViewHost;
24 using content::WebContents;
25 using extensions::ErrorUtils;
26 using extensions::ExtensionAPI;
27 using extensions::Feature;
29 namespace {
31 class ArgumentListResponseValue
32 : public ExtensionFunction::ResponseValueObject {
33 public:
34 ArgumentListResponseValue(const std::string& function_name,
35 const char* title,
36 ExtensionFunction* function,
37 scoped_ptr<base::ListValue> result)
38 : function_name_(function_name), title_(title) {
39 if (function->GetResultList()) {
40 DCHECK_EQ(function->GetResultList(), result.get())
41 << "The result set on this function (" << function_name_ << ") "
42 << "either by calling SetResult() or directly modifying |result_| is "
43 << "different to the one passed to " << title_ << "(). "
44 << "The best way to fix this problem is to exclusively use " << title_
45 << "(). SetResult() and |result_| are deprecated.";
46 } else {
47 function->SetResultList(result.Pass());
49 // It would be nice to DCHECK(error.empty()) but some legacy extension
50 // function implementations... I'm looking at chrome.input.ime... do this
51 // for some reason.
54 ~ArgumentListResponseValue() override {}
56 bool Apply() override { return true; }
58 private:
59 std::string function_name_;
60 const char* title_;
63 class ErrorResponseValue : public ExtensionFunction::ResponseValueObject {
64 public:
65 ErrorResponseValue(ExtensionFunction* function, const std::string& error) {
66 // It would be nice to DCHECK(!error.empty()) but too many legacy extension
67 // function implementations don't set error but signal failure.
68 function->SetError(error);
71 ~ErrorResponseValue() override {}
73 bool Apply() override { return false; }
76 class BadMessageResponseValue : public ExtensionFunction::ResponseValueObject {
77 public:
78 explicit BadMessageResponseValue(ExtensionFunction* function) {
79 function->set_bad_message(true);
80 NOTREACHED() << function->name() << ": bad message";
83 ~BadMessageResponseValue() override {}
85 bool Apply() override { return false; }
88 class RespondNowAction : public ExtensionFunction::ResponseActionObject {
89 public:
90 typedef base::Callback<void(bool)> SendResponseCallback;
91 RespondNowAction(ExtensionFunction::ResponseValue result,
92 const SendResponseCallback& send_response)
93 : result_(result.Pass()), send_response_(send_response) {}
94 ~RespondNowAction() override {}
96 void Execute() override { send_response_.Run(result_->Apply()); }
98 private:
99 ExtensionFunction::ResponseValue result_;
100 SendResponseCallback send_response_;
103 class RespondLaterAction : public ExtensionFunction::ResponseActionObject {
104 public:
105 ~RespondLaterAction() override {}
107 void Execute() override {}
110 // Used in implementation of ScopedUserGestureForTests.
111 class UserGestureForTests {
112 public:
113 static UserGestureForTests* GetInstance();
115 // Returns true if there is at least one ScopedUserGestureForTests object
116 // alive.
117 bool HaveGesture();
119 // These should be called when a ScopedUserGestureForTests object is
120 // created/destroyed respectively.
121 void IncrementCount();
122 void DecrementCount();
124 private:
125 UserGestureForTests();
126 friend struct DefaultSingletonTraits<UserGestureForTests>;
128 base::Lock lock_; // for protecting access to count_
129 int count_;
132 // static
133 UserGestureForTests* UserGestureForTests::GetInstance() {
134 return Singleton<UserGestureForTests>::get();
137 UserGestureForTests::UserGestureForTests() : count_(0) {}
139 bool UserGestureForTests::HaveGesture() {
140 base::AutoLock autolock(lock_);
141 return count_ > 0;
144 void UserGestureForTests::IncrementCount() {
145 base::AutoLock autolock(lock_);
146 ++count_;
149 void UserGestureForTests::DecrementCount() {
150 base::AutoLock autolock(lock_);
151 --count_;
155 } // namespace
157 // static
158 void ExtensionFunctionDeleteTraits::Destruct(const ExtensionFunction* x) {
159 x->Destruct();
162 // Helper class to track the lifetime of ExtensionFunction's RenderViewHost or
163 // RenderFrameHost pointer and NULL it out when it dies. It also allows us to
164 // filter IPC messages coming from the RenderViewHost/RenderFrameHost.
165 class UIThreadExtensionFunction::RenderHostTracker
166 : public content::WebContentsObserver {
167 public:
168 explicit RenderHostTracker(UIThreadExtensionFunction* function)
169 : content::WebContentsObserver(
170 function->render_view_host() ?
171 WebContents::FromRenderViewHost(function->render_view_host()) :
172 WebContents::FromRenderFrameHost(
173 function->render_frame_host())),
174 function_(function) {
177 private:
178 // content::WebContentsObserver:
179 void RenderViewDeleted(content::RenderViewHost* render_view_host) override {
180 if (render_view_host != function_->render_view_host())
181 return;
183 function_->SetRenderViewHost(NULL);
185 void RenderFrameDeleted(
186 content::RenderFrameHost* render_frame_host) override {
187 if (render_frame_host != function_->render_frame_host())
188 return;
190 function_->SetRenderFrameHost(NULL);
193 bool OnMessageReceived(const IPC::Message& message,
194 content::RenderFrameHost* render_frame_host) override {
195 DCHECK(render_frame_host);
196 if (render_frame_host == function_->render_frame_host())
197 return function_->OnMessageReceived(message);
198 else
199 return false;
202 bool OnMessageReceived(const IPC::Message& message) override {
203 return function_->OnMessageReceived(message);
206 UIThreadExtensionFunction* function_;
208 DISALLOW_COPY_AND_ASSIGN(RenderHostTracker);
211 ExtensionFunction::ExtensionFunction()
212 : request_id_(-1),
213 profile_id_(NULL),
214 has_callback_(false),
215 include_incognito_(false),
216 user_gesture_(false),
217 bad_message_(false),
218 histogram_value_(extensions::functions::UNKNOWN),
219 source_tab_id_(-1),
220 source_context_type_(Feature::UNSPECIFIED_CONTEXT) {
223 ExtensionFunction::~ExtensionFunction() {
226 UIThreadExtensionFunction* ExtensionFunction::AsUIThreadExtensionFunction() {
227 return NULL;
230 IOThreadExtensionFunction* ExtensionFunction::AsIOThreadExtensionFunction() {
231 return NULL;
234 bool ExtensionFunction::HasPermission() {
235 Feature::Availability availability =
236 ExtensionAPI::GetSharedInstance()->IsAvailable(
237 name_, extension_.get(), source_context_type_, source_url());
238 return availability.is_available();
241 void ExtensionFunction::OnQuotaExceeded(const std::string& violation_error) {
242 error_ = violation_error;
243 SendResponse(false);
246 void ExtensionFunction::SetArgs(const base::ListValue* args) {
247 DCHECK(!args_.get()); // Should only be called once.
248 args_.reset(args->DeepCopy());
251 void ExtensionFunction::SetResult(base::Value* result) {
252 results_.reset(new base::ListValue());
253 results_->Append(result);
256 void ExtensionFunction::SetResultList(scoped_ptr<base::ListValue> results) {
257 results_ = results.Pass();
260 const base::ListValue* ExtensionFunction::GetResultList() const {
261 return results_.get();
264 std::string ExtensionFunction::GetError() const {
265 return error_;
268 void ExtensionFunction::SetError(const std::string& error) {
269 error_ = error;
272 bool ExtensionFunction::user_gesture() const {
273 return user_gesture_ || UserGestureForTests::GetInstance()->HaveGesture();
276 ExtensionFunction::ResponseValue ExtensionFunction::NoArguments() {
277 return ResponseValue(new ArgumentListResponseValue(
278 name(), "NoArguments", this, make_scoped_ptr(new base::ListValue())));
281 ExtensionFunction::ResponseValue ExtensionFunction::OneArgument(
282 base::Value* arg) {
283 scoped_ptr<base::ListValue> args(new base::ListValue());
284 args->Append(arg);
285 return ResponseValue(
286 new ArgumentListResponseValue(name(), "OneArgument", this, args.Pass()));
289 ExtensionFunction::ResponseValue ExtensionFunction::TwoArguments(
290 base::Value* arg1,
291 base::Value* arg2) {
292 scoped_ptr<base::ListValue> args(new base::ListValue());
293 args->Append(arg1);
294 args->Append(arg2);
295 return ResponseValue(
296 new ArgumentListResponseValue(name(), "TwoArguments", this, args.Pass()));
299 ExtensionFunction::ResponseValue ExtensionFunction::ArgumentList(
300 scoped_ptr<base::ListValue> args) {
301 return ResponseValue(
302 new ArgumentListResponseValue(name(), "ArgumentList", this, args.Pass()));
305 ExtensionFunction::ResponseValue ExtensionFunction::Error(
306 const std::string& error) {
307 return ResponseValue(new ErrorResponseValue(this, error));
310 ExtensionFunction::ResponseValue ExtensionFunction::Error(
311 const std::string& format,
312 const std::string& s1) {
313 return ResponseValue(
314 new ErrorResponseValue(this, ErrorUtils::FormatErrorMessage(format, s1)));
317 ExtensionFunction::ResponseValue ExtensionFunction::Error(
318 const std::string& format,
319 const std::string& s1,
320 const std::string& s2) {
321 return ResponseValue(new ErrorResponseValue(
322 this, ErrorUtils::FormatErrorMessage(format, s1, s2)));
325 ExtensionFunction::ResponseValue ExtensionFunction::Error(
326 const std::string& format,
327 const std::string& s1,
328 const std::string& s2,
329 const std::string& s3) {
330 return ResponseValue(new ErrorResponseValue(
331 this, ErrorUtils::FormatErrorMessage(format, s1, s2, s3)));
334 ExtensionFunction::ResponseValue ExtensionFunction::BadMessage() {
335 return ResponseValue(new BadMessageResponseValue(this));
338 ExtensionFunction::ResponseAction ExtensionFunction::RespondNow(
339 ResponseValue result) {
340 return ResponseAction(new RespondNowAction(
341 result.Pass(), base::Bind(&ExtensionFunction::SendResponse, this)));
344 ExtensionFunction::ResponseAction ExtensionFunction::RespondLater() {
345 return ResponseAction(new RespondLaterAction());
348 // static
349 ExtensionFunction::ResponseAction ExtensionFunction::ValidationFailure(
350 ExtensionFunction* function) {
351 return function->RespondNow(function->BadMessage());
354 void ExtensionFunction::Respond(ResponseValue result) {
355 SendResponse(result->Apply());
358 bool ExtensionFunction::ShouldSkipQuotaLimiting() const {
359 return false;
362 bool ExtensionFunction::HasOptionalArgument(size_t index) {
363 base::Value* value;
364 return args_->Get(index, &value) && !value->IsType(base::Value::TYPE_NULL);
367 void ExtensionFunction::SendResponseImpl(bool success) {
368 DCHECK(!response_callback_.is_null());
370 ResponseType type = success ? SUCCEEDED : FAILED;
371 if (bad_message_) {
372 type = BAD_MESSAGE;
373 LOG(ERROR) << "Bad extension message " << name_;
376 // If results were never set, we send an empty argument list.
377 if (!results_)
378 results_.reset(new base::ListValue());
380 response_callback_.Run(type, *results_, GetError());
383 void ExtensionFunction::OnRespondingLater(ResponseValue value) {
384 SendResponse(value->Apply());
387 UIThreadExtensionFunction::UIThreadExtensionFunction()
388 : render_view_host_(NULL),
389 render_frame_host_(NULL),
390 context_(NULL),
391 delegate_(NULL) {
394 UIThreadExtensionFunction::~UIThreadExtensionFunction() {
395 if (dispatcher() && render_view_host())
396 dispatcher()->OnExtensionFunctionCompleted(extension());
399 UIThreadExtensionFunction*
400 UIThreadExtensionFunction::AsUIThreadExtensionFunction() {
401 return this;
404 bool UIThreadExtensionFunction::OnMessageReceived(const IPC::Message& message) {
405 return false;
408 void UIThreadExtensionFunction::Destruct() const {
409 BrowserThread::DeleteOnUIThread::Destruct(this);
412 void UIThreadExtensionFunction::SetRenderViewHost(
413 RenderViewHost* render_view_host) {
414 DCHECK(!render_frame_host_);
415 render_view_host_ = render_view_host;
416 tracker_.reset(render_view_host ? new RenderHostTracker(this) : NULL);
419 void UIThreadExtensionFunction::SetRenderFrameHost(
420 content::RenderFrameHost* render_frame_host) {
421 DCHECK(!render_view_host_);
422 render_frame_host_ = render_frame_host;
423 tracker_.reset(render_frame_host ? new RenderHostTracker(this) : NULL);
426 content::WebContents* UIThreadExtensionFunction::GetAssociatedWebContents() {
427 content::WebContents* web_contents = NULL;
428 if (dispatcher())
429 web_contents = dispatcher()->delegate()->GetAssociatedWebContents();
431 return web_contents;
434 void UIThreadExtensionFunction::SendResponse(bool success) {
435 if (delegate_)
436 delegate_->OnSendResponse(this, success, bad_message_);
437 else
438 SendResponseImpl(success);
440 if (!transferred_blob_uuids_.empty()) {
441 DCHECK(!delegate_) << "Blob transfer not supported with test delegate.";
442 GetIPCSender()->Send(
443 new ExtensionMsg_TransferBlobs(transferred_blob_uuids_));
447 void UIThreadExtensionFunction::SetTransferredBlobUUIDs(
448 const std::vector<std::string>& blob_uuids) {
449 DCHECK(transferred_blob_uuids_.empty()); // Should only be called once.
450 transferred_blob_uuids_ = blob_uuids;
453 void UIThreadExtensionFunction::WriteToConsole(
454 content::ConsoleMessageLevel level,
455 const std::string& message) {
456 GetIPCSender()->Send(
457 new ExtensionMsg_AddMessageToConsole(GetRoutingID(), level, message));
460 IPC::Sender* UIThreadExtensionFunction::GetIPCSender() {
461 if (render_view_host_)
462 return render_view_host_;
463 else
464 return render_frame_host_;
467 int UIThreadExtensionFunction::GetRoutingID() {
468 if (render_view_host_)
469 return render_view_host_->GetRoutingID();
470 else
471 return render_frame_host_->GetRoutingID();
474 IOThreadExtensionFunction::IOThreadExtensionFunction()
475 : routing_id_(MSG_ROUTING_NONE) {
478 IOThreadExtensionFunction::~IOThreadExtensionFunction() {
481 IOThreadExtensionFunction*
482 IOThreadExtensionFunction::AsIOThreadExtensionFunction() {
483 return this;
486 void IOThreadExtensionFunction::Destruct() const {
487 BrowserThread::DeleteOnIOThread::Destruct(this);
490 void IOThreadExtensionFunction::SendResponse(bool success) {
491 SendResponseImpl(success);
494 AsyncExtensionFunction::AsyncExtensionFunction() {
497 AsyncExtensionFunction::~AsyncExtensionFunction() {
500 ExtensionFunction::ScopedUserGestureForTests::ScopedUserGestureForTests() {
501 UserGestureForTests::GetInstance()->IncrementCount();
504 ExtensionFunction::ScopedUserGestureForTests::~ScopedUserGestureForTests() {
505 UserGestureForTests::GetInstance()->DecrementCount();
508 ExtensionFunction::ResponseAction AsyncExtensionFunction::Run() {
509 return RunAsync() ? RespondLater() : RespondNow(Error(error_));
512 // static
513 bool AsyncExtensionFunction::ValidationFailure(
514 AsyncExtensionFunction* function) {
515 return false;
518 SyncExtensionFunction::SyncExtensionFunction() {
521 SyncExtensionFunction::~SyncExtensionFunction() {
524 ExtensionFunction::ResponseAction SyncExtensionFunction::Run() {
525 return RespondNow(RunSync() ? ArgumentList(results_.Pass()) : Error(error_));
528 // static
529 bool SyncExtensionFunction::ValidationFailure(SyncExtensionFunction* function) {
530 return false;
533 SyncIOThreadExtensionFunction::SyncIOThreadExtensionFunction() {
536 SyncIOThreadExtensionFunction::~SyncIOThreadExtensionFunction() {
539 ExtensionFunction::ResponseAction SyncIOThreadExtensionFunction::Run() {
540 return RespondNow(RunSync() ? ArgumentList(results_.Pass()) : Error(error_));
543 // static
544 bool SyncIOThreadExtensionFunction::ValidationFailure(
545 SyncIOThreadExtensionFunction* function) {
546 return false;