Add ICU message format support
[chromium-blink-merge.git] / extensions / browser / extension_function.cc
blobf9a7d3f0e59c2440e08642e2d775a9849e5bf55d
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/web_contents.h"
14 #include "content/public/browser/web_contents_observer.h"
15 #include "extensions/browser/extension_function_dispatcher.h"
16 #include "extensions/browser/extension_message_filter.h"
17 #include "extensions/common/error_utils.h"
18 #include "extensions/common/extension_api.h"
19 #include "extensions/common/extension_messages.h"
21 using content::BrowserThread;
22 using content::RenderViewHost;
23 using content::WebContents;
24 using extensions::ErrorUtils;
25 using extensions::ExtensionAPI;
26 using extensions::Feature;
28 namespace {
30 class ArgumentListResponseValue
31 : public ExtensionFunction::ResponseValueObject {
32 public:
33 ArgumentListResponseValue(const std::string& function_name,
34 const char* title,
35 ExtensionFunction* function,
36 scoped_ptr<base::ListValue> result)
37 : function_name_(function_name), title_(title) {
38 if (function->GetResultList()) {
39 DCHECK_EQ(function->GetResultList(), result.get())
40 << "The result set on this function (" << function_name_ << ") "
41 << "either by calling SetResult() or directly modifying |result_| is "
42 << "different to the one passed to " << title_ << "(). "
43 << "The best way to fix this problem is to exclusively use " << title_
44 << "(). SetResult() and |result_| are deprecated.";
45 } else {
46 function->SetResultList(result.Pass());
48 // It would be nice to DCHECK(error.empty()) but some legacy extension
49 // function implementations... I'm looking at chrome.input.ime... do this
50 // for some reason.
53 ~ArgumentListResponseValue() override {}
55 bool Apply() override { return true; }
57 private:
58 std::string function_name_;
59 const char* title_;
62 class ErrorWithArgumentsResponseValue : public ArgumentListResponseValue {
63 public:
64 ErrorWithArgumentsResponseValue(const std::string& function_name,
65 const char* title,
66 ExtensionFunction* function,
67 scoped_ptr<base::ListValue> result,
68 const std::string& error)
69 : ArgumentListResponseValue(function_name,
70 title,
71 function,
72 result.Pass()) {
73 function->SetError(error);
76 ~ErrorWithArgumentsResponseValue() override {}
78 bool Apply() override { return false; }
81 class ErrorResponseValue : public ExtensionFunction::ResponseValueObject {
82 public:
83 ErrorResponseValue(ExtensionFunction* function, const std::string& error) {
84 // It would be nice to DCHECK(!error.empty()) but too many legacy extension
85 // function implementations don't set error but signal failure.
86 function->SetError(error);
89 ~ErrorResponseValue() override {}
91 bool Apply() override { return false; }
94 class BadMessageResponseValue : public ExtensionFunction::ResponseValueObject {
95 public:
96 explicit BadMessageResponseValue(ExtensionFunction* function) {
97 function->set_bad_message(true);
98 NOTREACHED() << function->name() << ": bad message";
101 ~BadMessageResponseValue() override {}
103 bool Apply() override { return false; }
106 class RespondNowAction : public ExtensionFunction::ResponseActionObject {
107 public:
108 typedef base::Callback<void(bool)> SendResponseCallback;
109 RespondNowAction(ExtensionFunction::ResponseValue result,
110 const SendResponseCallback& send_response)
111 : result_(result.Pass()), send_response_(send_response) {}
112 ~RespondNowAction() override {}
114 void Execute() override { send_response_.Run(result_->Apply()); }
116 private:
117 ExtensionFunction::ResponseValue result_;
118 SendResponseCallback send_response_;
121 class RespondLaterAction : public ExtensionFunction::ResponseActionObject {
122 public:
123 ~RespondLaterAction() override {}
125 void Execute() override {}
128 // Used in implementation of ScopedUserGestureForTests.
129 class UserGestureForTests {
130 public:
131 static UserGestureForTests* GetInstance();
133 // Returns true if there is at least one ScopedUserGestureForTests object
134 // alive.
135 bool HaveGesture();
137 // These should be called when a ScopedUserGestureForTests object is
138 // created/destroyed respectively.
139 void IncrementCount();
140 void DecrementCount();
142 private:
143 UserGestureForTests();
144 friend struct DefaultSingletonTraits<UserGestureForTests>;
146 base::Lock lock_; // for protecting access to count_
147 int count_;
150 // static
151 UserGestureForTests* UserGestureForTests::GetInstance() {
152 return Singleton<UserGestureForTests>::get();
155 UserGestureForTests::UserGestureForTests() : count_(0) {}
157 bool UserGestureForTests::HaveGesture() {
158 base::AutoLock autolock(lock_);
159 return count_ > 0;
162 void UserGestureForTests::IncrementCount() {
163 base::AutoLock autolock(lock_);
164 ++count_;
167 void UserGestureForTests::DecrementCount() {
168 base::AutoLock autolock(lock_);
169 --count_;
173 } // namespace
175 // static
176 void ExtensionFunctionDeleteTraits::Destruct(const ExtensionFunction* x) {
177 x->Destruct();
180 // Helper class to track the lifetime of ExtensionFunction's RenderFrameHost and
181 // notify the function when it is deleted, as well as forwarding any messages
182 // to the ExtensionFunction.
183 class UIThreadExtensionFunction::RenderFrameHostTracker
184 : public content::WebContentsObserver {
185 public:
186 explicit RenderFrameHostTracker(UIThreadExtensionFunction* function)
187 : content::WebContentsObserver(
188 WebContents::FromRenderFrameHost(function->render_frame_host())),
189 function_(function) {
192 private:
193 // content::WebContentsObserver:
194 void RenderFrameDeleted(
195 content::RenderFrameHost* render_frame_host) override {
196 if (render_frame_host == function_->render_frame_host())
197 function_->SetRenderFrameHost(nullptr);
200 bool OnMessageReceived(const IPC::Message& message,
201 content::RenderFrameHost* render_frame_host) override {
202 return render_frame_host == function_->render_frame_host() &&
203 function_->OnMessageReceived(message);
206 bool OnMessageReceived(const IPC::Message& message) override {
207 return function_->OnMessageReceived(message);
210 UIThreadExtensionFunction* function_; // Owns us.
212 DISALLOW_COPY_AND_ASSIGN(RenderFrameHostTracker);
215 ExtensionFunction::ExtensionFunction()
216 : request_id_(-1),
217 profile_id_(NULL),
218 name_(""),
219 has_callback_(false),
220 include_incognito_(false),
221 user_gesture_(false),
222 bad_message_(false),
223 histogram_value_(extensions::functions::UNKNOWN),
224 source_tab_id_(-1),
225 source_context_type_(Feature::UNSPECIFIED_CONTEXT),
226 source_process_id_(-1) {
229 ExtensionFunction::~ExtensionFunction() {
232 UIThreadExtensionFunction* ExtensionFunction::AsUIThreadExtensionFunction() {
233 return NULL;
236 IOThreadExtensionFunction* ExtensionFunction::AsIOThreadExtensionFunction() {
237 return NULL;
240 bool ExtensionFunction::HasPermission() {
241 Feature::Availability availability =
242 ExtensionAPI::GetSharedInstance()->IsAvailable(
243 name_, extension_.get(), source_context_type_, source_url());
244 return availability.is_available();
247 void ExtensionFunction::OnQuotaExceeded(const std::string& violation_error) {
248 error_ = violation_error;
249 SendResponse(false);
252 void ExtensionFunction::SetArgs(const base::ListValue* args) {
253 DCHECK(!args_.get()); // Should only be called once.
254 args_.reset(args->DeepCopy());
257 void ExtensionFunction::SetResult(base::Value* result) {
258 results_.reset(new base::ListValue());
259 results_->Append(result);
262 void ExtensionFunction::SetResult(scoped_ptr<base::Value> result) {
263 results_.reset(new base::ListValue());
264 results_->Append(result.Pass());
267 void ExtensionFunction::SetResultList(scoped_ptr<base::ListValue> results) {
268 results_ = results.Pass();
271 const base::ListValue* ExtensionFunction::GetResultList() const {
272 return results_.get();
275 std::string ExtensionFunction::GetError() const {
276 return error_;
279 void ExtensionFunction::SetError(const std::string& error) {
280 error_ = error;
283 bool ExtensionFunction::user_gesture() const {
284 return user_gesture_ || UserGestureForTests::GetInstance()->HaveGesture();
287 ExtensionFunction::ResponseValue ExtensionFunction::NoArguments() {
288 return ResponseValue(new ArgumentListResponseValue(
289 name(), "NoArguments", this, make_scoped_ptr(new base::ListValue())));
292 ExtensionFunction::ResponseValue ExtensionFunction::OneArgument(
293 base::Value* arg) {
294 scoped_ptr<base::ListValue> args(new base::ListValue());
295 args->Append(arg);
296 return ResponseValue(
297 new ArgumentListResponseValue(name(), "OneArgument", this, args.Pass()));
300 ExtensionFunction::ResponseValue ExtensionFunction::OneArgument(
301 scoped_ptr<base::Value> arg) {
302 return OneArgument(arg.release());
305 ExtensionFunction::ResponseValue ExtensionFunction::TwoArguments(
306 base::Value* arg1,
307 base::Value* arg2) {
308 scoped_ptr<base::ListValue> args(new base::ListValue());
309 args->Append(arg1);
310 args->Append(arg2);
311 return ResponseValue(
312 new ArgumentListResponseValue(name(), "TwoArguments", this, args.Pass()));
315 ExtensionFunction::ResponseValue ExtensionFunction::ArgumentList(
316 scoped_ptr<base::ListValue> args) {
317 return ResponseValue(
318 new ArgumentListResponseValue(name(), "ArgumentList", this, args.Pass()));
321 ExtensionFunction::ResponseValue ExtensionFunction::Error(
322 const std::string& error) {
323 return ResponseValue(new ErrorResponseValue(this, error));
326 ExtensionFunction::ResponseValue ExtensionFunction::Error(
327 const std::string& format,
328 const std::string& s1) {
329 return ResponseValue(
330 new ErrorResponseValue(this, ErrorUtils::FormatErrorMessage(format, s1)));
333 ExtensionFunction::ResponseValue ExtensionFunction::Error(
334 const std::string& format,
335 const std::string& s1,
336 const std::string& s2) {
337 return ResponseValue(new ErrorResponseValue(
338 this, ErrorUtils::FormatErrorMessage(format, s1, s2)));
341 ExtensionFunction::ResponseValue ExtensionFunction::Error(
342 const std::string& format,
343 const std::string& s1,
344 const std::string& s2,
345 const std::string& s3) {
346 return ResponseValue(new ErrorResponseValue(
347 this, ErrorUtils::FormatErrorMessage(format, s1, s2, s3)));
350 ExtensionFunction::ResponseValue ExtensionFunction::ErrorWithArguments(
351 scoped_ptr<base::ListValue> args,
352 const std::string& error) {
353 return ResponseValue(new ErrorWithArgumentsResponseValue(
354 name(), "ErrorWithArguments", this, args.Pass(), error));
357 ExtensionFunction::ResponseValue ExtensionFunction::BadMessage() {
358 return ResponseValue(new BadMessageResponseValue(this));
361 ExtensionFunction::ResponseAction ExtensionFunction::RespondNow(
362 ResponseValue result) {
363 return ResponseAction(new RespondNowAction(
364 result.Pass(), base::Bind(&ExtensionFunction::SendResponse, this)));
367 ExtensionFunction::ResponseAction ExtensionFunction::RespondLater() {
368 return ResponseAction(new RespondLaterAction());
371 // static
372 ExtensionFunction::ResponseAction ExtensionFunction::ValidationFailure(
373 ExtensionFunction* function) {
374 return function->RespondNow(function->BadMessage());
377 void ExtensionFunction::Respond(ResponseValue result) {
378 SendResponse(result->Apply());
381 bool ExtensionFunction::ShouldSkipQuotaLimiting() const {
382 return false;
385 bool ExtensionFunction::HasOptionalArgument(size_t index) {
386 base::Value* value;
387 return args_->Get(index, &value) && !value->IsType(base::Value::TYPE_NULL);
390 void ExtensionFunction::SendResponseImpl(bool success) {
391 DCHECK(!response_callback_.is_null());
393 ResponseType type = success ? SUCCEEDED : FAILED;
394 if (bad_message_) {
395 type = BAD_MESSAGE;
396 LOG(ERROR) << "Bad extension message " << name_;
399 // If results were never set, we send an empty argument list.
400 if (!results_)
401 results_.reset(new base::ListValue());
403 response_callback_.Run(type, *results_, GetError(), histogram_value());
406 void ExtensionFunction::OnRespondingLater(ResponseValue value) {
407 SendResponse(value->Apply());
410 UIThreadExtensionFunction::UIThreadExtensionFunction()
411 : context_(nullptr),
412 render_frame_host_(nullptr),
413 delegate_(nullptr) {
416 UIThreadExtensionFunction::~UIThreadExtensionFunction() {
417 if (dispatcher() && render_frame_host())
418 dispatcher()->OnExtensionFunctionCompleted(extension());
421 UIThreadExtensionFunction*
422 UIThreadExtensionFunction::AsUIThreadExtensionFunction() {
423 return this;
426 bool UIThreadExtensionFunction::OnMessageReceived(const IPC::Message& message) {
427 return false;
430 void UIThreadExtensionFunction::Destruct() const {
431 BrowserThread::DeleteOnUIThread::Destruct(this);
434 content::RenderViewHost*
435 UIThreadExtensionFunction::render_view_host_do_not_use() const {
436 return render_frame_host_ ? render_frame_host_->GetRenderViewHost() : nullptr;
439 void UIThreadExtensionFunction::SetRenderFrameHost(
440 content::RenderFrameHost* render_frame_host) {
441 DCHECK_NE(render_frame_host_ == nullptr, render_frame_host == nullptr);
442 render_frame_host_ = render_frame_host;
443 tracker_.reset(
444 render_frame_host ? new RenderFrameHostTracker(this) : nullptr);
447 content::WebContents* UIThreadExtensionFunction::GetAssociatedWebContents() {
448 content::WebContents* web_contents = NULL;
449 if (dispatcher())
450 web_contents = dispatcher()->GetAssociatedWebContents();
452 return web_contents;
455 content::WebContents* UIThreadExtensionFunction::GetSenderWebContents() {
456 return render_frame_host_ ?
457 content::WebContents::FromRenderFrameHost(render_frame_host_) : nullptr;
460 void UIThreadExtensionFunction::SendResponse(bool success) {
461 if (delegate_)
462 delegate_->OnSendResponse(this, success, bad_message_);
463 else
464 SendResponseImpl(success);
466 if (!transferred_blob_uuids_.empty()) {
467 DCHECK(!delegate_) << "Blob transfer not supported with test delegate.";
468 render_frame_host_->Send(
469 new ExtensionMsg_TransferBlobs(transferred_blob_uuids_));
473 void UIThreadExtensionFunction::SetTransferredBlobUUIDs(
474 const std::vector<std::string>& blob_uuids) {
475 DCHECK(transferred_blob_uuids_.empty()); // Should only be called once.
476 transferred_blob_uuids_ = blob_uuids;
479 void UIThreadExtensionFunction::WriteToConsole(
480 content::ConsoleMessageLevel level,
481 const std::string& message) {
482 // Only the main frame handles dev tools messages.
483 WebContents::FromRenderFrameHost(render_frame_host_)
484 ->GetMainFrame()
485 ->AddMessageToConsole(level, message);
488 IOThreadExtensionFunction::IOThreadExtensionFunction()
489 : routing_id_(MSG_ROUTING_NONE) {
492 IOThreadExtensionFunction::~IOThreadExtensionFunction() {
495 IOThreadExtensionFunction*
496 IOThreadExtensionFunction::AsIOThreadExtensionFunction() {
497 return this;
500 void IOThreadExtensionFunction::Destruct() const {
501 BrowserThread::DeleteOnIOThread::Destruct(this);
504 void IOThreadExtensionFunction::SendResponse(bool success) {
505 SendResponseImpl(success);
508 AsyncExtensionFunction::AsyncExtensionFunction() {
511 AsyncExtensionFunction::~AsyncExtensionFunction() {
514 ExtensionFunction::ScopedUserGestureForTests::ScopedUserGestureForTests() {
515 UserGestureForTests::GetInstance()->IncrementCount();
518 ExtensionFunction::ScopedUserGestureForTests::~ScopedUserGestureForTests() {
519 UserGestureForTests::GetInstance()->DecrementCount();
522 ExtensionFunction::ResponseAction AsyncExtensionFunction::Run() {
523 return RunAsync() ? RespondLater() : RespondNow(Error(error_));
526 // static
527 bool AsyncExtensionFunction::ValidationFailure(
528 AsyncExtensionFunction* function) {
529 return false;
532 SyncExtensionFunction::SyncExtensionFunction() {
535 SyncExtensionFunction::~SyncExtensionFunction() {
538 ExtensionFunction::ResponseAction SyncExtensionFunction::Run() {
539 return RespondNow(RunSync() ? ArgumentList(results_.Pass()) : Error(error_));
542 // static
543 bool SyncExtensionFunction::ValidationFailure(SyncExtensionFunction* function) {
544 return false;
547 SyncIOThreadExtensionFunction::SyncIOThreadExtensionFunction() {
550 SyncIOThreadExtensionFunction::~SyncIOThreadExtensionFunction() {
553 ExtensionFunction::ResponseAction SyncIOThreadExtensionFunction::Run() {
554 return RespondNow(RunSync() ? ArgumentList(results_.Pass()) : Error(error_));
557 // static
558 bool SyncIOThreadExtensionFunction::ValidationFailure(
559 SyncIOThreadExtensionFunction* function) {
560 return false;