- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / webui / extensions / extension_error_handler.cc
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.
4
5 #include "chrome/browser/ui/webui/extensions/extension_error_handler.h"
6
7 #include "base/bind.h"
8 #include "base/file_util.h"
9 #include "base/files/file_path.h"
10 #include "base/location.h"
11 #include "base/strings/string16.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/values.h"
14 #include "chrome/browser/devtools/devtools_window.h"
15 #include "chrome/browser/extensions/extension_service.h"
16 #include "chrome/browser/extensions/extension_system.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "chrome/browser/ui/browser.h"
19 #include "chrome/browser/ui/browser_finder.h"
20 #include "chrome/browser/ui/tabs/tab_strip_model.h"
21 #include "chrome/common/extensions/extension.h"
22 #include "content/public/browser/browser_thread.h"
23 #include "content/public/browser/render_view_host.h"
24 #include "content/public/browser/web_contents.h"
25 #include "content/public/browser/web_ui.h"
26 #include "content/public/browser/web_ui_data_source.h"
27 #include "extensions/browser/extension_error.h"
28 #include "extensions/browser/file_highlighter.h"
29 #include "extensions/common/constants.h"
30 #include "grit/generated_resources.h"
31 #include "ui/base/l10n/l10n_util.h"
32
33 namespace extensions {
34
35 // Keys for objects passed to and from extension error UI.
36 const char kPathSuffixKey[] = "pathSuffix";
37 const char kTitleKey[] = "title";
38
39 ExtensionErrorHandler::ExtensionErrorHandler(Profile* profile)
40     : profile_(profile) {
41 }
42
43 ExtensionErrorHandler::~ExtensionErrorHandler() {
44 }
45
46 void ExtensionErrorHandler::GetLocalizedValues(
47     content::WebUIDataSource* source) {
48   source->AddString(
49       "extensionErrorsManifestErrors",
50       l10n_util::GetStringUTF16(IDS_EXTENSIONS_ERRORS_MANIFEST_ERRORS));
51   source->AddString(
52       "extensionErrorsRuntimeErrors",
53       l10n_util::GetStringUTF16(IDS_EXTENSIONS_ERRORS_RUNTIME_ERRORS));
54   source->AddString(
55       "extensionErrorsShowMore",
56       l10n_util::GetStringUTF16(IDS_EXTENSIONS_ERRORS_SHOW_MORE));
57   source->AddString(
58       "extensionErrorsShowFewer",
59       l10n_util::GetStringUTF16(IDS_EXTENSIONS_ERRORS_SHOW_FEWER));
60   source->AddString(
61       "extensionErrorViewSource",
62       l10n_util::GetStringUTF16(IDS_EXTENSIONS_ERROR_VIEW_SOURCE));
63   source->AddString(
64       "extensionErrorInspect",
65       l10n_util::GetStringUTF16(IDS_EXTENSIONS_ERROR_INSPECT));
66   source->AddString(
67       "extensionErrorContext",
68       l10n_util::GetStringUTF16(IDS_EXTENSIONS_ERROR_CONTEXT));
69   source->AddString(
70       "extensionErrorStackTrace",
71       l10n_util::GetStringUTF16(IDS_EXTENSIONS_ERROR_STACK_TRACE));
72   source->AddString(
73       "extensionErrorAnonymousFunction",
74       l10n_util::GetStringUTF16(IDS_EXTENSIONS_ERROR_ANONYMOUS_FUNCTION));
75 }
76
77 void ExtensionErrorHandler::RegisterMessages() {
78   web_ui()->RegisterMessageCallback(
79       "extensionErrorRequestFileSource",
80       base::Bind(&ExtensionErrorHandler::HandleRequestFileSource,
81                  base::Unretained(this)));
82   web_ui()->RegisterMessageCallback(
83       "extensionErrorOpenDevTools",
84       base::Bind(&ExtensionErrorHandler::HandleOpenDevTools,
85                  base::Unretained(this)));
86 }
87
88 void ExtensionErrorHandler::HandleRequestFileSource(
89     const base::ListValue* args) {
90   // There should only be one argument, a dictionary. Use this instead of a list
91   // because it's more descriptive, harder to accidentally break with minor
92   // modifications, and supports optional arguments more easily.
93   CHECK_EQ(1u, args->GetSize());
94
95   const base::DictionaryValue* dict = NULL;
96
97   // Three required arguments: extension_id, path_suffix, and error_message.
98   std::string extension_id;
99   base::FilePath::StringType path_suffix_string;
100   base::string16 error_message;
101
102   if (!args->GetDictionary(0, &dict) ||
103       !dict->GetString(kPathSuffixKey, &path_suffix_string) ||
104       !dict->GetString(ExtensionError::kExtensionIdKey, &extension_id) ||
105       !dict->GetString(ExtensionError::kMessageKey, &error_message)) {
106     NOTREACHED();
107     return;
108   }
109
110   const Extension* extension =
111       ExtensionSystem::Get(Profile::FromWebUI(web_ui()))->
112           extension_service()->GetExtensionById(extension_id,
113                                                 true /* include disabled */ );
114
115   // Under no circumstances should we ever need to reference a file outside of
116   // the extension's directory. If it tries to, abort.
117   base::FilePath path_suffix(path_suffix_string);
118   if (path_suffix.ReferencesParent())
119     return;
120
121   base::FilePath path = extension->path().Append(path_suffix);
122
123   // Setting the title and the error message is the same for all file types.
124   scoped_ptr<base::DictionaryValue> results(new base::DictionaryValue);
125   results->SetString(kTitleKey,
126                      base::UTF8ToUTF16(extension->name()) +
127                          base::ASCIIToUTF16(": ") +
128                          path.BaseName().LossyDisplayName());
129   results->SetString(ExtensionError::kMessageKey, error_message);
130
131   base::Closure closure;
132   std::string* contents = NULL;
133
134   if (path_suffix_string == kManifestFilename) {
135     std::string manifest_key;
136     if (!dict->GetString(ManifestError::kManifestKeyKey, &manifest_key)) {
137       NOTREACHED();
138       return;
139     }
140
141     // A "specific" location is optional.
142     std::string specific;
143     dict->GetString(ManifestError::kManifestSpecificKey, &specific);
144
145     contents = new std::string;  // Owned by GetManifestFileCallback(    )
146     closure = base::Bind(&ExtensionErrorHandler::GetManifestFileCallback,
147                          base::Unretained(this),
148                          base::Owned(results.release()),
149                          manifest_key,
150                          specific,
151                          base::Owned(contents));
152   } else {
153     int line_number = 0;
154     dict->GetInteger(RuntimeError::kLineNumberKey, &line_number);
155
156     contents = new std::string;  // Owned by GetSourceFileCallback()
157     closure = base::Bind(&ExtensionErrorHandler::GetSourceFileCallback,
158                          base::Unretained(this),
159                          base::Owned(results.release()),
160                          line_number,
161                          base::Owned(contents));
162   }
163
164   content::BrowserThread::PostBlockingPoolTaskAndReply(
165       FROM_HERE,
166       base::Bind(base::IgnoreResult(&base::ReadFileToString),
167                  path,
168                  contents),
169       closure);
170 }
171
172 void ExtensionErrorHandler::HandleOpenDevTools(const base::ListValue* args) {
173   CHECK(args->GetSize() == 1);
174
175   const base::DictionaryValue* dict = NULL;
176   int render_process_id = 0;
177   int render_view_id = 0;
178
179   // The render view and render process ids are required.
180   if (!args->GetDictionary(0, &dict) ||
181       !dict->GetInteger(RuntimeError::kRenderProcessIdKey,
182                         &render_process_id) ||
183       !dict->GetInteger(RuntimeError::kRenderViewIdKey, &render_view_id)) {
184     NOTREACHED();
185     return;
186   }
187
188   content::RenderViewHost* rvh =
189       content::RenderViewHost::FromID(render_process_id, render_view_id);
190
191   // It's possible that the render view was closed since we last updated the
192   // links. Handle this gracefully.
193   if (!rvh)
194     return;
195
196   // Check if we already have an inspector for the given RenderViewHost. If not,
197   // create one.
198   DevToolsWindow* window =
199       DevToolsWindow::GetInstanceForInspectedRenderViewHost(rvh);
200   if (!window)
201     window = DevToolsWindow::OpenDevToolsWindow(rvh);
202
203   // If we include a url, we should inspect it specifically (and not just the
204   // render view).
205   base::string16 url;
206   if (dict->GetString(RuntimeError::kUrlKey, &url)) {
207     // Line and column numbers are optional; default to the first line.
208     int line_number = 1;
209     int column_number = 1;
210     dict->GetInteger(RuntimeError::kLineNumberKey, &line_number);
211     dict->GetInteger(RuntimeError::kColumnNumberKey, &column_number);
212
213     // Line/column numbers are reported in display-friendly 1-based numbers,
214     // but are inspected in zero-based numbers.
215     window->Show(
216         DevToolsToggleAction::Reveal(url, line_number - 1, column_number - 1));
217   }
218
219   // Once we open the inspector, we focus on the appropriate tab...
220   content::WebContents* web_contents =
221       content::WebContents::FromRenderViewHost(rvh);
222   Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
223   // ... but background pages have no associated browser (and the inspector
224   // opens in its own window), so our work is done.
225   if (!browser)
226     return;
227
228   TabStripModel* tab_strip = browser->tab_strip_model();
229   tab_strip->ActivateTabAt(tab_strip->GetIndexOfWebContents(web_contents),
230                            false);  // Not through direct user gesture.
231 }
232
233 void ExtensionErrorHandler::GetManifestFileCallback(
234     base::DictionaryValue* results,
235     const std::string& key,
236     const std::string& specific,
237     std::string* contents) {
238   ManifestHighlighter highlighter(*contents, key, specific);
239   highlighter.SetHighlightedRegions(results);
240   web_ui()->CallJavascriptFunction(
241       "extensions.ExtensionErrorOverlay.requestFileSourceResponse", *results);
242 }
243
244 void ExtensionErrorHandler::GetSourceFileCallback(
245     base::DictionaryValue* results,
246     int line_number,
247     std::string* contents) {
248   SourceHighlighter highlighter(*contents, line_number);
249   highlighter.SetHighlightedRegions(results);
250   web_ui()->CallJavascriptFunction(
251       "extensions.ExtensionErrorOverlay.requestFileSourceResponse", *results);
252 }
253
254 }  // namespace extensions