Stack sampling profiler: add fire-and-forget interface
[chromium-blink-merge.git] / components / test_runner / web_test_proxy.cc
blob1539ac729aa4b06ccc709a3e9c54f2c0427d4dfd
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 "components/test_runner/web_test_proxy.h"
7 #include <cctype>
9 #include "base/callback_helpers.h"
10 #include "base/command_line.h"
11 #include "base/i18n/rtl.h"
12 #include "base/logging.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/time/time.h"
18 #include "base/trace_event/trace_event.h"
19 #include "components/test_runner/accessibility_controller.h"
20 #include "components/test_runner/event_sender.h"
21 #include "components/test_runner/mock_color_chooser.h"
22 #include "components/test_runner/mock_credential_manager_client.h"
23 #include "components/test_runner/mock_screen_orientation_client.h"
24 #include "components/test_runner/mock_web_speech_recognizer.h"
25 #include "components/test_runner/mock_web_user_media_client.h"
26 #include "components/test_runner/spell_check_client.h"
27 #include "components/test_runner/test_interfaces.h"
28 #include "components/test_runner/test_plugin.h"
29 #include "components/test_runner/test_runner.h"
30 #include "components/test_runner/web_test_delegate.h"
31 #include "components/test_runner/web_test_interfaces.h"
32 #include "components/test_runner/web_test_runner.h"
33 // FIXME: Including platform_canvas.h here is a layering violation.
34 #include "skia/ext/platform_canvas.h"
35 #include "third_party/WebKit/public/platform/Platform.h"
36 #include "third_party/WebKit/public/platform/WebCString.h"
37 #include "third_party/WebKit/public/platform/WebClipboard.h"
38 #include "third_party/WebKit/public/platform/WebCompositeAndReadbackAsyncCallback.h"
39 #include "third_party/WebKit/public/platform/WebLayoutAndPaintAsyncCallback.h"
40 #include "third_party/WebKit/public/platform/WebURLError.h"
41 #include "third_party/WebKit/public/platform/WebURLRequest.h"
42 #include "third_party/WebKit/public/platform/WebURLResponse.h"
43 #include "third_party/WebKit/public/web/WebAXEnums.h"
44 #include "third_party/WebKit/public/web/WebAXObject.h"
45 #include "third_party/WebKit/public/web/WebCachedURLRequest.h"
46 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
47 #include "third_party/WebKit/public/web/WebDataSource.h"
48 #include "third_party/WebKit/public/web/WebDocument.h"
49 #include "third_party/WebKit/public/web/WebElement.h"
50 #include "third_party/WebKit/public/web/WebHistoryItem.h"
51 #include "third_party/WebKit/public/web/WebLocalFrame.h"
52 #include "third_party/WebKit/public/web/WebNode.h"
53 #include "third_party/WebKit/public/web/WebPagePopup.h"
54 #include "third_party/WebKit/public/web/WebPluginParams.h"
55 #include "third_party/WebKit/public/web/WebPrintParams.h"
56 #include "third_party/WebKit/public/web/WebRange.h"
57 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
58 #include "third_party/WebKit/public/web/WebView.h"
59 #include "third_party/WebKit/public/web/WebWidgetClient.h"
61 namespace test_runner {
63 namespace {
65 class CaptureCallback : public blink::WebCompositeAndReadbackAsyncCallback {
66 public:
67 CaptureCallback(const base::Callback<void(const SkBitmap&)>& callback);
68 virtual ~CaptureCallback();
70 void set_wait_for_popup(bool wait) { wait_for_popup_ = wait; }
71 void set_popup_position(const gfx::Point& position) {
72 popup_position_ = position;
75 // WebCompositeAndReadbackAsyncCallback implementation.
76 virtual void didCompositeAndReadback(const SkBitmap& bitmap);
78 private:
79 base::Callback<void(const SkBitmap&)> callback_;
80 SkBitmap main_bitmap_;
81 bool wait_for_popup_;
82 gfx::Point popup_position_;
85 class LayoutAndPaintCallback : public blink::WebLayoutAndPaintAsyncCallback {
86 public:
87 LayoutAndPaintCallback(const base::Closure& callback)
88 : callback_(callback), wait_for_popup_(false) {
90 virtual ~LayoutAndPaintCallback() {
93 void set_wait_for_popup(bool wait) { wait_for_popup_ = wait; }
95 // WebLayoutAndPaintAsyncCallback implementation.
96 virtual void didLayoutAndPaint();
98 private:
99 base::Closure callback_;
100 bool wait_for_popup_;
103 class HostMethodTask : public WebMethodTask<WebTestProxyBase> {
104 public:
105 typedef void (WebTestProxyBase::*CallbackMethodType)();
106 HostMethodTask(WebTestProxyBase* object, CallbackMethodType callback)
107 : WebMethodTask<WebTestProxyBase>(object), callback_(callback) {}
109 void RunIfValid() override { (object_->*callback_)(); }
111 private:
112 CallbackMethodType callback_;
115 void PrintFrameDescription(WebTestDelegate* delegate, blink::WebFrame* frame) {
116 std::string name8 = frame->uniqueName().utf8();
117 if (frame == frame->view()->mainFrame()) {
118 if (!name8.length()) {
119 delegate->PrintMessage("main frame");
120 return;
122 delegate->PrintMessage(std::string("main frame \"") + name8 + "\"");
123 return;
125 if (!name8.length()) {
126 delegate->PrintMessage("frame (anonymous)");
127 return;
129 delegate->PrintMessage(std::string("frame \"") + name8 + "\"");
132 void PrintFrameuserGestureStatus(WebTestDelegate* delegate,
133 blink::WebFrame* frame,
134 const char* msg) {
135 bool is_user_gesture =
136 blink::WebUserGestureIndicator::isProcessingUserGesture();
137 delegate->PrintMessage(std::string("Frame with user gesture \"") +
138 (is_user_gesture ? "true" : "false") + "\"" + msg);
141 // Used to write a platform neutral file:/// URL by taking the
142 // filename and its directory. (e.g., converts
143 // "file:///tmp/foo/bar.txt" to just "bar.txt").
144 std::string DescriptionSuitableForTestResult(const std::string& url) {
145 if (url.empty() || std::string::npos == url.find("file://"))
146 return url;
148 size_t pos = url.rfind('/');
149 if (pos == std::string::npos || !pos)
150 return "ERROR:" + url;
151 pos = url.rfind('/', pos - 1);
152 if (pos == std::string::npos)
153 return "ERROR:" + url;
155 return url.substr(pos + 1);
158 void PrintResponseDescription(WebTestDelegate* delegate,
159 const blink::WebURLResponse& response) {
160 if (response.isNull()) {
161 delegate->PrintMessage("(null)");
162 return;
164 delegate->PrintMessage(base::StringPrintf(
165 "<NSURLResponse %s, http status code %d>",
166 DescriptionSuitableForTestResult(response.url().spec()).c_str(),
167 response.httpStatusCode()));
170 std::string URLDescription(const GURL& url) {
171 if (url.SchemeIs(url::kFileScheme))
172 return url.ExtractFileName();
173 return url.possibly_invalid_spec();
176 std::string PriorityDescription(
177 const blink::WebURLRequest::Priority& priority) {
178 switch (priority) {
179 case blink::WebURLRequest::PriorityVeryLow:
180 return "VeryLow";
181 case blink::WebURLRequest::PriorityLow:
182 return "Low";
183 case blink::WebURLRequest::PriorityMedium:
184 return "Medium";
185 case blink::WebURLRequest::PriorityHigh:
186 return "High";
187 case blink::WebURLRequest::PriorityVeryHigh:
188 return "VeryHigh";
189 case blink::WebURLRequest::PriorityUnresolved:
190 default:
191 return "Unresolved";
195 void BlockRequest(blink::WebURLRequest& request) {
196 request.setURL(GURL("255.255.255.255"));
199 bool IsLocalHost(const std::string& host) {
200 return host == "127.0.0.1" || host == "localhost";
203 bool IsTestHost(const std::string& host) {
204 return base::EndsWith(host, ".test", base::CompareCase::INSENSITIVE_ASCII);
207 bool HostIsUsedBySomeTestsToGenerateError(const std::string& host) {
208 return host == "255.255.255.255";
211 // Used to write a platform neutral file:/// URL by only taking the filename
212 // (e.g., converts "file:///tmp/foo.txt" to just "foo.txt").
213 std::string URLSuitableForTestResult(const std::string& url) {
214 if (url.empty() || std::string::npos == url.find("file://"))
215 return url;
217 size_t pos = url.rfind('/');
218 if (pos == std::string::npos) {
219 #ifdef WIN32
220 pos = url.rfind('\\');
221 if (pos == std::string::npos)
222 pos = 0;
223 #else
224 pos = 0;
225 #endif
227 std::string filename = url.substr(pos + 1);
228 if (filename.empty())
229 return "file:"; // A WebKit test has this in its expected output.
230 return filename;
233 // WebNavigationType debugging strings taken from PolicyDelegate.mm.
234 const char* kLinkClickedString = "link clicked";
235 const char* kFormSubmittedString = "form submitted";
236 const char* kBackForwardString = "back/forward";
237 const char* kReloadString = "reload";
238 const char* kFormResubmittedString = "form resubmitted";
239 const char* kOtherString = "other";
240 const char* kIllegalString = "illegal value";
242 // Get a debugging string from a WebNavigationType.
243 const char* WebNavigationTypeToString(blink::WebNavigationType type) {
244 switch (type) {
245 case blink::WebNavigationTypeLinkClicked:
246 return kLinkClickedString;
247 case blink::WebNavigationTypeFormSubmitted:
248 return kFormSubmittedString;
249 case blink::WebNavigationTypeBackForward:
250 return kBackForwardString;
251 case blink::WebNavigationTypeReload:
252 return kReloadString;
253 case blink::WebNavigationTypeFormResubmitted:
254 return kFormResubmittedString;
255 case blink::WebNavigationTypeOther:
256 return kOtherString;
258 return kIllegalString;
261 const char* kPolicyIgnore = "Ignore";
262 const char* kPolicyDownload = "download";
263 const char* kPolicyCurrentTab = "current tab";
264 const char* kPolicyNewBackgroundTab = "new background tab";
265 const char* kPolicyNewForegroundTab = "new foreground tab";
266 const char* kPolicyNewWindow = "new window";
267 const char* kPolicyNewPopup = "new popup";
269 const char* WebNavigationPolicyToString(blink::WebNavigationPolicy policy) {
270 switch (policy) {
271 case blink::WebNavigationPolicyIgnore:
272 return kPolicyIgnore;
273 case blink::WebNavigationPolicyDownload:
274 return kPolicyDownload;
275 case blink::WebNavigationPolicyCurrentTab:
276 return kPolicyCurrentTab;
277 case blink::WebNavigationPolicyNewBackgroundTab:
278 return kPolicyNewBackgroundTab;
279 case blink::WebNavigationPolicyNewForegroundTab:
280 return kPolicyNewForegroundTab;
281 case blink::WebNavigationPolicyNewWindow:
282 return kPolicyNewWindow;
283 case blink::WebNavigationPolicyNewPopup:
284 return kPolicyNewPopup;
286 return kIllegalString;
289 std::string DumpFrameHeaderIfNeeded(blink::WebFrame* frame) {
290 std::string result;
292 // Add header for all but the main frame. Skip empty frames.
293 if (frame->parent() && !frame->document().documentElement().isNull()) {
294 result.append("\n--------\nFrame: '");
295 result.append(frame->uniqueName().utf8().data());
296 result.append("'\n--------\n");
299 return result;
302 std::string DumpFramesAsMarkup(blink::WebFrame* frame, bool recursive) {
303 std::string result = DumpFrameHeaderIfNeeded(frame);
304 result.append(frame->contentAsMarkup().utf8());
305 result.append("\n");
307 if (recursive) {
308 for (blink::WebFrame* child = frame->firstChild(); child;
309 child = child->nextSibling())
310 result.append(DumpFramesAsMarkup(child, recursive));
313 return result;
316 std::string DumpDocumentText(blink::WebFrame* frame) {
317 return frame->document().contentAsTextForTesting().utf8();
320 std::string DumpFramesAsText(blink::WebFrame* frame, bool recursive) {
321 std::string result = DumpFrameHeaderIfNeeded(frame);
322 result.append(DumpDocumentText(frame));
323 result.append("\n");
325 if (recursive) {
326 for (blink::WebFrame* child = frame->firstChild(); child;
327 child = child->nextSibling())
328 result.append(DumpFramesAsText(child, recursive));
331 return result;
334 std::string DumpFramesAsPrintedText(blink::WebFrame* frame, bool recursive) {
335 // Cannot do printed format for anything other than HTML
336 if (!frame->document().isHTMLDocument())
337 return std::string();
339 std::string result = DumpFrameHeaderIfNeeded(frame);
340 result.append(
341 frame->layoutTreeAsText(blink::WebFrame::LayoutAsTextPrinting).utf8());
342 result.append("\n");
344 if (recursive) {
345 for (blink::WebFrame* child = frame->firstChild(); child;
346 child = child->nextSibling())
347 result.append(DumpFramesAsPrintedText(child, recursive));
350 return result;
353 std::string DumpFrameScrollPosition(blink::WebFrame* frame, bool recursive) {
354 std::string result;
355 blink::WebSize offset = frame->scrollOffset();
356 if (offset.width > 0 || offset.height > 0) {
357 if (frame->parent()) {
358 result =
359 std::string("frame '") + frame->uniqueName().utf8().data() + "' ";
361 base::StringAppendF(
362 &result, "scrolled to %d,%d\n", offset.width, offset.height);
365 if (!recursive)
366 return result;
367 for (blink::WebFrame* child = frame->firstChild(); child;
368 child = child->nextSibling())
369 result += DumpFrameScrollPosition(child, recursive);
370 return result;
373 std::string DumpAllBackForwardLists(TestInterfaces* interfaces,
374 WebTestDelegate* delegate) {
375 std::string result;
376 const std::vector<WebTestProxyBase*>& window_list =
377 interfaces->GetWindowList();
378 for (size_t i = 0; i < window_list.size(); ++i)
379 result.append(delegate->DumpHistoryForWindow(window_list.at(i)));
380 return result;
384 WebTestProxyBase::WebTestProxyBase()
385 : web_test_interfaces_(NULL),
386 test_interfaces_(NULL),
387 delegate_(NULL),
388 web_widget_(NULL),
389 spellcheck_(new SpellCheckClient(this)),
390 chooser_count_(0) {
391 Reset();
394 WebTestProxyBase::~WebTestProxyBase() {
395 test_interfaces_->WindowClosed(this);
398 void WebTestProxyBase::SetInterfaces(WebTestInterfaces* interfaces) {
399 web_test_interfaces_ = interfaces;
400 test_interfaces_ = interfaces->GetTestInterfaces();
401 test_interfaces_->WindowOpened(this);
404 WebTestInterfaces* WebTestProxyBase::GetInterfaces() {
405 return web_test_interfaces_;
408 void WebTestProxyBase::SetDelegate(WebTestDelegate* delegate) {
409 delegate_ = delegate;
410 spellcheck_->SetDelegate(delegate);
411 if (speech_recognizer_.get())
412 speech_recognizer_->SetDelegate(delegate);
415 WebTestDelegate* WebTestProxyBase::GetDelegate() {
416 return delegate_;
419 blink::WebView* WebTestProxyBase::GetWebView() const {
420 DCHECK(web_widget_);
421 // TestRunner does not support popup widgets. So |web_widget|_ is always a
422 // WebView.
423 return static_cast<blink::WebView*>(web_widget_);
426 void WebTestProxyBase::Reset() {
427 drag_image_.reset();
428 animate_scheduled_ = false;
429 resource_identifier_map_.clear();
430 log_console_output_ = true;
431 accept_languages_ = "";
434 blink::WebSpellCheckClient* WebTestProxyBase::GetSpellCheckClient() const {
435 return spellcheck_.get();
438 blink::WebColorChooser* WebTestProxyBase::CreateColorChooser(
439 blink::WebColorChooserClient* client,
440 const blink::WebColor& color,
441 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
442 // This instance is deleted by WebCore::ColorInputType
443 return new MockColorChooser(client, delegate_, this);
446 bool WebTestProxyBase::RunFileChooser(
447 const blink::WebFileChooserParams& params,
448 blink::WebFileChooserCompletion* completion) {
449 delegate_->PrintMessage("Mock: Opening a file chooser.\n");
450 // FIXME: Add ability to set file names to a file upload control.
451 return false;
454 void WebTestProxyBase::ShowValidationMessage(
455 const blink::WebString& main_message,
456 blink::WebTextDirection main_message_hint,
457 const blink::WebString& sub_message,
458 blink::WebTextDirection sub_message_hint) {
459 base::string16 wrapped_main_text = main_message;
460 base::string16 wrapped_sub_text = sub_message;
462 if (main_message_hint == blink::WebTextDirectionLeftToRight) {
463 wrapped_main_text =
464 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_main_text);
465 } else if (main_message_hint == blink::WebTextDirectionRightToLeft &&
466 !base::i18n::IsRTL()) {
467 base::i18n::WrapStringWithRTLFormatting(&wrapped_main_text);
470 if (!wrapped_sub_text.empty()) {
471 if (sub_message_hint == blink::WebTextDirectionLeftToRight) {
472 wrapped_sub_text =
473 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_sub_text);
474 } else if (sub_message_hint == blink::WebTextDirectionRightToLeft) {
475 base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text);
478 delegate_->PrintMessage("ValidationMessageClient: main-message=" +
479 base::UTF16ToUTF8(wrapped_main_text) +
480 " sub-message=" +
481 base::UTF16ToUTF8(wrapped_sub_text) + "\n");
484 std::string WebTestProxyBase::CaptureTree(
485 bool debug_render_tree,
486 bool dump_line_box_trees) {
487 bool should_dump_custom_text =
488 test_interfaces_->GetTestRunner()->shouldDumpAsCustomText();
489 bool should_dump_as_text =
490 test_interfaces_->GetTestRunner()->shouldDumpAsText();
491 bool should_dump_as_markup =
492 test_interfaces_->GetTestRunner()->shouldDumpAsMarkup();
493 bool should_dump_as_printed = test_interfaces_->GetTestRunner()->isPrinting();
494 blink::WebFrame* frame = GetWebView()->mainFrame();
495 std::string data_utf8;
496 if (should_dump_custom_text) {
497 // Append a newline for the test driver.
498 data_utf8 = test_interfaces_->GetTestRunner()->customDumpText() + "\n";
499 } else if (should_dump_as_text) {
500 bool recursive =
501 test_interfaces_->GetTestRunner()->shouldDumpChildFramesAsText();
502 data_utf8 = should_dump_as_printed ?
503 DumpFramesAsPrintedText(frame, recursive) :
504 DumpFramesAsText(frame, recursive);
505 } else if (should_dump_as_markup) {
506 bool recursive =
507 test_interfaces_->GetTestRunner()->shouldDumpChildFramesAsMarkup();
508 // Append a newline for the test driver.
509 data_utf8 = DumpFramesAsMarkup(frame, recursive);
510 } else {
511 bool recursive = test_interfaces_->GetTestRunner()
512 ->shouldDumpChildFrameScrollPositions();
513 blink::WebFrame::LayoutAsTextControls layout_text_behavior =
514 blink::WebFrame::LayoutAsTextNormal;
515 if (should_dump_as_printed)
516 layout_text_behavior |= blink::WebFrame::LayoutAsTextPrinting;
517 if (debug_render_tree)
518 layout_text_behavior |= blink::WebFrame::LayoutAsTextDebug;
519 if (dump_line_box_trees)
520 layout_text_behavior |= blink::WebFrame::LayoutAsTextWithLineTrees;
521 data_utf8 = frame->layoutTreeAsText(layout_text_behavior).utf8();
522 data_utf8 += DumpFrameScrollPosition(frame, recursive);
525 if (test_interfaces_->GetTestRunner()->ShouldDumpBackForwardList())
526 data_utf8 += DumpAllBackForwardLists(test_interfaces_, delegate_);
528 return data_utf8;
531 void WebTestProxyBase::DrawSelectionRect(SkCanvas* canvas) {
532 // See if we need to draw the selection bounds rect. Selection bounds
533 // rect is the rect enclosing the (possibly transformed) selection.
534 // The rect should be drawn after everything is laid out and painted.
535 if (!test_interfaces_->GetTestRunner()->shouldDumpSelectionRect())
536 return;
537 // If there is a selection rect - draw a red 1px border enclosing rect
538 blink::WebRect wr = GetWebView()->mainFrame()->selectionBoundsRect();
539 if (wr.isEmpty())
540 return;
541 // Render a red rectangle bounding selection rect
542 SkPaint paint;
543 paint.setColor(0xFFFF0000); // Fully opaque red
544 paint.setStyle(SkPaint::kStroke_Style);
545 paint.setFlags(SkPaint::kAntiAlias_Flag);
546 paint.setStrokeWidth(1.0f);
547 SkIRect rect; // Bounding rect
548 rect.set(wr.x, wr.y, wr.x + wr.width, wr.y + wr.height);
549 canvas->drawIRect(rect, paint);
552 void WebTestProxyBase::SetAcceptLanguages(const std::string& accept_languages) {
553 bool notify = accept_languages_ != accept_languages;
554 accept_languages_ = accept_languages;
556 if (notify)
557 GetWebView()->acceptLanguagesChanged();
560 void WebTestProxyBase::CopyImageAtAndCapturePixels(
561 int x, int y, const base::Callback<void(const SkBitmap&)>& callback) {
562 DCHECK(!callback.is_null());
563 uint64_t sequence_number = blink::Platform::current()->clipboard()->
564 sequenceNumber(blink::WebClipboard::Buffer());
565 GetWebView()->copyImageAt(blink::WebPoint(x, y));
566 if (sequence_number == blink::Platform::current()->clipboard()->
567 sequenceNumber(blink::WebClipboard::Buffer())) {
568 SkBitmap emptyBitmap;
569 callback.Run(emptyBitmap);
570 return;
573 blink::WebData data = blink::Platform::current()->clipboard()->readImage(
574 blink::WebClipboard::Buffer());
575 blink::WebImage image = blink::WebImage::fromData(data, blink::WebSize());
576 const SkBitmap& bitmap = image.getSkBitmap();
577 SkAutoLockPixels autoLock(bitmap);
578 callback.Run(bitmap);
581 void WebTestProxyBase::CapturePixelsForPrinting(
582 const base::Callback<void(const SkBitmap&)>& callback) {
583 web_widget_->layout();
585 blink::WebSize page_size_in_pixels = web_widget_->size();
586 blink::WebFrame* web_frame = GetWebView()->mainFrame();
588 int page_count = web_frame->printBegin(page_size_in_pixels);
589 int totalHeight = page_count * (page_size_in_pixels.height + 1) - 1;
591 bool is_opaque = false;
592 skia::RefPtr<SkCanvas> canvas(skia::AdoptRef(skia::TryCreateBitmapCanvas(
593 page_size_in_pixels.width, totalHeight, is_opaque)));
594 if (!canvas) {
595 callback.Run(SkBitmap());
596 return;
598 web_frame->printPagesWithBoundaries(canvas.get(), page_size_in_pixels);
599 web_frame->printEnd();
601 DrawSelectionRect(canvas.get());
602 SkBaseDevice* device = skia::GetTopDevice(*canvas);
603 const SkBitmap& bitmap = device->accessBitmap(false);
604 callback.Run(bitmap);
607 CaptureCallback::CaptureCallback(
608 const base::Callback<void(const SkBitmap&)>& callback)
609 : callback_(callback), wait_for_popup_(false) {
612 CaptureCallback::~CaptureCallback() {
615 void CaptureCallback::didCompositeAndReadback(const SkBitmap& bitmap) {
616 TRACE_EVENT2("shell",
617 "CaptureCallback::didCompositeAndReadback",
618 "x",
619 bitmap.info().width(),
620 "y",
621 bitmap.info().height());
622 if (!wait_for_popup_) {
623 callback_.Run(bitmap);
624 delete this;
625 return;
627 if (main_bitmap_.isNull()) {
628 bitmap.deepCopyTo(&main_bitmap_);
629 return;
631 SkCanvas canvas(main_bitmap_);
632 canvas.drawBitmap(bitmap, popup_position_.x(), popup_position_.y());
633 callback_.Run(main_bitmap_);
634 delete this;
637 void WebTestProxyBase::CapturePixelsAsync(
638 const base::Callback<void(const SkBitmap&)>& callback) {
639 TRACE_EVENT0("shell", "WebTestProxyBase::CapturePixelsAsync");
640 DCHECK(!callback.is_null());
642 if (test_interfaces_->GetTestRunner()->shouldDumpDragImage()) {
643 if (drag_image_.isNull()) {
644 // This means the test called dumpDragImage but did not initiate a drag.
645 // Return a blank image so that the test fails.
646 SkBitmap bitmap;
647 bitmap.allocN32Pixels(1, 1);
649 SkAutoLockPixels lock(bitmap);
650 bitmap.eraseColor(0);
652 callback.Run(bitmap);
653 return;
656 callback.Run(drag_image_.getSkBitmap());
657 return;
660 if (test_interfaces_->GetTestRunner()->isPrinting()) {
661 base::ThreadTaskRunnerHandle::Get()->PostTask(
662 FROM_HERE, base::Bind(&WebTestProxyBase::CapturePixelsForPrinting,
663 base::Unretained(this), callback));
664 return;
667 CaptureCallback* capture_callback = new CaptureCallback(base::Bind(
668 &WebTestProxyBase::DidCapturePixelsAsync, base::Unretained(this),
669 callback));
670 web_widget_->compositeAndReadbackAsync(capture_callback);
671 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
672 capture_callback->set_wait_for_popup(true);
673 capture_callback->set_popup_position(popup->positionRelativeToOwner());
674 popup->compositeAndReadbackAsync(capture_callback);
678 void WebTestProxyBase::DidCapturePixelsAsync(
679 const base::Callback<void(const SkBitmap&)>& callback,
680 const SkBitmap& bitmap) {
681 SkCanvas canvas(bitmap);
682 DrawSelectionRect(&canvas);
683 if (!callback.is_null())
684 callback.Run(bitmap);
687 void WebTestProxyBase::SetLogConsoleOutput(bool enabled) {
688 log_console_output_ = enabled;
691 void LayoutAndPaintCallback::didLayoutAndPaint() {
692 TRACE_EVENT0("shell", "LayoutAndPaintCallback::didLayoutAndPaint");
693 if (wait_for_popup_) {
694 wait_for_popup_ = false;
695 return;
698 if (!callback_.is_null())
699 callback_.Run();
700 delete this;
703 void WebTestProxyBase::LayoutAndPaintAsyncThen(const base::Closure& callback) {
704 TRACE_EVENT0("shell", "WebTestProxyBase::LayoutAndPaintAsyncThen");
706 LayoutAndPaintCallback* layout_and_paint_callback =
707 new LayoutAndPaintCallback(callback);
708 web_widget_->layoutAndPaintAsync(layout_and_paint_callback);
709 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
710 layout_and_paint_callback->set_wait_for_popup(true);
711 popup->layoutAndPaintAsync(layout_and_paint_callback);
715 void WebTestProxyBase::GetScreenOrientationForTesting(
716 blink::WebScreenInfo& screen_info) {
717 if (!screen_orientation_client_)
718 return;
719 // Override screen orientation information with mock data.
720 screen_info.orientationType =
721 screen_orientation_client_->CurrentOrientationType();
722 screen_info.orientationAngle =
723 screen_orientation_client_->CurrentOrientationAngle();
726 MockScreenOrientationClient*
727 WebTestProxyBase::GetScreenOrientationClientMock() {
728 if (!screen_orientation_client_.get()) {
729 screen_orientation_client_.reset(new MockScreenOrientationClient);
731 return screen_orientation_client_.get();
734 MockWebSpeechRecognizer* WebTestProxyBase::GetSpeechRecognizerMock() {
735 if (!speech_recognizer_.get()) {
736 speech_recognizer_.reset(new MockWebSpeechRecognizer());
737 speech_recognizer_->SetDelegate(delegate_);
739 return speech_recognizer_.get();
742 MockCredentialManagerClient*
743 WebTestProxyBase::GetCredentialManagerClientMock() {
744 if (!credential_manager_client_.get())
745 credential_manager_client_.reset(new MockCredentialManagerClient());
746 return credential_manager_client_.get();
749 void WebTestProxyBase::ScheduleAnimation() {
750 if (!test_interfaces_->GetTestRunner()->TestIsRunning())
751 return;
753 if (!animate_scheduled_) {
754 animate_scheduled_ = true;
755 delegate_->PostDelayedTask(
756 new HostMethodTask(this, &WebTestProxyBase::AnimateNow), 1);
760 void WebTestProxyBase::AnimateNow() {
761 if (animate_scheduled_) {
762 base::TimeDelta animate_time = base::TimeTicks::Now() - base::TimeTicks();
763 base::TimeDelta interval = base::TimeDelta::FromMicroseconds(16666);
764 blink::WebBeginFrameArgs args(animate_time.InSecondsF(),
765 (animate_time + interval).InSecondsF(),
766 interval.InSecondsF());
768 animate_scheduled_ = false;
769 web_widget_->beginFrame(args);
770 web_widget_->layout();
771 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
772 popup->beginFrame(args);
773 popup->layout();
778 void WebTestProxyBase::PostAccessibilityEvent(const blink::WebAXObject& obj,
779 blink::WebAXEvent event) {
780 // Only hook the accessibility events occured during the test run.
781 // This check prevents false positives in WebLeakDetector.
782 // The pending tasks in browser/renderer message queue may trigger
783 // accessibility events,
784 // and AccessibilityController will hold on to their target nodes if we don't
785 // ignore them here.
786 if (!test_interfaces_->GetTestRunner()->TestIsRunning())
787 return;
789 if (event == blink::WebAXEventFocus)
790 test_interfaces_->GetAccessibilityController()->SetFocusedElement(obj);
792 const char* event_name = NULL;
793 switch (event) {
794 case blink::WebAXEventActiveDescendantChanged:
795 event_name = "ActiveDescendantChanged";
796 break;
797 case blink::WebAXEventAlert:
798 event_name = "Alert";
799 break;
800 case blink::WebAXEventAriaAttributeChanged:
801 event_name = "AriaAttributeChanged";
802 break;
803 case blink::WebAXEventAutocorrectionOccured:
804 event_name = "AutocorrectionOccured";
805 break;
806 case blink::WebAXEventBlur:
807 event_name = "Blur";
808 break;
809 case blink::WebAXEventCheckedStateChanged:
810 event_name = "CheckedStateChanged";
811 break;
812 case blink::WebAXEventChildrenChanged:
813 event_name = "ChildrenChanged";
814 break;
815 case blink::WebAXEventFocus:
816 event_name = "Focus";
817 break;
818 case blink::WebAXEventHide:
819 event_name = "Hide";
820 break;
821 case blink::WebAXEventInvalidStatusChanged:
822 event_name = "InvalidStatusChanged";
823 break;
824 case blink::WebAXEventLayoutComplete:
825 event_name = "LayoutComplete";
826 break;
827 case blink::WebAXEventLiveRegionChanged:
828 event_name = "LiveRegionChanged";
829 break;
830 case blink::WebAXEventLoadComplete:
831 event_name = "LoadComplete";
832 break;
833 case blink::WebAXEventLocationChanged:
834 event_name = "LocationChanged";
835 break;
836 case blink::WebAXEventMenuListItemSelected:
837 event_name = "MenuListItemSelected";
838 break;
839 case blink::WebAXEventMenuListItemUnselected:
840 event_name = "MenuListItemUnselected";
841 break;
842 case blink::WebAXEventMenuListValueChanged:
843 event_name = "MenuListValueChanged";
844 break;
845 case blink::WebAXEventRowCollapsed:
846 event_name = "RowCollapsed";
847 break;
848 case blink::WebAXEventRowCountChanged:
849 event_name = "RowCountChanged";
850 break;
851 case blink::WebAXEventRowExpanded:
852 event_name = "RowExpanded";
853 break;
854 case blink::WebAXEventScrollPositionChanged:
855 event_name = "ScrollPositionChanged";
856 break;
857 case blink::WebAXEventScrolledToAnchor:
858 event_name = "ScrolledToAnchor";
859 break;
860 case blink::WebAXEventSelectedChildrenChanged:
861 event_name = "SelectedChildrenChanged";
862 break;
863 case blink::WebAXEventSelectedTextChanged:
864 event_name = "SelectedTextChanged";
865 break;
866 case blink::WebAXEventShow:
867 event_name = "Show";
868 break;
869 case blink::WebAXEventTextChanged:
870 event_name = "TextChanged";
871 break;
872 case blink::WebAXEventTextInserted:
873 event_name = "TextInserted";
874 break;
875 case blink::WebAXEventTextRemoved:
876 event_name = "TextRemoved";
877 break;
878 case blink::WebAXEventValueChanged:
879 event_name = "ValueChanged";
880 break;
881 default:
882 event_name = "Unknown";
883 break;
886 test_interfaces_->GetAccessibilityController()->NotificationReceived(
887 obj, event_name);
889 if (test_interfaces_->GetAccessibilityController()
890 ->ShouldLogAccessibilityEvents()) {
891 std::string message("AccessibilityNotification - ");
892 message += event_name;
894 blink::WebNode node = obj.node();
895 if (!node.isNull() && node.isElementNode()) {
896 blink::WebElement element = node.to<blink::WebElement>();
897 if (element.hasAttribute("id")) {
898 message += " - id:";
899 message += element.getAttribute("id").utf8().data();
903 delegate_->PrintMessage(message + "\n");
907 void WebTestProxyBase::StartDragging(blink::WebLocalFrame* frame,
908 const blink::WebDragData& data,
909 blink::WebDragOperationsMask mask,
910 const blink::WebImage& image,
911 const blink::WebPoint& point) {
912 if (test_interfaces_->GetTestRunner()->shouldDumpDragImage()) {
913 if (drag_image_.isNull())
914 drag_image_ = image;
916 // When running a test, we need to fake a drag drop operation otherwise
917 // Windows waits for real mouse events to know when the drag is over.
918 test_interfaces_->GetEventSender()->DoDragDrop(data, mask);
921 // The output from these methods in layout test mode should match that
922 // expected by the layout tests. See EditingDelegate.m in DumpRenderTree.
924 void WebTestProxyBase::DidChangeSelection(bool is_empty_callback) {
925 if (test_interfaces_->GetTestRunner()->shouldDumpEditingCallbacks())
926 delegate_->PrintMessage(
927 "EDITING DELEGATE: "
928 "webViewDidChangeSelection:WebViewDidChangeSelectionNotification\n");
931 void WebTestProxyBase::DidChangeContents() {
932 if (test_interfaces_->GetTestRunner()->shouldDumpEditingCallbacks())
933 delegate_->PrintMessage(
934 "EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification\n");
937 bool WebTestProxyBase::CreateView(blink::WebLocalFrame* frame,
938 const blink::WebURLRequest& request,
939 const blink::WebWindowFeatures& features,
940 const blink::WebString& frame_name,
941 blink::WebNavigationPolicy policy,
942 bool suppress_opener) {
943 if (test_interfaces_->GetTestRunner()->shouldDumpNavigationPolicy()) {
944 delegate_->PrintMessage("Default policy for createView for '" +
945 URLDescription(request.url()) + "' is '" +
946 WebNavigationPolicyToString(policy) + "'\n");
949 if (!test_interfaces_->GetTestRunner()->canOpenWindows())
950 return false;
951 if (test_interfaces_->GetTestRunner()->shouldDumpCreateView())
952 delegate_->PrintMessage(std::string("createView(") +
953 URLDescription(request.url()) + ")\n");
954 return true;
957 blink::WebPlugin* WebTestProxyBase::CreatePlugin(
958 blink::WebLocalFrame* frame,
959 const blink::WebPluginParams& params) {
960 if (TestPlugin::IsSupportedMimeType(params.mimeType))
961 return TestPlugin::create(frame, params, delegate_);
962 return delegate_->CreatePluginPlaceholder(frame, params);
965 void WebTestProxyBase::SetStatusText(const blink::WebString& text) {
966 if (!test_interfaces_->GetTestRunner()->shouldDumpStatusCallbacks())
967 return;
968 delegate_->PrintMessage(
969 std::string("UI DELEGATE STATUS CALLBACK: setStatusText:") +
970 text.utf8().data() + "\n");
973 void WebTestProxyBase::DidStopLoading() {
974 if (test_interfaces_->GetTestRunner()->shouldDumpProgressFinishedCallback())
975 delegate_->PrintMessage("postProgressFinishedNotification\n");
978 void WebTestProxyBase::ShowContextMenu(
979 const blink::WebContextMenuData& context_menu_data) {
980 test_interfaces_->GetEventSender()->SetContextMenuData(context_menu_data);
983 blink::WebUserMediaClient* WebTestProxyBase::GetUserMediaClient() {
984 if (!user_media_client_.get())
985 user_media_client_.reset(new MockWebUserMediaClient(delegate_));
986 return user_media_client_.get();
989 // Simulate a print by going into print mode and then exit straight away.
990 void WebTestProxyBase::PrintPage(blink::WebLocalFrame* frame) {
991 blink::WebSize page_size_in_pixels = web_widget_->size();
992 if (page_size_in_pixels.isEmpty())
993 return;
994 blink::WebPrintParams printParams(page_size_in_pixels);
995 frame->printBegin(printParams);
996 frame->printEnd();
999 blink::WebSpeechRecognizer* WebTestProxyBase::GetSpeechRecognizer() {
1000 return GetSpeechRecognizerMock();
1003 bool WebTestProxyBase::RequestPointerLock() {
1004 return test_interfaces_->GetTestRunner()->RequestPointerLock();
1007 void WebTestProxyBase::RequestPointerUnlock() {
1008 test_interfaces_->GetTestRunner()->RequestPointerUnlock();
1011 bool WebTestProxyBase::IsPointerLocked() {
1012 return test_interfaces_->GetTestRunner()->isPointerLocked();
1015 void WebTestProxyBase::DidFocus() {
1016 delegate_->SetFocus(this, true);
1019 void WebTestProxyBase::DidBlur() {
1020 delegate_->SetFocus(this, false);
1023 void WebTestProxyBase::SetToolTipText(const blink::WebString& text,
1024 blink::WebTextDirection direction) {
1025 test_interfaces_->GetTestRunner()->setToolTipText(text);
1028 void WebTestProxyBase::DidOpenChooser() {
1029 chooser_count_++;
1032 void WebTestProxyBase::DidCloseChooser() {
1033 chooser_count_--;
1036 bool WebTestProxyBase::IsChooserShown() {
1037 return 0 < chooser_count_;
1040 void WebTestProxyBase::LoadURLExternally(
1041 blink::WebLocalFrame* frame,
1042 const blink::WebURLRequest& request,
1043 blink::WebNavigationPolicy policy,
1044 const blink::WebString& suggested_name) {
1045 if (test_interfaces_->GetTestRunner()->shouldWaitUntilExternalURLLoad()) {
1046 if (policy == blink::WebNavigationPolicyDownload) {
1047 delegate_->PrintMessage(
1048 std::string("Downloading URL with suggested filename \"") +
1049 suggested_name.utf8() + "\"\n");
1050 } else {
1051 delegate_->PrintMessage(std::string("Loading URL externally - \"") +
1052 URLDescription(request.url()) + "\"\n");
1054 delegate_->TestFinished();
1058 void WebTestProxyBase::DidStartProvisionalLoad(blink::WebLocalFrame* frame) {
1059 if (!test_interfaces_->GetTestRunner()->topLoadingFrame())
1060 test_interfaces_->GetTestRunner()->setTopLoadingFrame(frame, false);
1062 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1063 PrintFrameDescription(delegate_, frame);
1064 delegate_->PrintMessage(" - didStartProvisionalLoadForFrame\n");
1067 if (test_interfaces_->GetTestRunner()
1068 ->shouldDumpUserGestureInFrameLoadCallbacks()) {
1069 PrintFrameuserGestureStatus(
1070 delegate_, frame, " - in didStartProvisionalLoadForFrame\n");
1074 void WebTestProxyBase::DidReceiveServerRedirectForProvisionalLoad(
1075 blink::WebLocalFrame* frame) {
1076 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1077 PrintFrameDescription(delegate_, frame);
1078 delegate_->PrintMessage(
1079 " - didReceiveServerRedirectForProvisionalLoadForFrame\n");
1083 bool WebTestProxyBase::DidFailProvisionalLoad(
1084 blink::WebLocalFrame* frame,
1085 const blink::WebURLError& error,
1086 blink::WebHistoryCommitType commit_type) {
1087 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1088 PrintFrameDescription(delegate_, frame);
1089 delegate_->PrintMessage(" - didFailProvisionalLoadWithError\n");
1091 CheckDone(frame, MainResourceLoadFailed);
1092 return !frame->provisionalDataSource();
1095 void WebTestProxyBase::DidCommitProvisionalLoad(
1096 blink::WebLocalFrame* frame,
1097 const blink::WebHistoryItem& history_item,
1098 blink::WebHistoryCommitType history_type) {
1099 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1100 PrintFrameDescription(delegate_, frame);
1101 delegate_->PrintMessage(" - didCommitLoadForFrame\n");
1105 void WebTestProxyBase::DidReceiveTitle(blink::WebLocalFrame* frame,
1106 const blink::WebString& title,
1107 blink::WebTextDirection direction) {
1108 blink::WebCString title8 = title.utf8();
1110 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1111 PrintFrameDescription(delegate_, frame);
1112 delegate_->PrintMessage(std::string(" - didReceiveTitle: ") +
1113 title8.data() + "\n");
1116 if (test_interfaces_->GetTestRunner()->shouldDumpTitleChanges())
1117 delegate_->PrintMessage(std::string("TITLE CHANGED: '") + title8.data() +
1118 "'\n");
1121 void WebTestProxyBase::DidChangeIcon(blink::WebLocalFrame* frame,
1122 blink::WebIconURL::Type icon_type) {
1123 if (test_interfaces_->GetTestRunner()->shouldDumpIconChanges()) {
1124 PrintFrameDescription(delegate_, frame);
1125 delegate_->PrintMessage(std::string(" - didChangeIcons\n"));
1129 void WebTestProxyBase::DidFinishDocumentLoad(blink::WebLocalFrame* frame) {
1130 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1131 PrintFrameDescription(delegate_, frame);
1132 delegate_->PrintMessage(" - didFinishDocumentLoadForFrame\n");
1136 void WebTestProxyBase::DidHandleOnloadEvents(blink::WebLocalFrame* frame) {
1137 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1138 PrintFrameDescription(delegate_, frame);
1139 delegate_->PrintMessage(" - didHandleOnloadEventsForFrame\n");
1143 void WebTestProxyBase::DidFailLoad(blink::WebLocalFrame* frame,
1144 const blink::WebURLError& error,
1145 blink::WebHistoryCommitType commit_type) {
1146 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1147 PrintFrameDescription(delegate_, frame);
1148 delegate_->PrintMessage(" - didFailLoadWithError\n");
1150 CheckDone(frame, MainResourceLoadFailed);
1153 void WebTestProxyBase::DidFinishLoad(blink::WebLocalFrame* frame) {
1154 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1155 PrintFrameDescription(delegate_, frame);
1156 delegate_->PrintMessage(" - didFinishLoadForFrame\n");
1158 CheckDone(frame, LoadFinished);
1161 void WebTestProxyBase::DidDetectXSS(blink::WebLocalFrame* frame,
1162 const blink::WebURL& insecure_url,
1163 bool did_block_entire_page) {
1164 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks())
1165 delegate_->PrintMessage("didDetectXSS\n");
1168 void WebTestProxyBase::DidDispatchPingLoader(blink::WebLocalFrame* frame,
1169 const blink::WebURL& url) {
1170 if (test_interfaces_->GetTestRunner()->shouldDumpPingLoaderCallbacks())
1171 delegate_->PrintMessage(std::string("PingLoader dispatched to '") +
1172 URLDescription(url).c_str() + "'.\n");
1175 void WebTestProxyBase::WillRequestResource(
1176 blink::WebLocalFrame* frame,
1177 const blink::WebCachedURLRequest& request) {
1178 if (test_interfaces_->GetTestRunner()->shouldDumpResourceRequestCallbacks()) {
1179 PrintFrameDescription(delegate_, frame);
1180 delegate_->PrintMessage(std::string(" - ") +
1181 request.initiatorName().utf8().data());
1182 delegate_->PrintMessage(std::string(" requested '") +
1183 URLDescription(request.urlRequest().url()).c_str() +
1184 "'\n");
1188 void WebTestProxyBase::WillSendRequest(
1189 blink::WebLocalFrame* frame,
1190 unsigned identifier,
1191 blink::WebURLRequest& request,
1192 const blink::WebURLResponse& redirect_response) {
1193 // Need to use GURL for host() and SchemeIs()
1194 GURL url = request.url();
1195 std::string request_url = url.possibly_invalid_spec();
1197 GURL main_document_url = request.firstPartyForCookies();
1199 if (redirect_response.isNull() &&
1200 (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks() ||
1201 test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities())) {
1202 DCHECK(resource_identifier_map_.find(identifier) ==
1203 resource_identifier_map_.end());
1204 resource_identifier_map_[identifier] =
1205 DescriptionSuitableForTestResult(request_url);
1208 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1209 if (resource_identifier_map_.find(identifier) ==
1210 resource_identifier_map_.end())
1211 delegate_->PrintMessage("<unknown>");
1212 else
1213 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1214 delegate_->PrintMessage(" - willSendRequest <NSURLRequest URL ");
1215 delegate_->PrintMessage(
1216 DescriptionSuitableForTestResult(request_url).c_str());
1217 delegate_->PrintMessage(", main document URL ");
1218 delegate_->PrintMessage(URLDescription(main_document_url).c_str());
1219 delegate_->PrintMessage(", http method ");
1220 delegate_->PrintMessage(request.httpMethod().utf8().data());
1221 delegate_->PrintMessage("> redirectResponse ");
1222 PrintResponseDescription(delegate_, redirect_response);
1223 delegate_->PrintMessage("\n");
1226 if (test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities()) {
1227 delegate_->PrintMessage(
1228 DescriptionSuitableForTestResult(request_url).c_str());
1229 delegate_->PrintMessage(" has priority ");
1230 delegate_->PrintMessage(PriorityDescription(request.priority()));
1231 delegate_->PrintMessage("\n");
1234 if (test_interfaces_->GetTestRunner()->httpHeadersToClear()) {
1235 const std::set<std::string>* clearHeaders =
1236 test_interfaces_->GetTestRunner()->httpHeadersToClear();
1237 for (std::set<std::string>::const_iterator header = clearHeaders->begin();
1238 header != clearHeaders->end();
1239 ++header)
1240 request.clearHTTPHeaderField(blink::WebString::fromUTF8(*header));
1243 std::string host = url.host();
1244 if (!host.empty() &&
1245 (url.SchemeIs(url::kHttpScheme) || url.SchemeIs(url::kHttpsScheme))) {
1246 if (!IsLocalHost(host) && !IsTestHost(host) &&
1247 !HostIsUsedBySomeTestsToGenerateError(host) &&
1248 ((!main_document_url.SchemeIs(url::kHttpScheme) &&
1249 !main_document_url.SchemeIs(url::kHttpsScheme)) ||
1250 IsLocalHost(main_document_url.host())) &&
1251 !delegate_->AllowExternalPages()) {
1252 delegate_->PrintMessage(std::string("Blocked access to external URL ") +
1253 request_url + "\n");
1254 BlockRequest(request);
1255 return;
1259 // Set the new substituted URL.
1260 request.setURL(delegate_->RewriteLayoutTestsURL(request.url().spec()));
1263 void WebTestProxyBase::DidReceiveResponse(
1264 blink::WebLocalFrame* frame,
1265 unsigned identifier,
1266 const blink::WebURLResponse& response) {
1267 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1268 if (resource_identifier_map_.find(identifier) ==
1269 resource_identifier_map_.end())
1270 delegate_->PrintMessage("<unknown>");
1271 else
1272 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1273 delegate_->PrintMessage(" - didReceiveResponse ");
1274 PrintResponseDescription(delegate_, response);
1275 delegate_->PrintMessage("\n");
1277 if (test_interfaces_->GetTestRunner()
1278 ->shouldDumpResourceResponseMIMETypes()) {
1279 GURL url = response.url();
1280 blink::WebString mime_type = response.mimeType();
1281 delegate_->PrintMessage(url.ExtractFileName());
1282 delegate_->PrintMessage(" has MIME type ");
1283 // Simulate NSURLResponse's mapping of empty/unknown MIME types to
1284 // application/octet-stream
1285 delegate_->PrintMessage(mime_type.isEmpty() ? "application/octet-stream"
1286 : mime_type.utf8().data());
1287 delegate_->PrintMessage("\n");
1291 void WebTestProxyBase::DidChangeResourcePriority(
1292 blink::WebLocalFrame* frame,
1293 unsigned identifier,
1294 const blink::WebURLRequest::Priority& priority,
1295 int intra_priority_value) {
1296 if (test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities()) {
1297 if (resource_identifier_map_.find(identifier) ==
1298 resource_identifier_map_.end())
1299 delegate_->PrintMessage("<unknown>");
1300 else
1301 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1302 delegate_->PrintMessage(
1303 base::StringPrintf(" changed priority to %s, intra_priority %d\n",
1304 PriorityDescription(priority).c_str(),
1305 intra_priority_value));
1309 void WebTestProxyBase::DidFinishResourceLoad(blink::WebLocalFrame* frame,
1310 unsigned identifier) {
1311 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1312 if (resource_identifier_map_.find(identifier) ==
1313 resource_identifier_map_.end())
1314 delegate_->PrintMessage("<unknown>");
1315 else
1316 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1317 delegate_->PrintMessage(" - didFinishLoading\n");
1319 resource_identifier_map_.erase(identifier);
1320 CheckDone(frame, ResourceLoadCompleted);
1323 void WebTestProxyBase::DidAddMessageToConsole(
1324 const blink::WebConsoleMessage& message,
1325 const blink::WebString& source_name,
1326 unsigned source_line) {
1327 // This matches win DumpRenderTree's UIDelegate.cpp.
1328 if (!log_console_output_)
1329 return;
1330 std::string level;
1331 switch (message.level) {
1332 case blink::WebConsoleMessage::LevelDebug:
1333 level = "DEBUG";
1334 break;
1335 case blink::WebConsoleMessage::LevelLog:
1336 level = "MESSAGE";
1337 break;
1338 case blink::WebConsoleMessage::LevelInfo:
1339 level = "INFO";
1340 break;
1341 case blink::WebConsoleMessage::LevelWarning:
1342 level = "WARNING";
1343 break;
1344 case blink::WebConsoleMessage::LevelError:
1345 level = "ERROR";
1346 break;
1347 default:
1348 level = "MESSAGE";
1350 delegate_->PrintMessage(std::string("CONSOLE ") + level + ": ");
1351 if (source_line) {
1352 delegate_->PrintMessage(base::StringPrintf("line %d: ", source_line));
1354 if (!message.text.isEmpty()) {
1355 std::string new_message;
1356 new_message = message.text.utf8();
1357 size_t file_protocol = new_message.find("file://");
1358 if (file_protocol != std::string::npos) {
1359 new_message = new_message.substr(0, file_protocol) +
1360 URLSuitableForTestResult(new_message.substr(file_protocol));
1362 delegate_->PrintMessage(new_message);
1364 delegate_->PrintMessage(std::string("\n"));
1367 void WebTestProxyBase::CheckDone(blink::WebLocalFrame* frame,
1368 CheckDoneReason reason) {
1369 if (frame != test_interfaces_->GetTestRunner()->topLoadingFrame())
1370 return;
1371 if (reason != MainResourceLoadFailed &&
1372 (frame->isResourceLoadInProgress() || frame->isLoading()))
1373 return;
1374 test_interfaces_->GetTestRunner()->setTopLoadingFrame(frame, true);
1377 blink::WebNavigationPolicy WebTestProxyBase::DecidePolicyForNavigation(
1378 const blink::WebFrameClient::NavigationPolicyInfo& info) {
1379 if (test_interfaces_->GetTestRunner()->shouldDumpNavigationPolicy()) {
1380 delegate_->PrintMessage("Default policy for navigation to '" +
1381 URLDescription(info.urlRequest.url()) + "' is '" +
1382 WebNavigationPolicyToString(info.defaultPolicy) +
1383 "'\n");
1386 blink::WebNavigationPolicy result;
1387 if (!test_interfaces_->GetTestRunner()->policyDelegateEnabled())
1388 return info.defaultPolicy;
1390 delegate_->PrintMessage(
1391 std::string("Policy delegate: attempt to load ") +
1392 URLDescription(info.urlRequest.url()) + " with navigation type '" +
1393 WebNavigationTypeToString(info.navigationType) + "'\n");
1394 if (test_interfaces_->GetTestRunner()->policyDelegateIsPermissive())
1395 result = blink::WebNavigationPolicyCurrentTab;
1396 else
1397 result = blink::WebNavigationPolicyIgnore;
1399 if (test_interfaces_->GetTestRunner()->policyDelegateShouldNotifyDone()) {
1400 test_interfaces_->GetTestRunner()->policyDelegateDone();
1401 result = blink::WebNavigationPolicyIgnore;
1404 return result;
1407 bool WebTestProxyBase::WillCheckAndDispatchMessageEvent(
1408 blink::WebLocalFrame* source_frame,
1409 blink::WebFrame* target_frame,
1410 blink::WebSecurityOrigin target,
1411 blink::WebDOMMessageEvent event) {
1412 if (test_interfaces_->GetTestRunner()->shouldInterceptPostMessage()) {
1413 delegate_->PrintMessage("intercepted postMessage\n");
1414 return true;
1417 return false;
1420 void WebTestProxyBase::PostSpellCheckEvent(const blink::WebString& event_name) {
1421 if (test_interfaces_->GetTestRunner()->shouldDumpSpellCheckCallbacks()) {
1422 delegate_->PrintMessage(std::string("SpellCheckEvent: ") +
1423 event_name.utf8().data() + "\n");
1427 void WebTestProxyBase::ResetInputMethod() {
1428 // If a composition text exists, then we need to let the browser process
1429 // to cancel the input method's ongoing composition session.
1430 if (web_widget_)
1431 web_widget_->confirmComposition();
1434 blink::WebString WebTestProxyBase::acceptLanguages() {
1435 return blink::WebString::fromUTF8(accept_languages_);
1438 } // namespace test_runner