1 // Copyright 2014 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/browser/devtools/devtools_ui_bindings.h"
7 #include "base/json/json_reader.h"
8 #include "base/json/json_writer.h"
9 #include "base/metrics/histogram.h"
10 #include "base/prefs/scoped_user_pref_update.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/values.h"
16 #include "chrome/browser/chrome_notification_types.h"
17 #include "chrome/browser/devtools/devtools_target_impl.h"
18 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
19 #include "chrome/browser/infobars/infobar_service.h"
20 #include "chrome/browser/prefs/pref_service_syncable.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/ui/browser.h"
23 #include "chrome/browser/ui/browser_iterator.h"
24 #include "chrome/browser/ui/browser_list.h"
25 #include "chrome/browser/ui/browser_window.h"
26 #include "chrome/browser/ui/tabs/tab_strip_model.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "chrome/common/extensions/chrome_manifest_url_handlers.h"
29 #include "chrome/common/pref_names.h"
30 #include "chrome/common/url_constants.h"
31 #include "chrome/grit/generated_resources.h"
32 #include "components/infobars/core/confirm_infobar_delegate.h"
33 #include "components/infobars/core/infobar.h"
34 #include "components/ui/zoom/page_zoom.h"
35 #include "content/public/browser/invalidate_type.h"
36 #include "content/public/browser/navigation_controller.h"
37 #include "content/public/browser/navigation_entry.h"
38 #include "content/public/browser/notification_source.h"
39 #include "content/public/browser/render_frame_host.h"
40 #include "content/public/browser/render_view_host.h"
41 #include "content/public/browser/user_metrics.h"
42 #include "content/public/browser/web_contents.h"
43 #include "content/public/browser/web_contents_observer.h"
44 #include "content/public/common/renderer_preferences.h"
45 #include "content/public/common/url_constants.h"
46 #include "extensions/browser/extension_registry.h"
47 #include "extensions/common/permissions/permissions_data.h"
48 #include "net/base/io_buffer.h"
49 #include "net/base/net_errors.h"
50 #include "net/http/http_response_headers.h"
51 #include "net/url_request/url_fetcher.h"
52 #include "net/url_request/url_fetcher_response_writer.h"
53 #include "ui/base/l10n/l10n_util.h"
54 #include "ui/base/page_transition_types.h"
56 using base::DictionaryValue
;
57 using content::BrowserThread
;
60 struct LoadCommittedDetails
;
61 struct FrameNavigateParams
;
66 static const char kFrontendHostId
[] = "id";
67 static const char kFrontendHostMethod
[] = "method";
68 static const char kFrontendHostParams
[] = "params";
69 static const char kTitleFormat
[] = "Developer Tools - %s";
71 static const char kDevToolsActionTakenHistogram
[] = "DevTools.ActionTaken";
72 static const char kDevToolsPanelShownHistogram
[] = "DevTools.PanelShown";
74 // This constant should be in sync with
75 // the constant at shell_devtools_frontend.cc.
76 const size_t kMaxMessageChunkSize
= IPC::Channel::kMaximumMessageSize
/ 4;
78 typedef std::vector
<DevToolsUIBindings
*> DevToolsUIBindingsList
;
79 base::LazyInstance
<DevToolsUIBindingsList
>::Leaky g_instances
=
80 LAZY_INSTANCE_INITIALIZER
;
82 base::DictionaryValue
* CreateFileSystemValue(
83 DevToolsFileHelper::FileSystem file_system
) {
84 base::DictionaryValue
* file_system_value
= new base::DictionaryValue();
85 file_system_value
->SetString("fileSystemName", file_system
.file_system_name
);
86 file_system_value
->SetString("rootURL", file_system
.root_url
);
87 file_system_value
->SetString("fileSystemPath", file_system
.file_system_path
);
88 return file_system_value
;
91 Browser
* FindBrowser(content::WebContents
* web_contents
) {
92 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
93 int tab_index
= it
->tab_strip_model()->GetIndexOfWebContents(
95 if (tab_index
!= TabStripModel::kNoTab
)
101 // DevToolsConfirmInfoBarDelegate ---------------------------------------------
103 typedef base::Callback
<void(bool)> InfoBarCallback
;
105 class DevToolsConfirmInfoBarDelegate
: public ConfirmInfoBarDelegate
{
107 // If |infobar_service| is NULL, runs |callback| with a single argument with
108 // value "false". Otherwise, creates a dev tools confirm infobar and delegate
109 // and adds the infobar to |infobar_service|.
110 static void Create(InfoBarService
* infobar_service
,
111 const InfoBarCallback
& callback
,
112 const base::string16
& message
);
115 DevToolsConfirmInfoBarDelegate(
116 const InfoBarCallback
& callback
,
117 const base::string16
& message
);
118 ~DevToolsConfirmInfoBarDelegate() override
;
120 base::string16
GetMessageText() const override
;
121 base::string16
GetButtonLabel(InfoBarButton button
) const override
;
122 bool Accept() override
;
123 bool Cancel() override
;
125 InfoBarCallback callback_
;
126 const base::string16 message_
;
128 DISALLOW_COPY_AND_ASSIGN(DevToolsConfirmInfoBarDelegate
);
131 void DevToolsConfirmInfoBarDelegate::Create(
132 InfoBarService
* infobar_service
,
133 const InfoBarCallback
& callback
,
134 const base::string16
& message
) {
135 if (!infobar_service
) {
140 infobar_service
->AddInfoBar(
141 infobar_service
->CreateConfirmInfoBar(scoped_ptr
<ConfirmInfoBarDelegate
>(
142 new DevToolsConfirmInfoBarDelegate(callback
, message
))));
145 DevToolsConfirmInfoBarDelegate::DevToolsConfirmInfoBarDelegate(
146 const InfoBarCallback
& callback
,
147 const base::string16
& message
)
148 : ConfirmInfoBarDelegate(),
153 DevToolsConfirmInfoBarDelegate::~DevToolsConfirmInfoBarDelegate() {
154 if (!callback_
.is_null())
155 callback_
.Run(false);
158 base::string16
DevToolsConfirmInfoBarDelegate::GetMessageText() const {
162 base::string16
DevToolsConfirmInfoBarDelegate::GetButtonLabel(
163 InfoBarButton button
) const {
164 return l10n_util::GetStringUTF16((button
== BUTTON_OK
) ?
165 IDS_DEV_TOOLS_CONFIRM_ALLOW_BUTTON
: IDS_DEV_TOOLS_CONFIRM_DENY_BUTTON
);
168 bool DevToolsConfirmInfoBarDelegate::Accept() {
174 bool DevToolsConfirmInfoBarDelegate::Cancel() {
175 callback_
.Run(false);
180 // DevToolsUIDefaultDelegate --------------------------------------------------
182 class DefaultBindingsDelegate
: public DevToolsUIBindings::Delegate
{
184 explicit DefaultBindingsDelegate(content::WebContents
* web_contents
)
185 : web_contents_(web_contents
) {}
188 ~DefaultBindingsDelegate() override
{}
190 void ActivateWindow() override
;
191 void CloseWindow() override
{}
192 void SetInspectedPageBounds(const gfx::Rect
& rect
) override
{}
193 void InspectElementCompleted() override
{}
194 void SetIsDocked(bool is_docked
) override
{}
195 void OpenInNewTab(const std::string
& url
) override
;
196 void SetWhitelistedShortcuts(const std::string
& message
) override
{}
197 using DispatchCallback
=
198 DevToolsEmbedderMessageDispatcher::Delegate::DispatchCallback
;
200 void InspectedContentsClosing() override
;
201 void OnLoadCompleted() override
{}
202 InfoBarService
* GetInfoBarService() override
;
203 void RenderProcessGone(bool crashed
) override
{}
205 content::WebContents
* web_contents_
;
206 DISALLOW_COPY_AND_ASSIGN(DefaultBindingsDelegate
);
209 void DefaultBindingsDelegate::ActivateWindow() {
210 web_contents_
->GetDelegate()->ActivateContents(web_contents_
);
211 web_contents_
->Focus();
214 void DefaultBindingsDelegate::OpenInNewTab(const std::string
& url
) {
215 content::OpenURLParams
params(
216 GURL(url
), content::Referrer(), NEW_FOREGROUND_TAB
,
217 ui::PAGE_TRANSITION_LINK
, false);
218 Browser
* browser
= FindBrowser(web_contents_
);
219 browser
->OpenURL(params
);
222 void DefaultBindingsDelegate::InspectedContentsClosing() {
223 web_contents_
->ClosePage();
226 InfoBarService
* DefaultBindingsDelegate::GetInfoBarService() {
227 return InfoBarService::FromWebContents(web_contents_
);
230 // ResponseWriter -------------------------------------------------------------
232 class ResponseWriter
: public net::URLFetcherResponseWriter
{
234 ResponseWriter(base::WeakPtr
<DevToolsUIBindings
> bindings
, int stream_id
);
235 ~ResponseWriter() override
;
237 // URLFetcherResponseWriter overrides:
238 int Initialize(const net::CompletionCallback
& callback
) override
;
239 int Write(net::IOBuffer
* buffer
,
241 const net::CompletionCallback
& callback
) override
;
242 int Finish(const net::CompletionCallback
& callback
) override
;
245 base::WeakPtr
<DevToolsUIBindings
> bindings_
;
248 DISALLOW_COPY_AND_ASSIGN(ResponseWriter
);
251 ResponseWriter::ResponseWriter(base::WeakPtr
<DevToolsUIBindings
> bindings
,
253 : bindings_(bindings
),
254 stream_id_(stream_id
) {
257 ResponseWriter::~ResponseWriter() {
260 int ResponseWriter::Initialize(const net::CompletionCallback
& callback
) {
264 int ResponseWriter::Write(net::IOBuffer
* buffer
,
266 const net::CompletionCallback
& callback
) {
267 base::FundamentalValue
* id
= new base::FundamentalValue(stream_id_
);
268 base::StringValue
* chunk
=
269 new base::StringValue(std::string(buffer
->data(), num_bytes
));
271 content::BrowserThread::PostTask(
272 content::BrowserThread::UI
, FROM_HERE
,
273 base::Bind(&DevToolsUIBindings::CallClientFunction
,
274 bindings_
, "DevToolsAPI.streamWrite",
275 base::Owned(id
), base::Owned(chunk
), nullptr));
279 int ResponseWriter::Finish(const net::CompletionCallback
& callback
) {
285 // DevToolsUIBindings::FrontendWebContentsObserver ----------------------------
287 class DevToolsUIBindings::FrontendWebContentsObserver
288 : public content::WebContentsObserver
{
290 explicit FrontendWebContentsObserver(DevToolsUIBindings
* ui_bindings
);
291 ~FrontendWebContentsObserver() override
;
294 // contents::WebContentsObserver:
295 void RenderProcessGone(base::TerminationStatus status
) override
;
296 // TODO(creis): Replace with RenderFrameCreated when http://crbug.com/425397
297 // is fixed. See also http://crbug.com/424641.
298 void AboutToNavigateRenderFrame(
299 content::RenderFrameHost
* old_host
,
300 content::RenderFrameHost
* new_host
) override
;
301 void DocumentOnLoadCompletedInMainFrame() override
;
302 void DidNavigateMainFrame(
303 const content::LoadCommittedDetails
& details
,
304 const content::FrameNavigateParams
& params
) override
;
306 DevToolsUIBindings
* devtools_bindings_
;
307 DISALLOW_COPY_AND_ASSIGN(FrontendWebContentsObserver
);
310 DevToolsUIBindings::FrontendWebContentsObserver::FrontendWebContentsObserver(
311 DevToolsUIBindings
* devtools_ui_bindings
)
312 : WebContentsObserver(devtools_ui_bindings
->web_contents()),
313 devtools_bindings_(devtools_ui_bindings
) {
316 DevToolsUIBindings::FrontendWebContentsObserver::
317 ~FrontendWebContentsObserver() {
320 void DevToolsUIBindings::FrontendWebContentsObserver::RenderProcessGone(
321 base::TerminationStatus status
) {
324 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
:
325 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
:
326 #if defined(OS_CHROMEOS)
327 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
:
329 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
330 case base::TERMINATION_STATUS_LAUNCH_FAILED
:
331 if (devtools_bindings_
->agent_host_
.get())
332 devtools_bindings_
->Detach();
338 devtools_bindings_
->delegate_
->RenderProcessGone(crashed
);
341 void DevToolsUIBindings::FrontendWebContentsObserver::
342 AboutToNavigateRenderFrame(content::RenderFrameHost
* old_host
,
343 content::RenderFrameHost
* new_host
) {
344 if (new_host
->GetParent())
346 devtools_bindings_
->frontend_host_
.reset(
347 content::DevToolsFrontendHost::Create(new_host
,
348 devtools_bindings_
));
351 void DevToolsUIBindings::FrontendWebContentsObserver::
352 DocumentOnLoadCompletedInMainFrame() {
353 devtools_bindings_
->DocumentOnLoadCompletedInMainFrame();
356 void DevToolsUIBindings::FrontendWebContentsObserver::
357 DidNavigateMainFrame(const content::LoadCommittedDetails
& details
,
358 const content::FrameNavigateParams
& params
) {
359 devtools_bindings_
->DidNavigateMainFrame();
362 // DevToolsUIBindings ---------------------------------------------------------
364 DevToolsUIBindings
* DevToolsUIBindings::ForWebContents(
365 content::WebContents
* web_contents
) {
366 if (g_instances
== NULL
)
368 DevToolsUIBindingsList
* instances
= g_instances
.Pointer();
369 for (DevToolsUIBindingsList::iterator
it(instances
->begin());
370 it
!= instances
->end(); ++it
) {
371 if ((*it
)->web_contents() == web_contents
)
377 DevToolsUIBindings::DevToolsUIBindings(content::WebContents
* web_contents
)
378 : profile_(Profile::FromBrowserContext(web_contents
->GetBrowserContext())),
379 android_bridge_(DevToolsAndroidBridge::Factory::GetForProfile(profile_
)),
380 web_contents_(web_contents
),
381 delegate_(new DefaultBindingsDelegate(web_contents_
)),
382 devices_updates_enabled_(false),
383 frontend_loaded_(false),
384 weak_factory_(this) {
385 g_instances
.Get().push_back(this);
386 frontend_contents_observer_
.reset(new FrontendWebContentsObserver(this));
387 web_contents_
->GetMutableRendererPrefs()->can_accept_load_drops
= false;
389 file_helper_
.reset(new DevToolsFileHelper(web_contents_
, profile_
));
390 file_system_indexer_
= new DevToolsFileSystemIndexer();
391 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
394 // Register on-load actions.
395 embedder_message_dispatcher_
.reset(
396 DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this));
398 frontend_host_
.reset(content::DevToolsFrontendHost::Create(
399 web_contents_
->GetMainFrame(), this));
402 DevToolsUIBindings::~DevToolsUIBindings() {
403 for (const auto& pair
: pending_requests_
)
406 if (agent_host_
.get())
407 agent_host_
->DetachClient();
409 for (IndexingJobsMap::const_iterator
jobs_it(indexing_jobs_
.begin());
410 jobs_it
!= indexing_jobs_
.end(); ++jobs_it
) {
411 jobs_it
->second
->Stop();
413 indexing_jobs_
.clear();
414 SetDevicesUpdatesEnabled(false);
416 // Remove self from global list.
417 DevToolsUIBindingsList
* instances
= g_instances
.Pointer();
418 DevToolsUIBindingsList::iterator
it(
419 std::find(instances
->begin(), instances
->end(), this));
420 DCHECK(it
!= instances
->end());
421 instances
->erase(it
);
424 // content::DevToolsFrontendHost::Delegate implementation ---------------------
425 void DevToolsUIBindings::HandleMessageFromDevToolsFrontend(
426 const std::string
& message
) {
428 base::ListValue empty_params
;
429 base::ListValue
* params
= &empty_params
;
431 base::DictionaryValue
* dict
= NULL
;
432 scoped_ptr
<base::Value
> parsed_message
= base::JSONReader::Read(message
);
433 if (!parsed_message
||
434 !parsed_message
->GetAsDictionary(&dict
) ||
435 !dict
->GetString(kFrontendHostMethod
, &method
) ||
436 (dict
->HasKey(kFrontendHostParams
) &&
437 !dict
->GetList(kFrontendHostParams
, ¶ms
))) {
438 LOG(ERROR
) << "Invalid message was sent to embedder: " << message
;
442 dict
->GetInteger(kFrontendHostId
, &id
);
443 embedder_message_dispatcher_
->Dispatch(
444 base::Bind(&DevToolsUIBindings::SendMessageAck
,
445 weak_factory_
.GetWeakPtr(),
451 void DevToolsUIBindings::HandleMessageFromDevToolsFrontendToBackend(
452 const std::string
& message
) {
453 if (agent_host_
.get())
454 agent_host_
->DispatchProtocolMessage(message
);
457 // content::DevToolsAgentHostClient implementation --------------------------
458 void DevToolsUIBindings::DispatchProtocolMessage(
459 content::DevToolsAgentHost
* agent_host
, const std::string
& message
) {
460 DCHECK(agent_host
== agent_host_
.get());
462 if (message
.length() < kMaxMessageChunkSize
) {
463 base::string16 javascript
= base::UTF8ToUTF16(
464 "DevToolsAPI.dispatchMessage(" + message
+ ");");
465 web_contents_
->GetMainFrame()->ExecuteJavaScript(javascript
);
469 base::FundamentalValue
total_size(static_cast<int>(message
.length()));
470 for (size_t pos
= 0; pos
< message
.length(); pos
+= kMaxMessageChunkSize
) {
471 base::StringValue
message_value(message
.substr(pos
, kMaxMessageChunkSize
));
472 CallClientFunction("DevToolsAPI.dispatchMessageChunk",
473 &message_value
, pos
? NULL
: &total_size
, NULL
);
477 void DevToolsUIBindings::AgentHostClosed(
478 content::DevToolsAgentHost
* agent_host
,
479 bool replaced_with_another_client
) {
480 DCHECK(agent_host
== agent_host_
.get());
482 delegate_
->InspectedContentsClosing();
485 void DevToolsUIBindings::SendMessageAck(int request_id
,
486 const base::Value
* arg
) {
487 base::FundamentalValue
id_value(request_id
);
488 CallClientFunction("DevToolsAPI.embedderMessageAck",
489 &id_value
, arg
, nullptr);
492 // DevToolsEmbedderMessageDispatcher::Delegate implementation -----------------
493 void DevToolsUIBindings::ActivateWindow() {
494 delegate_
->ActivateWindow();
497 void DevToolsUIBindings::CloseWindow() {
498 delegate_
->CloseWindow();
501 void DevToolsUIBindings::LoadCompleted() {
505 void DevToolsUIBindings::SetInspectedPageBounds(const gfx::Rect
& rect
) {
506 delegate_
->SetInspectedPageBounds(rect
);
509 void DevToolsUIBindings::SetIsDocked(const DispatchCallback
& callback
,
510 bool dock_requested
) {
511 delegate_
->SetIsDocked(dock_requested
);
512 callback
.Run(nullptr);
515 void DevToolsUIBindings::InspectElementCompleted() {
516 delegate_
->InspectElementCompleted();
519 void DevToolsUIBindings::InspectedURLChanged(const std::string
& url
) {
520 content::NavigationController
& controller
= web_contents()->GetController();
521 content::NavigationEntry
* entry
= controller
.GetActiveEntry();
522 // DevTools UI is not localized.
524 base::UTF8ToUTF16(base::StringPrintf(kTitleFormat
, url
.c_str())));
525 web_contents()->NotifyNavigationStateChanged(content::INVALIDATE_TYPE_TITLE
);
528 void DevToolsUIBindings::LoadNetworkResource(const DispatchCallback
& callback
,
529 const std::string
& url
,
530 const std::string
& headers
,
533 if (!gurl
.is_valid()) {
534 base::DictionaryValue response
;
535 response
.SetInteger("statusCode", 404);
536 callback
.Run(&response
);
540 net::URLFetcher
* fetcher
=
541 net::URLFetcher::Create(gurl
, net::URLFetcher::GET
, this).release();
542 pending_requests_
[fetcher
] = callback
;
543 fetcher
->SetRequestContext(profile_
->GetRequestContext());
544 fetcher
->SetExtraRequestHeaders(headers
);
545 fetcher
->SaveResponseWithWriter(scoped_ptr
<net::URLFetcherResponseWriter
>(
546 new ResponseWriter(weak_factory_
.GetWeakPtr(), stream_id
)));
550 void DevToolsUIBindings::OpenInNewTab(const std::string
& url
) {
551 delegate_
->OpenInNewTab(url
);
554 void DevToolsUIBindings::SaveToFile(const std::string
& url
,
555 const std::string
& content
,
557 file_helper_
->Save(url
, content
, save_as
,
558 base::Bind(&DevToolsUIBindings::FileSavedAs
,
559 weak_factory_
.GetWeakPtr(), url
),
560 base::Bind(&DevToolsUIBindings::CanceledFileSaveAs
,
561 weak_factory_
.GetWeakPtr(), url
));
564 void DevToolsUIBindings::AppendToFile(const std::string
& url
,
565 const std::string
& content
) {
566 file_helper_
->Append(url
, content
,
567 base::Bind(&DevToolsUIBindings::AppendedTo
,
568 weak_factory_
.GetWeakPtr(), url
));
571 void DevToolsUIBindings::RequestFileSystems() {
572 CHECK(web_contents_
->GetURL().SchemeIs(content::kChromeDevToolsScheme
));
573 file_helper_
->RequestFileSystems(base::Bind(
574 &DevToolsUIBindings::FileSystemsLoaded
, weak_factory_
.GetWeakPtr()));
577 void DevToolsUIBindings::AddFileSystem() {
578 CHECK(web_contents_
->GetURL().SchemeIs(content::kChromeDevToolsScheme
));
579 file_helper_
->AddFileSystem(
580 base::Bind(&DevToolsUIBindings::FileSystemAdded
,
581 weak_factory_
.GetWeakPtr()),
582 base::Bind(&DevToolsUIBindings::ShowDevToolsConfirmInfoBar
,
583 weak_factory_
.GetWeakPtr()));
586 void DevToolsUIBindings::RemoveFileSystem(const std::string
& file_system_path
) {
587 CHECK(web_contents_
->GetURL().SchemeIs(content::kChromeDevToolsScheme
));
588 file_helper_
->RemoveFileSystem(file_system_path
);
589 base::StringValue
file_system_path_value(file_system_path
);
590 CallClientFunction("DevToolsAPI.fileSystemRemoved",
591 &file_system_path_value
, NULL
, NULL
);
594 void DevToolsUIBindings::UpgradeDraggedFileSystemPermissions(
595 const std::string
& file_system_url
) {
596 CHECK(web_contents_
->GetURL().SchemeIs(content::kChromeDevToolsScheme
));
597 file_helper_
->UpgradeDraggedFileSystemPermissions(
599 base::Bind(&DevToolsUIBindings::FileSystemAdded
,
600 weak_factory_
.GetWeakPtr()),
601 base::Bind(&DevToolsUIBindings::ShowDevToolsConfirmInfoBar
,
602 weak_factory_
.GetWeakPtr()));
605 void DevToolsUIBindings::IndexPath(int index_request_id
,
606 const std::string
& file_system_path
) {
607 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
608 CHECK(web_contents_
->GetURL().SchemeIs(content::kChromeDevToolsScheme
));
609 if (!file_helper_
->IsFileSystemAdded(file_system_path
)) {
610 IndexingDone(index_request_id
, file_system_path
);
613 if (indexing_jobs_
.count(index_request_id
) != 0)
615 indexing_jobs_
[index_request_id
] =
616 scoped_refptr
<DevToolsFileSystemIndexer::FileSystemIndexingJob
>(
617 file_system_indexer_
->IndexPath(
619 Bind(&DevToolsUIBindings::IndexingTotalWorkCalculated
,
620 weak_factory_
.GetWeakPtr(),
623 Bind(&DevToolsUIBindings::IndexingWorked
,
624 weak_factory_
.GetWeakPtr(),
627 Bind(&DevToolsUIBindings::IndexingDone
,
628 weak_factory_
.GetWeakPtr(),
633 void DevToolsUIBindings::StopIndexing(int index_request_id
) {
634 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
635 IndexingJobsMap::iterator it
= indexing_jobs_
.find(index_request_id
);
636 if (it
== indexing_jobs_
.end())
639 indexing_jobs_
.erase(it
);
642 void DevToolsUIBindings::SearchInPath(int search_request_id
,
643 const std::string
& file_system_path
,
644 const std::string
& query
) {
645 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
646 CHECK(web_contents_
->GetURL().SchemeIs(content::kChromeDevToolsScheme
));
647 if (!file_helper_
->IsFileSystemAdded(file_system_path
)) {
648 SearchCompleted(search_request_id
,
650 std::vector
<std::string
>());
653 file_system_indexer_
->SearchInPath(file_system_path
,
655 Bind(&DevToolsUIBindings::SearchCompleted
,
656 weak_factory_
.GetWeakPtr(),
661 void DevToolsUIBindings::SetWhitelistedShortcuts(const std::string
& message
) {
662 delegate_
->SetWhitelistedShortcuts(message
);
665 void DevToolsUIBindings::ZoomIn() {
666 ui_zoom::PageZoom::Zoom(web_contents(), content::PAGE_ZOOM_IN
);
669 void DevToolsUIBindings::ZoomOut() {
670 ui_zoom::PageZoom::Zoom(web_contents(), content::PAGE_ZOOM_OUT
);
673 void DevToolsUIBindings::ResetZoom() {
674 ui_zoom::PageZoom::Zoom(web_contents(), content::PAGE_ZOOM_RESET
);
677 void DevToolsUIBindings::SetDevicesUpdatesEnabled(bool enabled
) {
678 if (devices_updates_enabled_
== enabled
)
680 devices_updates_enabled_
= enabled
;
682 remote_targets_handler_
= DevToolsTargetsUIHandler::CreateForAdb(
683 base::Bind(&DevToolsUIBindings::DevicesUpdated
,
684 base::Unretained(this)),
687 remote_targets_handler_
.reset();
691 void DevToolsUIBindings::GetPreferences(const DispatchCallback
& callback
) {
692 const DictionaryValue
* prefs
=
693 profile_
->GetPrefs()->GetDictionary(prefs::kDevToolsPreferences
);
697 void DevToolsUIBindings::SetPreference(const std::string
& name
,
698 const std::string
& value
) {
699 DictionaryPrefUpdate
update(profile_
->GetPrefs(),
700 prefs::kDevToolsPreferences
);
701 update
.Get()->SetStringWithoutPathExpansion(name
, value
);
704 void DevToolsUIBindings::RemovePreference(const std::string
& name
) {
705 DictionaryPrefUpdate
update(profile_
->GetPrefs(),
706 prefs::kDevToolsPreferences
);
707 update
.Get()->RemoveWithoutPathExpansion(name
, nullptr);
710 void DevToolsUIBindings::ClearPreferences() {
711 DictionaryPrefUpdate
update(profile_
->GetPrefs(),
712 prefs::kDevToolsPreferences
);
713 update
.Get()->Clear();
716 void DevToolsUIBindings::SendMessageToBrowser(const std::string
& message
) {
717 if (agent_host_
.get())
718 agent_host_
->DispatchProtocolMessage(message
);
721 void DevToolsUIBindings::RecordEnumeratedHistogram(const std::string
& name
,
723 int boundary_value
) {
724 if (!(boundary_value
>= 0 && boundary_value
<= 100 && sample
>= 0 &&
725 sample
< boundary_value
)) {
726 // TODO(nick): Replace with chrome::bad_message::ReceivedBadMessage().
727 frontend_host_
->BadMessageRecieved();
730 // Each histogram name must follow a different code path in
731 // order to UMA_HISTOGRAM_ENUMERATION work correctly.
732 if (name
== kDevToolsActionTakenHistogram
)
733 UMA_HISTOGRAM_ENUMERATION(name
, sample
, boundary_value
);
734 else if (name
== kDevToolsPanelShownHistogram
)
735 UMA_HISTOGRAM_ENUMERATION(name
, sample
, boundary_value
);
737 frontend_host_
->BadMessageRecieved();
740 void DevToolsUIBindings::SendJsonRequest(const DispatchCallback
& callback
,
741 const std::string
& browser_id
,
742 const std::string
& url
) {
743 if (!android_bridge_
) {
744 callback
.Run(nullptr);
747 android_bridge_
->SendJsonRequest(browser_id
, url
,
748 base::Bind(&DevToolsUIBindings::JsonReceived
,
749 weak_factory_
.GetWeakPtr(),
753 void DevToolsUIBindings::JsonReceived(const DispatchCallback
& callback
,
755 const std::string
& message
) {
756 if (result
!= net::OK
) {
757 callback
.Run(nullptr);
760 base::StringValue
message_value(message
);
761 callback
.Run(&message_value
);
764 void DevToolsUIBindings::OnURLFetchComplete(const net::URLFetcher
* source
) {
766 PendingRequestsMap::iterator it
= pending_requests_
.find(source
);
767 DCHECK(it
!= pending_requests_
.end());
769 base::DictionaryValue response
;
770 base::DictionaryValue
* headers
= new base::DictionaryValue();
771 net::HttpResponseHeaders
* rh
= source
->GetResponseHeaders();
772 response
.SetInteger("statusCode", rh
? rh
->response_code() : 200);
773 response
.Set("headers", headers
);
775 void* iterator
= NULL
;
778 while (rh
&& rh
->EnumerateHeaderLines(&iterator
, &name
, &value
))
779 headers
->SetString(name
, value
);
781 it
->second
.Run(&response
);
782 pending_requests_
.erase(it
);
786 void DevToolsUIBindings::DeviceCountChanged(int count
) {
787 base::FundamentalValue
value(count
);
788 CallClientFunction("DevToolsAPI.deviceCountUpdated", &value
, NULL
,
792 void DevToolsUIBindings::DevicesUpdated(
793 const std::string
& source
,
794 const base::ListValue
& targets
) {
795 CallClientFunction("DevToolsAPI.devicesUpdated", &targets
, NULL
,
799 void DevToolsUIBindings::FileSavedAs(const std::string
& url
) {
800 base::StringValue
url_value(url
);
801 CallClientFunction("DevToolsAPI.savedURL", &url_value
, NULL
, NULL
);
804 void DevToolsUIBindings::CanceledFileSaveAs(const std::string
& url
) {
805 base::StringValue
url_value(url
);
806 CallClientFunction("DevToolsAPI.canceledSaveURL",
807 &url_value
, NULL
, NULL
);
810 void DevToolsUIBindings::AppendedTo(const std::string
& url
) {
811 base::StringValue
url_value(url
);
812 CallClientFunction("DevToolsAPI.appendedToURL", &url_value
, NULL
,
816 void DevToolsUIBindings::FileSystemsLoaded(
817 const std::vector
<DevToolsFileHelper::FileSystem
>& file_systems
) {
818 base::ListValue file_systems_value
;
819 for (size_t i
= 0; i
< file_systems
.size(); ++i
)
820 file_systems_value
.Append(CreateFileSystemValue(file_systems
[i
]));
821 CallClientFunction("DevToolsAPI.fileSystemsLoaded",
822 &file_systems_value
, NULL
, NULL
);
825 void DevToolsUIBindings::FileSystemAdded(
826 const DevToolsFileHelper::FileSystem
& file_system
) {
827 scoped_ptr
<base::StringValue
> error_string_value(
828 new base::StringValue(std::string()));
829 scoped_ptr
<base::DictionaryValue
> file_system_value
;
830 if (!file_system
.file_system_path
.empty())
831 file_system_value
.reset(CreateFileSystemValue(file_system
));
832 CallClientFunction("DevToolsAPI.fileSystemAdded",
833 error_string_value
.get(), file_system_value
.get(), NULL
);
836 void DevToolsUIBindings::IndexingTotalWorkCalculated(
838 const std::string
& file_system_path
,
840 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
841 base::FundamentalValue
request_id_value(request_id
);
842 base::StringValue
file_system_path_value(file_system_path
);
843 base::FundamentalValue
total_work_value(total_work
);
844 CallClientFunction("DevToolsAPI.indexingTotalWorkCalculated",
845 &request_id_value
, &file_system_path_value
,
849 void DevToolsUIBindings::IndexingWorked(int request_id
,
850 const std::string
& file_system_path
,
852 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
853 base::FundamentalValue
request_id_value(request_id
);
854 base::StringValue
file_system_path_value(file_system_path
);
855 base::FundamentalValue
worked_value(worked
);
856 CallClientFunction("DevToolsAPI.indexingWorked", &request_id_value
,
857 &file_system_path_value
, &worked_value
);
860 void DevToolsUIBindings::IndexingDone(int request_id
,
861 const std::string
& file_system_path
) {
862 indexing_jobs_
.erase(request_id
);
863 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
864 base::FundamentalValue
request_id_value(request_id
);
865 base::StringValue
file_system_path_value(file_system_path
);
866 CallClientFunction("DevToolsAPI.indexingDone", &request_id_value
,
867 &file_system_path_value
, NULL
);
870 void DevToolsUIBindings::SearchCompleted(
872 const std::string
& file_system_path
,
873 const std::vector
<std::string
>& file_paths
) {
874 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
875 base::ListValue file_paths_value
;
876 for (std::vector
<std::string
>::const_iterator
it(file_paths
.begin());
877 it
!= file_paths
.end(); ++it
) {
878 file_paths_value
.AppendString(*it
);
880 base::FundamentalValue
request_id_value(request_id
);
881 base::StringValue
file_system_path_value(file_system_path
);
882 CallClientFunction("DevToolsAPI.searchCompleted", &request_id_value
,
883 &file_system_path_value
, &file_paths_value
);
886 void DevToolsUIBindings::ShowDevToolsConfirmInfoBar(
887 const base::string16
& message
,
888 const InfoBarCallback
& callback
) {
889 DevToolsConfirmInfoBarDelegate::Create(delegate_
->GetInfoBarService(),
893 void DevToolsUIBindings::AddDevToolsExtensionsToClient() {
894 const extensions::ExtensionRegistry
* registry
=
895 extensions::ExtensionRegistry::Get(profile_
->GetOriginalProfile());
899 base::ListValue results
;
900 for (const scoped_refptr
<const extensions::Extension
>& extension
:
901 registry
->enabled_extensions()) {
902 if (extensions::chrome_manifest_urls::GetDevToolsPage(extension
.get())
905 base::DictionaryValue
* extension_info
= new base::DictionaryValue();
908 new base::StringValue(extensions::chrome_manifest_urls::GetDevToolsPage(
909 extension
.get()).spec()));
910 extension_info
->Set("name", new base::StringValue(extension
->name()));
911 extension_info
->Set("exposeExperimentalAPIs",
912 new base::FundamentalValue(
913 extension
->permissions_data()->HasAPIPermission(
914 extensions::APIPermission::kExperimental
)));
915 results
.Append(extension_info
);
917 CallClientFunction("DevToolsAPI.addExtensions",
918 &results
, NULL
, NULL
);
921 void DevToolsUIBindings::SetDelegate(Delegate
* delegate
) {
922 delegate_
.reset(delegate
);
925 void DevToolsUIBindings::AttachTo(
926 const scoped_refptr
<content::DevToolsAgentHost
>& agent_host
) {
927 if (agent_host_
.get())
929 agent_host_
= agent_host
;
930 agent_host_
->AttachClient(this);
933 void DevToolsUIBindings::Reattach() {
934 DCHECK(agent_host_
.get());
935 agent_host_
->DetachClient();
936 agent_host_
->AttachClient(this);
939 void DevToolsUIBindings::Detach() {
940 if (agent_host_
.get())
941 agent_host_
->DetachClient();
945 bool DevToolsUIBindings::IsAttachedTo(content::DevToolsAgentHost
* agent_host
) {
946 return agent_host_
.get() == agent_host
;
949 void DevToolsUIBindings::CallClientFunction(const std::string
& function_name
,
950 const base::Value
* arg1
,
951 const base::Value
* arg2
,
952 const base::Value
* arg3
) {
953 std::string javascript
= function_name
+ "(";
956 base::JSONWriter::Write(*arg1
, &json
);
957 javascript
.append(json
);
959 base::JSONWriter::Write(*arg2
, &json
);
960 javascript
.append(", ").append(json
);
962 base::JSONWriter::Write(*arg3
, &json
);
963 javascript
.append(", ").append(json
);
967 javascript
.append(");");
968 web_contents_
->GetMainFrame()->ExecuteJavaScript(
969 base::UTF8ToUTF16(javascript
));
972 void DevToolsUIBindings::DocumentOnLoadCompletedInMainFrame() {
973 // In the DEBUG_DEVTOOLS mode, the DocumentOnLoadCompletedInMainFrame event
974 // arrives before the LoadCompleted event, thus it should not trigger the
975 // frontend load handling.
976 #if !defined(DEBUG_DEVTOOLS)
981 void DevToolsUIBindings::DidNavigateMainFrame() {
982 frontend_loaded_
= false;
985 void DevToolsUIBindings::FrontendLoaded() {
986 if (frontend_loaded_
)
988 frontend_loaded_
= true;
990 // Call delegate first - it seeds importants bit of information.
991 delegate_
->OnLoadCompleted();
993 AddDevToolsExtensionsToClient();