1// Copyright (c) 2010 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.
4
5#include "chrome/browser/extensions/extension_function.h"
6
7#include "base/json/json_writer.h"
8#include "base/logging.h"
9#include "chrome/browser/extensions/extension_function_dispatcher.h"
10#include "chrome/browser/extensions/extension_service.h"
11#include "chrome/browser/profiles/profile.h"
12
13ExtensionFunction::ExtensionFunction()
14    : request_id_(-1),
15      profile_(NULL),
16      has_callback_(false),
17      include_incognito_(false),
18      user_gesture_(false) {
19}
20
21ExtensionFunction::~ExtensionFunction() {
22}
23
24const Extension* ExtensionFunction::GetExtension() {
25  ExtensionService* service = profile_->GetExtensionService();
26  DCHECK(service);
27  return service->GetExtensionById(extension_id_, false);
28}
29
30Browser* ExtensionFunction::GetCurrentBrowser() {
31  return dispatcher()->GetCurrentBrowser(include_incognito_);
32}
33
34AsyncExtensionFunction::AsyncExtensionFunction()
35    : args_(NULL), bad_message_(false) {
36}
37
38AsyncExtensionFunction::~AsyncExtensionFunction() {
39}
40
41void AsyncExtensionFunction::SetArgs(const ListValue* args) {
42  DCHECK(!args_.get());  // Should only be called once.
43  args_.reset(args->DeepCopy());
44}
45
46const std::string AsyncExtensionFunction::GetResult() {
47  std::string json;
48  // Some functions might not need to return any results.
49  if (result_.get())
50    base::JSONWriter::Write(result_.get(), false, &json);
51  return json;
52}
53
54const std::string AsyncExtensionFunction::GetError() {
55  return error_;
56}
57
58void AsyncExtensionFunction::Run() {
59  if (!RunImpl())
60    SendResponse(false);
61}
62
63void AsyncExtensionFunction::SendResponse(bool success) {
64  if (!dispatcher())
65    return;
66  if (bad_message_) {
67    dispatcher()->HandleBadMessage(this);
68  } else {
69    dispatcher()->SendResponse(this, success);
70  }
71}
72
73bool AsyncExtensionFunction::HasOptionalArgument(size_t index) {
74  Value* value;
75  return args_->Get(index, &value) && !value->IsType(Value::TYPE_NULL);
76}
77
78SyncExtensionFunction::SyncExtensionFunction() {
79}
80
81SyncExtensionFunction::~SyncExtensionFunction() {
82}
83
84void SyncExtensionFunction::Run() {
85  SendResponse(RunImpl());
86}
87