Revert of Revert of Update V8 to version 4.5.61. (patchset #1 id:1 of https://coderev...
[chromium-blink-merge.git] / components / test_runner / web_test_proxy.cc
blob7bc243c74b7bd64c7fcdd6a38adcba8ed10ed460
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/logging.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/thread_task_runner_handle.h"
16 #include "base/trace_event/trace_event.h"
17 #include "components/test_runner/accessibility_controller.h"
18 #include "components/test_runner/event_sender.h"
19 #include "components/test_runner/mock_color_chooser.h"
20 #include "components/test_runner/mock_credential_manager_client.h"
21 #include "components/test_runner/mock_screen_orientation_client.h"
22 #include "components/test_runner/mock_web_speech_recognizer.h"
23 #include "components/test_runner/mock_web_user_media_client.h"
24 #include "components/test_runner/spell_check_client.h"
25 #include "components/test_runner/test_interfaces.h"
26 #include "components/test_runner/test_plugin.h"
27 #include "components/test_runner/test_runner.h"
28 #include "components/test_runner/web_test_delegate.h"
29 #include "components/test_runner/web_test_interfaces.h"
30 #include "components/test_runner/web_test_runner.h"
31 // FIXME: Including platform_canvas.h here is a layering violation.
32 #include "skia/ext/platform_canvas.h"
33 #include "third_party/WebKit/public/platform/Platform.h"
34 #include "third_party/WebKit/public/platform/WebCString.h"
35 #include "third_party/WebKit/public/platform/WebClipboard.h"
36 #include "third_party/WebKit/public/platform/WebCompositeAndReadbackAsyncCallback.h"
37 #include "third_party/WebKit/public/platform/WebLayoutAndPaintAsyncCallback.h"
38 #include "third_party/WebKit/public/platform/WebURLError.h"
39 #include "third_party/WebKit/public/platform/WebURLRequest.h"
40 #include "third_party/WebKit/public/platform/WebURLResponse.h"
41 #include "third_party/WebKit/public/web/WebAXEnums.h"
42 #include "third_party/WebKit/public/web/WebAXObject.h"
43 #include "third_party/WebKit/public/web/WebCachedURLRequest.h"
44 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
45 #include "third_party/WebKit/public/web/WebDataSource.h"
46 #include "third_party/WebKit/public/web/WebDocument.h"
47 #include "third_party/WebKit/public/web/WebElement.h"
48 #include "third_party/WebKit/public/web/WebHistoryItem.h"
49 #include "third_party/WebKit/public/web/WebLocalFrame.h"
50 #include "third_party/WebKit/public/web/WebNode.h"
51 #include "third_party/WebKit/public/web/WebPagePopup.h"
52 #include "third_party/WebKit/public/web/WebPluginParams.h"
53 #include "third_party/WebKit/public/web/WebPrintParams.h"
54 #include "third_party/WebKit/public/web/WebRange.h"
55 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
56 #include "third_party/WebKit/public/web/WebView.h"
57 #include "third_party/WebKit/public/web/WebWidgetClient.h"
59 namespace test_runner {
61 namespace {
63 class CaptureCallback : public blink::WebCompositeAndReadbackAsyncCallback {
64 public:
65 CaptureCallback(const base::Callback<void(const SkBitmap&)>& callback);
66 virtual ~CaptureCallback();
68 void set_wait_for_popup(bool wait) { wait_for_popup_ = wait; }
69 void set_popup_position(const gfx::Point& position) {
70 popup_position_ = position;
73 // WebCompositeAndReadbackAsyncCallback implementation.
74 virtual void didCompositeAndReadback(const SkBitmap& bitmap);
76 private:
77 base::Callback<void(const SkBitmap&)> callback_;
78 SkBitmap main_bitmap_;
79 bool wait_for_popup_;
80 gfx::Point popup_position_;
83 class LayoutAndPaintCallback : public blink::WebLayoutAndPaintAsyncCallback {
84 public:
85 LayoutAndPaintCallback(const base::Closure& callback)
86 : callback_(callback), wait_for_popup_(false) {
88 virtual ~LayoutAndPaintCallback() {
91 void set_wait_for_popup(bool wait) { wait_for_popup_ = wait; }
93 // WebLayoutAndPaintAsyncCallback implementation.
94 virtual void didLayoutAndPaint();
96 private:
97 base::Closure callback_;
98 bool wait_for_popup_;
101 class HostMethodTask : public WebMethodTask<WebTestProxyBase> {
102 public:
103 typedef void (WebTestProxyBase::*CallbackMethodType)();
104 HostMethodTask(WebTestProxyBase* object, CallbackMethodType callback)
105 : WebMethodTask<WebTestProxyBase>(object), callback_(callback) {}
107 void RunIfValid() override { (object_->*callback_)(); }
109 private:
110 CallbackMethodType callback_;
113 void PrintFrameDescription(WebTestDelegate* delegate, blink::WebFrame* frame) {
114 std::string name8 = frame->uniqueName().utf8();
115 if (frame == frame->view()->mainFrame()) {
116 if (!name8.length()) {
117 delegate->PrintMessage("main frame");
118 return;
120 delegate->PrintMessage(std::string("main frame \"") + name8 + "\"");
121 return;
123 if (!name8.length()) {
124 delegate->PrintMessage("frame (anonymous)");
125 return;
127 delegate->PrintMessage(std::string("frame \"") + name8 + "\"");
130 void PrintFrameuserGestureStatus(WebTestDelegate* delegate,
131 blink::WebFrame* frame,
132 const char* msg) {
133 bool is_user_gesture =
134 blink::WebUserGestureIndicator::isProcessingUserGesture();
135 delegate->PrintMessage(std::string("Frame with user gesture \"") +
136 (is_user_gesture ? "true" : "false") + "\"" + msg);
139 // Used to write a platform neutral file:/// URL by taking the
140 // filename and its directory. (e.g., converts
141 // "file:///tmp/foo/bar.txt" to just "bar.txt").
142 std::string DescriptionSuitableForTestResult(const std::string& url) {
143 if (url.empty() || std::string::npos == url.find("file://"))
144 return url;
146 size_t pos = url.rfind('/');
147 if (pos == std::string::npos || !pos)
148 return "ERROR:" + url;
149 pos = url.rfind('/', pos - 1);
150 if (pos == std::string::npos)
151 return "ERROR:" + url;
153 return url.substr(pos + 1);
156 void PrintResponseDescription(WebTestDelegate* delegate,
157 const blink::WebURLResponse& response) {
158 if (response.isNull()) {
159 delegate->PrintMessage("(null)");
160 return;
162 delegate->PrintMessage(base::StringPrintf(
163 "<NSURLResponse %s, http status code %d>",
164 DescriptionSuitableForTestResult(response.url().spec()).c_str(),
165 response.httpStatusCode()));
168 std::string URLDescription(const GURL& url) {
169 if (url.SchemeIs(url::kFileScheme))
170 return url.ExtractFileName();
171 return url.possibly_invalid_spec();
174 std::string PriorityDescription(
175 const blink::WebURLRequest::Priority& priority) {
176 switch (priority) {
177 case blink::WebURLRequest::PriorityVeryLow:
178 return "VeryLow";
179 case blink::WebURLRequest::PriorityLow:
180 return "Low";
181 case blink::WebURLRequest::PriorityMedium:
182 return "Medium";
183 case blink::WebURLRequest::PriorityHigh:
184 return "High";
185 case blink::WebURLRequest::PriorityVeryHigh:
186 return "VeryHigh";
187 case blink::WebURLRequest::PriorityUnresolved:
188 default:
189 return "Unresolved";
193 void BlockRequest(blink::WebURLRequest& request) {
194 request.setURL(GURL("255.255.255.255"));
197 bool IsLocalHost(const std::string& host) {
198 return host == "127.0.0.1" || host == "localhost";
201 bool IsTestHost(const std::string& host) {
202 return base::EndsWith(host, ".test", false);
205 bool HostIsUsedBySomeTestsToGenerateError(const std::string& host) {
206 return host == "255.255.255.255";
209 // Used to write a platform neutral file:/// URL by only taking the filename
210 // (e.g., converts "file:///tmp/foo.txt" to just "foo.txt").
211 std::string URLSuitableForTestResult(const std::string& url) {
212 if (url.empty() || std::string::npos == url.find("file://"))
213 return url;
215 size_t pos = url.rfind('/');
216 if (pos == std::string::npos) {
217 #ifdef WIN32
218 pos = url.rfind('\\');
219 if (pos == std::string::npos)
220 pos = 0;
221 #else
222 pos = 0;
223 #endif
225 std::string filename = url.substr(pos + 1);
226 if (filename.empty())
227 return "file:"; // A WebKit test has this in its expected output.
228 return filename;
231 // WebNavigationType debugging strings taken from PolicyDelegate.mm.
232 const char* kLinkClickedString = "link clicked";
233 const char* kFormSubmittedString = "form submitted";
234 const char* kBackForwardString = "back/forward";
235 const char* kReloadString = "reload";
236 const char* kFormResubmittedString = "form resubmitted";
237 const char* kOtherString = "other";
238 const char* kIllegalString = "illegal value";
240 // Get a debugging string from a WebNavigationType.
241 const char* WebNavigationTypeToString(blink::WebNavigationType type) {
242 switch (type) {
243 case blink::WebNavigationTypeLinkClicked:
244 return kLinkClickedString;
245 case blink::WebNavigationTypeFormSubmitted:
246 return kFormSubmittedString;
247 case blink::WebNavigationTypeBackForward:
248 return kBackForwardString;
249 case blink::WebNavigationTypeReload:
250 return kReloadString;
251 case blink::WebNavigationTypeFormResubmitted:
252 return kFormResubmittedString;
253 case blink::WebNavigationTypeOther:
254 return kOtherString;
256 return kIllegalString;
259 const char* kPolicyIgnore = "Ignore";
260 const char* kPolicyDownload = "download";
261 const char* kPolicyCurrentTab = "current tab";
262 const char* kPolicyNewBackgroundTab = "new background tab";
263 const char* kPolicyNewForegroundTab = "new foreground tab";
264 const char* kPolicyNewWindow = "new window";
265 const char* kPolicyNewPopup = "new popup";
267 const char* WebNavigationPolicyToString(blink::WebNavigationPolicy policy) {
268 switch (policy) {
269 case blink::WebNavigationPolicyIgnore:
270 return kPolicyIgnore;
271 case blink::WebNavigationPolicyDownload:
272 return kPolicyDownload;
273 case blink::WebNavigationPolicyCurrentTab:
274 return kPolicyCurrentTab;
275 case blink::WebNavigationPolicyNewBackgroundTab:
276 return kPolicyNewBackgroundTab;
277 case blink::WebNavigationPolicyNewForegroundTab:
278 return kPolicyNewForegroundTab;
279 case blink::WebNavigationPolicyNewWindow:
280 return kPolicyNewWindow;
281 case blink::WebNavigationPolicyNewPopup:
282 return kPolicyNewPopup;
284 return kIllegalString;
287 std::string DumpFrameHeaderIfNeeded(blink::WebFrame* frame) {
288 std::string result;
290 // Add header for all but the main frame. Skip empty frames.
291 if (frame->parent() && !frame->document().documentElement().isNull()) {
292 result.append("\n--------\nFrame: '");
293 result.append(frame->uniqueName().utf8().data());
294 result.append("'\n--------\n");
297 return result;
300 std::string DumpFramesAsMarkup(blink::WebFrame* frame, bool recursive) {
301 std::string result = DumpFrameHeaderIfNeeded(frame);
302 result.append(frame->contentAsMarkup().utf8());
303 result.append("\n");
305 if (recursive) {
306 for (blink::WebFrame* child = frame->firstChild(); child;
307 child = child->nextSibling())
308 result.append(DumpFramesAsMarkup(child, recursive));
311 return result;
314 std::string DumpDocumentText(blink::WebFrame* frame) {
315 return frame->document().contentAsTextForTesting().utf8();
318 std::string DumpFramesAsText(blink::WebFrame* frame, bool recursive) {
319 std::string result = DumpFrameHeaderIfNeeded(frame);
320 result.append(DumpDocumentText(frame));
321 result.append("\n");
323 if (recursive) {
324 for (blink::WebFrame* child = frame->firstChild(); child;
325 child = child->nextSibling())
326 result.append(DumpFramesAsText(child, recursive));
329 return result;
332 std::string DumpFramesAsPrintedText(blink::WebFrame* frame, bool recursive) {
333 // Cannot do printed format for anything other than HTML
334 if (!frame->document().isHTMLDocument())
335 return std::string();
337 std::string result = DumpFrameHeaderIfNeeded(frame);
338 result.append(
339 frame->layoutTreeAsText(blink::WebFrame::LayoutAsTextPrinting).utf8());
340 result.append("\n");
342 if (recursive) {
343 for (blink::WebFrame* child = frame->firstChild(); child;
344 child = child->nextSibling())
345 result.append(DumpFramesAsPrintedText(child, recursive));
348 return result;
351 std::string DumpFrameScrollPosition(blink::WebFrame* frame, bool recursive) {
352 std::string result;
353 blink::WebSize offset = frame->scrollOffset();
354 if (offset.width > 0 || offset.height > 0) {
355 if (frame->parent()) {
356 result =
357 std::string("frame '") + frame->uniqueName().utf8().data() + "' ";
359 base::StringAppendF(
360 &result, "scrolled to %d,%d\n", offset.width, offset.height);
363 if (!recursive)
364 return result;
365 for (blink::WebFrame* child = frame->firstChild(); child;
366 child = child->nextSibling())
367 result += DumpFrameScrollPosition(child, recursive);
368 return result;
371 std::string DumpAllBackForwardLists(TestInterfaces* interfaces,
372 WebTestDelegate* delegate) {
373 std::string result;
374 const std::vector<WebTestProxyBase*>& window_list =
375 interfaces->GetWindowList();
376 for (size_t i = 0; i < window_list.size(); ++i)
377 result.append(delegate->DumpHistoryForWindow(window_list.at(i)));
378 return result;
382 WebTestProxyBase::WebTestProxyBase()
383 : web_test_interfaces_(NULL),
384 test_interfaces_(NULL),
385 delegate_(NULL),
386 web_widget_(NULL),
387 spellcheck_(new SpellCheckClient(this)),
388 chooser_count_(0) {
389 Reset();
392 WebTestProxyBase::~WebTestProxyBase() {
393 test_interfaces_->WindowClosed(this);
396 void WebTestProxyBase::SetInterfaces(WebTestInterfaces* interfaces) {
397 web_test_interfaces_ = interfaces;
398 test_interfaces_ = interfaces->GetTestInterfaces();
399 test_interfaces_->WindowOpened(this);
402 WebTestInterfaces* WebTestProxyBase::GetInterfaces() {
403 return web_test_interfaces_;
406 void WebTestProxyBase::SetDelegate(WebTestDelegate* delegate) {
407 delegate_ = delegate;
408 spellcheck_->SetDelegate(delegate);
409 if (speech_recognizer_.get())
410 speech_recognizer_->SetDelegate(delegate);
413 WebTestDelegate* WebTestProxyBase::GetDelegate() {
414 return delegate_;
417 blink::WebView* WebTestProxyBase::GetWebView() const {
418 DCHECK(web_widget_);
419 // TestRunner does not support popup widgets. So |web_widget|_ is always a
420 // WebView.
421 return static_cast<blink::WebView*>(web_widget_);
424 void WebTestProxyBase::Reset() {
425 drag_image_.reset();
426 animate_scheduled_ = false;
427 resource_identifier_map_.clear();
428 log_console_output_ = true;
429 accept_languages_ = "";
432 blink::WebSpellCheckClient* WebTestProxyBase::GetSpellCheckClient() const {
433 return spellcheck_.get();
436 blink::WebColorChooser* WebTestProxyBase::CreateColorChooser(
437 blink::WebColorChooserClient* client,
438 const blink::WebColor& color,
439 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
440 // This instance is deleted by WebCore::ColorInputType
441 return new MockColorChooser(client, delegate_, this);
444 bool WebTestProxyBase::RunFileChooser(
445 const blink::WebFileChooserParams& params,
446 blink::WebFileChooserCompletion* completion) {
447 delegate_->PrintMessage("Mock: Opening a file chooser.\n");
448 // FIXME: Add ability to set file names to a file upload control.
449 return false;
452 void WebTestProxyBase::ShowValidationMessage(
453 const base::string16& message,
454 const base::string16& sub_message) {
455 delegate_->PrintMessage("ValidationMessageClient: main-message=" +
456 base::UTF16ToUTF8(message) + " sub-message=" +
457 base::UTF16ToUTF8(sub_message) + "\n");
460 std::string WebTestProxyBase::CaptureTree(
461 bool debug_render_tree,
462 bool dump_line_box_trees) {
463 bool should_dump_custom_text =
464 test_interfaces_->GetTestRunner()->shouldDumpAsCustomText();
465 bool should_dump_as_text =
466 test_interfaces_->GetTestRunner()->shouldDumpAsText();
467 bool should_dump_as_markup =
468 test_interfaces_->GetTestRunner()->shouldDumpAsMarkup();
469 bool should_dump_as_printed = test_interfaces_->GetTestRunner()->isPrinting();
470 blink::WebFrame* frame = GetWebView()->mainFrame();
471 std::string data_utf8;
472 if (should_dump_custom_text) {
473 // Append a newline for the test driver.
474 data_utf8 = test_interfaces_->GetTestRunner()->customDumpText() + "\n";
475 } else if (should_dump_as_text) {
476 bool recursive =
477 test_interfaces_->GetTestRunner()->shouldDumpChildFramesAsText();
478 data_utf8 = should_dump_as_printed ?
479 DumpFramesAsPrintedText(frame, recursive) :
480 DumpFramesAsText(frame, recursive);
481 } else if (should_dump_as_markup) {
482 bool recursive =
483 test_interfaces_->GetTestRunner()->shouldDumpChildFramesAsMarkup();
484 // Append a newline for the test driver.
485 data_utf8 = DumpFramesAsMarkup(frame, recursive);
486 } else {
487 bool recursive = test_interfaces_->GetTestRunner()
488 ->shouldDumpChildFrameScrollPositions();
489 blink::WebFrame::LayoutAsTextControls layout_text_behavior =
490 blink::WebFrame::LayoutAsTextNormal;
491 if (should_dump_as_printed)
492 layout_text_behavior |= blink::WebFrame::LayoutAsTextPrinting;
493 if (debug_render_tree)
494 layout_text_behavior |= blink::WebFrame::LayoutAsTextDebug;
495 if (dump_line_box_trees)
496 layout_text_behavior |= blink::WebFrame::LayoutAsTextWithLineTrees;
497 data_utf8 = frame->layoutTreeAsText(layout_text_behavior).utf8();
498 data_utf8 += DumpFrameScrollPosition(frame, recursive);
501 if (test_interfaces_->GetTestRunner()->ShouldDumpBackForwardList())
502 data_utf8 += DumpAllBackForwardLists(test_interfaces_, delegate_);
504 return data_utf8;
507 void WebTestProxyBase::DrawSelectionRect(SkCanvas* canvas) {
508 // See if we need to draw the selection bounds rect. Selection bounds
509 // rect is the rect enclosing the (possibly transformed) selection.
510 // The rect should be drawn after everything is laid out and painted.
511 if (!test_interfaces_->GetTestRunner()->shouldDumpSelectionRect())
512 return;
513 // If there is a selection rect - draw a red 1px border enclosing rect
514 blink::WebRect wr = GetWebView()->mainFrame()->selectionBoundsRect();
515 if (wr.isEmpty())
516 return;
517 // Render a red rectangle bounding selection rect
518 SkPaint paint;
519 paint.setColor(0xFFFF0000); // Fully opaque red
520 paint.setStyle(SkPaint::kStroke_Style);
521 paint.setFlags(SkPaint::kAntiAlias_Flag);
522 paint.setStrokeWidth(1.0f);
523 SkIRect rect; // Bounding rect
524 rect.set(wr.x, wr.y, wr.x + wr.width, wr.y + wr.height);
525 canvas->drawIRect(rect, paint);
528 void WebTestProxyBase::SetAcceptLanguages(const std::string& accept_languages) {
529 bool notify = accept_languages_ != accept_languages;
530 accept_languages_ = accept_languages;
532 if (notify)
533 GetWebView()->acceptLanguagesChanged();
536 void WebTestProxyBase::CopyImageAtAndCapturePixels(
537 int x, int y, const base::Callback<void(const SkBitmap&)>& callback) {
538 DCHECK(!callback.is_null());
539 uint64_t sequence_number = blink::Platform::current()->clipboard()->
540 sequenceNumber(blink::WebClipboard::Buffer());
541 GetWebView()->copyImageAt(blink::WebPoint(x, y));
542 if (sequence_number == blink::Platform::current()->clipboard()->
543 sequenceNumber(blink::WebClipboard::Buffer())) {
544 SkBitmap emptyBitmap;
545 callback.Run(emptyBitmap);
546 return;
549 blink::WebData data = blink::Platform::current()->clipboard()->readImage(
550 blink::WebClipboard::Buffer());
551 blink::WebImage image = blink::WebImage::fromData(data, blink::WebSize());
552 const SkBitmap& bitmap = image.getSkBitmap();
553 SkAutoLockPixels autoLock(bitmap);
554 callback.Run(bitmap);
557 void WebTestProxyBase::CapturePixelsForPrinting(
558 const base::Callback<void(const SkBitmap&)>& callback) {
559 web_widget_->layout();
561 blink::WebSize page_size_in_pixels = web_widget_->size();
562 blink::WebFrame* web_frame = GetWebView()->mainFrame();
564 int page_count = web_frame->printBegin(page_size_in_pixels);
565 int totalHeight = page_count * (page_size_in_pixels.height + 1) - 1;
567 bool is_opaque = false;
568 skia::RefPtr<SkCanvas> canvas(skia::AdoptRef(skia::TryCreateBitmapCanvas(
569 page_size_in_pixels.width, totalHeight, is_opaque)));
570 if (!canvas) {
571 callback.Run(SkBitmap());
572 return;
574 web_frame->printPagesWithBoundaries(canvas.get(), page_size_in_pixels);
575 web_frame->printEnd();
577 DrawSelectionRect(canvas.get());
578 SkBaseDevice* device = skia::GetTopDevice(*canvas);
579 const SkBitmap& bitmap = device->accessBitmap(false);
580 callback.Run(bitmap);
583 CaptureCallback::CaptureCallback(
584 const base::Callback<void(const SkBitmap&)>& callback)
585 : callback_(callback), wait_for_popup_(false) {
588 CaptureCallback::~CaptureCallback() {
591 void CaptureCallback::didCompositeAndReadback(const SkBitmap& bitmap) {
592 TRACE_EVENT2("shell",
593 "CaptureCallback::didCompositeAndReadback",
594 "x",
595 bitmap.info().width(),
596 "y",
597 bitmap.info().height());
598 if (!wait_for_popup_) {
599 callback_.Run(bitmap);
600 delete this;
601 return;
603 if (main_bitmap_.isNull()) {
604 bitmap.deepCopyTo(&main_bitmap_);
605 return;
607 SkCanvas canvas(main_bitmap_);
608 canvas.drawBitmap(bitmap, popup_position_.x(), popup_position_.y());
609 callback_.Run(main_bitmap_);
610 delete this;
613 void WebTestProxyBase::CapturePixelsAsync(
614 const base::Callback<void(const SkBitmap&)>& callback) {
615 TRACE_EVENT0("shell", "WebTestProxyBase::CapturePixelsAsync");
616 DCHECK(!callback.is_null());
618 if (test_interfaces_->GetTestRunner()->shouldDumpDragImage()) {
619 if (drag_image_.isNull()) {
620 // This means the test called dumpDragImage but did not initiate a drag.
621 // Return a blank image so that the test fails.
622 SkBitmap bitmap;
623 bitmap.allocN32Pixels(1, 1);
625 SkAutoLockPixels lock(bitmap);
626 bitmap.eraseColor(0);
628 callback.Run(bitmap);
629 return;
632 callback.Run(drag_image_.getSkBitmap());
633 return;
636 if (test_interfaces_->GetTestRunner()->isPrinting()) {
637 base::ThreadTaskRunnerHandle::Get()->PostTask(
638 FROM_HERE, base::Bind(&WebTestProxyBase::CapturePixelsForPrinting,
639 base::Unretained(this), callback));
640 return;
643 CaptureCallback* capture_callback = new CaptureCallback(base::Bind(
644 &WebTestProxyBase::DidCapturePixelsAsync, base::Unretained(this),
645 callback));
646 web_widget_->compositeAndReadbackAsync(capture_callback);
647 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
648 capture_callback->set_wait_for_popup(true);
649 capture_callback->set_popup_position(popup->positionRelativeToOwner());
650 popup->compositeAndReadbackAsync(capture_callback);
654 void WebTestProxyBase::DidCapturePixelsAsync(
655 const base::Callback<void(const SkBitmap&)>& callback,
656 const SkBitmap& bitmap) {
657 SkCanvas canvas(bitmap);
658 DrawSelectionRect(&canvas);
659 if (!callback.is_null())
660 callback.Run(bitmap);
663 void WebTestProxyBase::SetLogConsoleOutput(bool enabled) {
664 log_console_output_ = enabled;
667 void LayoutAndPaintCallback::didLayoutAndPaint() {
668 TRACE_EVENT0("shell", "LayoutAndPaintCallback::didLayoutAndPaint");
669 if (wait_for_popup_) {
670 wait_for_popup_ = false;
671 return;
674 if (!callback_.is_null())
675 callback_.Run();
676 delete this;
679 void WebTestProxyBase::LayoutAndPaintAsyncThen(const base::Closure& callback) {
680 TRACE_EVENT0("shell", "WebTestProxyBase::LayoutAndPaintAsyncThen");
682 LayoutAndPaintCallback* layout_and_paint_callback =
683 new LayoutAndPaintCallback(callback);
684 web_widget_->layoutAndPaintAsync(layout_and_paint_callback);
685 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
686 layout_and_paint_callback->set_wait_for_popup(true);
687 popup->layoutAndPaintAsync(layout_and_paint_callback);
691 void WebTestProxyBase::GetScreenOrientationForTesting(
692 blink::WebScreenInfo& screen_info) {
693 if (!screen_orientation_client_)
694 return;
695 // Override screen orientation information with mock data.
696 screen_info.orientationType =
697 screen_orientation_client_->CurrentOrientationType();
698 screen_info.orientationAngle =
699 screen_orientation_client_->CurrentOrientationAngle();
702 MockScreenOrientationClient*
703 WebTestProxyBase::GetScreenOrientationClientMock() {
704 if (!screen_orientation_client_.get()) {
705 screen_orientation_client_.reset(new MockScreenOrientationClient);
707 return screen_orientation_client_.get();
710 MockWebSpeechRecognizer* WebTestProxyBase::GetSpeechRecognizerMock() {
711 if (!speech_recognizer_.get()) {
712 speech_recognizer_.reset(new MockWebSpeechRecognizer());
713 speech_recognizer_->SetDelegate(delegate_);
715 return speech_recognizer_.get();
718 MockCredentialManagerClient*
719 WebTestProxyBase::GetCredentialManagerClientMock() {
720 if (!credential_manager_client_.get())
721 credential_manager_client_.reset(new MockCredentialManagerClient());
722 return credential_manager_client_.get();
725 void WebTestProxyBase::ScheduleAnimation() {
726 if (!test_interfaces_->GetTestRunner()->TestIsRunning())
727 return;
729 if (!animate_scheduled_) {
730 animate_scheduled_ = true;
731 delegate_->PostDelayedTask(
732 new HostMethodTask(this, &WebTestProxyBase::AnimateNow), 1);
736 void WebTestProxyBase::AnimateNow() {
737 if (animate_scheduled_) {
738 animate_scheduled_ = false;
739 web_widget_->beginFrame(blink::WebBeginFrameArgs(0.0, 0.0, 0.0));
740 web_widget_->layout();
741 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
742 popup->beginFrame(blink::WebBeginFrameArgs(0.0, 0.0, 0.0));
743 popup->layout();
748 void WebTestProxyBase::PostAccessibilityEvent(const blink::WebAXObject& obj,
749 blink::WebAXEvent event) {
750 // Only hook the accessibility events occured during the test run.
751 // This check prevents false positives in WebLeakDetector.
752 // The pending tasks in browser/renderer message queue may trigger
753 // accessibility events,
754 // and AccessibilityController will hold on to their target nodes if we don't
755 // ignore them here.
756 if (!test_interfaces_->GetTestRunner()->TestIsRunning())
757 return;
759 if (event == blink::WebAXEventFocus)
760 test_interfaces_->GetAccessibilityController()->SetFocusedElement(obj);
762 const char* event_name = NULL;
763 switch (event) {
764 case blink::WebAXEventActiveDescendantChanged:
765 event_name = "ActiveDescendantChanged";
766 break;
767 case blink::WebAXEventAlert:
768 event_name = "Alert";
769 break;
770 case blink::WebAXEventAriaAttributeChanged:
771 event_name = "AriaAttributeChanged";
772 break;
773 case blink::WebAXEventAutocorrectionOccured:
774 event_name = "AutocorrectionOccured";
775 break;
776 case blink::WebAXEventBlur:
777 event_name = "Blur";
778 break;
779 case blink::WebAXEventCheckedStateChanged:
780 event_name = "CheckedStateChanged";
781 break;
782 case blink::WebAXEventChildrenChanged:
783 event_name = "ChildrenChanged";
784 break;
785 case blink::WebAXEventFocus:
786 event_name = "Focus";
787 break;
788 case blink::WebAXEventHide:
789 event_name = "Hide";
790 break;
791 case blink::WebAXEventInvalidStatusChanged:
792 event_name = "InvalidStatusChanged";
793 break;
794 case blink::WebAXEventLayoutComplete:
795 event_name = "LayoutComplete";
796 break;
797 case blink::WebAXEventLiveRegionChanged:
798 event_name = "LiveRegionChanged";
799 break;
800 case blink::WebAXEventLoadComplete:
801 event_name = "LoadComplete";
802 break;
803 case blink::WebAXEventLocationChanged:
804 event_name = "LocationChanged";
805 break;
806 case blink::WebAXEventMenuListItemSelected:
807 event_name = "MenuListItemSelected";
808 break;
809 case blink::WebAXEventMenuListItemUnselected:
810 event_name = "MenuListItemUnselected";
811 break;
812 case blink::WebAXEventMenuListValueChanged:
813 event_name = "MenuListValueChanged";
814 break;
815 case blink::WebAXEventRowCollapsed:
816 event_name = "RowCollapsed";
817 break;
818 case blink::WebAXEventRowCountChanged:
819 event_name = "RowCountChanged";
820 break;
821 case blink::WebAXEventRowExpanded:
822 event_name = "RowExpanded";
823 break;
824 case blink::WebAXEventScrollPositionChanged:
825 event_name = "ScrollPositionChanged";
826 break;
827 case blink::WebAXEventScrolledToAnchor:
828 event_name = "ScrolledToAnchor";
829 break;
830 case blink::WebAXEventSelectedChildrenChanged:
831 event_name = "SelectedChildrenChanged";
832 break;
833 case blink::WebAXEventSelectedTextChanged:
834 event_name = "SelectedTextChanged";
835 break;
836 case blink::WebAXEventShow:
837 event_name = "Show";
838 break;
839 case blink::WebAXEventTextChanged:
840 event_name = "TextChanged";
841 break;
842 case blink::WebAXEventTextInserted:
843 event_name = "TextInserted";
844 break;
845 case blink::WebAXEventTextRemoved:
846 event_name = "TextRemoved";
847 break;
848 case blink::WebAXEventValueChanged:
849 event_name = "ValueChanged";
850 break;
851 default:
852 event_name = "Unknown";
853 break;
856 test_interfaces_->GetAccessibilityController()->NotificationReceived(
857 obj, event_name);
859 if (test_interfaces_->GetAccessibilityController()
860 ->ShouldLogAccessibilityEvents()) {
861 std::string message("AccessibilityNotification - ");
862 message += event_name;
864 blink::WebNode node = obj.node();
865 if (!node.isNull() && node.isElementNode()) {
866 blink::WebElement element = node.to<blink::WebElement>();
867 if (element.hasAttribute("id")) {
868 message += " - id:";
869 message += element.getAttribute("id").utf8().data();
873 delegate_->PrintMessage(message + "\n");
877 void WebTestProxyBase::StartDragging(blink::WebLocalFrame* frame,
878 const blink::WebDragData& data,
879 blink::WebDragOperationsMask mask,
880 const blink::WebImage& image,
881 const blink::WebPoint& point) {
882 if (test_interfaces_->GetTestRunner()->shouldDumpDragImage()) {
883 if (drag_image_.isNull())
884 drag_image_ = image;
886 // When running a test, we need to fake a drag drop operation otherwise
887 // Windows waits for real mouse events to know when the drag is over.
888 test_interfaces_->GetEventSender()->DoDragDrop(data, mask);
891 // The output from these methods in layout test mode should match that
892 // expected by the layout tests. See EditingDelegate.m in DumpRenderTree.
894 void WebTestProxyBase::DidChangeSelection(bool is_empty_callback) {
895 if (test_interfaces_->GetTestRunner()->shouldDumpEditingCallbacks())
896 delegate_->PrintMessage(
897 "EDITING DELEGATE: "
898 "webViewDidChangeSelection:WebViewDidChangeSelectionNotification\n");
901 void WebTestProxyBase::DidChangeContents() {
902 if (test_interfaces_->GetTestRunner()->shouldDumpEditingCallbacks())
903 delegate_->PrintMessage(
904 "EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification\n");
907 bool WebTestProxyBase::CreateView(blink::WebLocalFrame* frame,
908 const blink::WebURLRequest& request,
909 const blink::WebWindowFeatures& features,
910 const blink::WebString& frame_name,
911 blink::WebNavigationPolicy policy,
912 bool suppress_opener) {
913 if (test_interfaces_->GetTestRunner()->shouldDumpNavigationPolicy()) {
914 delegate_->PrintMessage("Default policy for createView for '" +
915 URLDescription(request.url()) + "' is '" +
916 WebNavigationPolicyToString(policy) + "'\n");
919 if (!test_interfaces_->GetTestRunner()->canOpenWindows())
920 return false;
921 if (test_interfaces_->GetTestRunner()->shouldDumpCreateView())
922 delegate_->PrintMessage(std::string("createView(") +
923 URLDescription(request.url()) + ")\n");
924 return true;
927 blink::WebPlugin* WebTestProxyBase::CreatePlugin(
928 blink::WebLocalFrame* frame,
929 const blink::WebPluginParams& params) {
930 if (TestPlugin::IsSupportedMimeType(params.mimeType))
931 return TestPlugin::create(frame, params, delegate_);
932 return delegate_->CreatePluginPlaceholder(frame, params);
935 void WebTestProxyBase::SetStatusText(const blink::WebString& text) {
936 if (!test_interfaces_->GetTestRunner()->shouldDumpStatusCallbacks())
937 return;
938 delegate_->PrintMessage(
939 std::string("UI DELEGATE STATUS CALLBACK: setStatusText:") +
940 text.utf8().data() + "\n");
943 void WebTestProxyBase::DidStopLoading() {
944 if (test_interfaces_->GetTestRunner()->shouldDumpProgressFinishedCallback())
945 delegate_->PrintMessage("postProgressFinishedNotification\n");
948 void WebTestProxyBase::ShowContextMenu(
949 blink::WebLocalFrame* frame,
950 const blink::WebContextMenuData& context_menu_data) {
951 test_interfaces_->GetEventSender()->SetContextMenuData(context_menu_data);
954 blink::WebUserMediaClient* WebTestProxyBase::GetUserMediaClient() {
955 if (!user_media_client_.get())
956 user_media_client_.reset(new MockWebUserMediaClient(delegate_));
957 return user_media_client_.get();
960 // Simulate a print by going into print mode and then exit straight away.
961 void WebTestProxyBase::PrintPage(blink::WebLocalFrame* frame) {
962 blink::WebSize page_size_in_pixels = web_widget_->size();
963 if (page_size_in_pixels.isEmpty())
964 return;
965 blink::WebPrintParams printParams(page_size_in_pixels);
966 frame->printBegin(printParams);
967 frame->printEnd();
970 blink::WebSpeechRecognizer* WebTestProxyBase::GetSpeechRecognizer() {
971 return GetSpeechRecognizerMock();
974 bool WebTestProxyBase::RequestPointerLock() {
975 return test_interfaces_->GetTestRunner()->RequestPointerLock();
978 void WebTestProxyBase::RequestPointerUnlock() {
979 test_interfaces_->GetTestRunner()->RequestPointerUnlock();
982 bool WebTestProxyBase::IsPointerLocked() {
983 return test_interfaces_->GetTestRunner()->isPointerLocked();
986 void WebTestProxyBase::DidFocus() {
987 delegate_->SetFocus(this, true);
990 void WebTestProxyBase::DidBlur() {
991 delegate_->SetFocus(this, false);
994 void WebTestProxyBase::SetToolTipText(const blink::WebString& text,
995 blink::WebTextDirection direction) {
996 test_interfaces_->GetTestRunner()->setToolTipText(text);
999 void WebTestProxyBase::DidOpenChooser() {
1000 chooser_count_++;
1003 void WebTestProxyBase::DidCloseChooser() {
1004 chooser_count_--;
1007 bool WebTestProxyBase::IsChooserShown() {
1008 return 0 < chooser_count_;
1011 void WebTestProxyBase::LoadURLExternally(
1012 blink::WebLocalFrame* frame,
1013 const blink::WebURLRequest& request,
1014 blink::WebNavigationPolicy policy,
1015 const blink::WebString& suggested_name) {
1016 if (test_interfaces_->GetTestRunner()->shouldWaitUntilExternalURLLoad()) {
1017 if (policy == blink::WebNavigationPolicyDownload) {
1018 delegate_->PrintMessage(
1019 std::string("Downloading URL with suggested filename \"") +
1020 suggested_name.utf8() + "\"\n");
1021 } else {
1022 delegate_->PrintMessage(std::string("Loading URL externally - \"") +
1023 URLDescription(request.url()) + "\"\n");
1025 delegate_->TestFinished();
1029 void WebTestProxyBase::DidStartProvisionalLoad(blink::WebLocalFrame* frame) {
1030 if (!test_interfaces_->GetTestRunner()->topLoadingFrame())
1031 test_interfaces_->GetTestRunner()->setTopLoadingFrame(frame, false);
1033 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1034 PrintFrameDescription(delegate_, frame);
1035 delegate_->PrintMessage(" - didStartProvisionalLoadForFrame\n");
1038 if (test_interfaces_->GetTestRunner()
1039 ->shouldDumpUserGestureInFrameLoadCallbacks()) {
1040 PrintFrameuserGestureStatus(
1041 delegate_, frame, " - in didStartProvisionalLoadForFrame\n");
1045 void WebTestProxyBase::DidReceiveServerRedirectForProvisionalLoad(
1046 blink::WebLocalFrame* frame) {
1047 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1048 PrintFrameDescription(delegate_, frame);
1049 delegate_->PrintMessage(
1050 " - didReceiveServerRedirectForProvisionalLoadForFrame\n");
1054 bool WebTestProxyBase::DidFailProvisionalLoad(
1055 blink::WebLocalFrame* frame,
1056 const blink::WebURLError& error,
1057 blink::WebHistoryCommitType commit_type) {
1058 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1059 PrintFrameDescription(delegate_, frame);
1060 delegate_->PrintMessage(" - didFailProvisionalLoadWithError\n");
1062 CheckDone(frame, MainResourceLoadFailed);
1063 return !frame->provisionalDataSource();
1066 void WebTestProxyBase::DidCommitProvisionalLoad(
1067 blink::WebLocalFrame* frame,
1068 const blink::WebHistoryItem& history_item,
1069 blink::WebHistoryCommitType history_type) {
1070 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1071 PrintFrameDescription(delegate_, frame);
1072 delegate_->PrintMessage(" - didCommitLoadForFrame\n");
1076 void WebTestProxyBase::DidReceiveTitle(blink::WebLocalFrame* frame,
1077 const blink::WebString& title,
1078 blink::WebTextDirection direction) {
1079 blink::WebCString title8 = title.utf8();
1081 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1082 PrintFrameDescription(delegate_, frame);
1083 delegate_->PrintMessage(std::string(" - didReceiveTitle: ") +
1084 title8.data() + "\n");
1087 if (test_interfaces_->GetTestRunner()->shouldDumpTitleChanges())
1088 delegate_->PrintMessage(std::string("TITLE CHANGED: '") + title8.data() +
1089 "'\n");
1092 void WebTestProxyBase::DidChangeIcon(blink::WebLocalFrame* frame,
1093 blink::WebIconURL::Type icon_type) {
1094 if (test_interfaces_->GetTestRunner()->shouldDumpIconChanges()) {
1095 PrintFrameDescription(delegate_, frame);
1096 delegate_->PrintMessage(std::string(" - didChangeIcons\n"));
1100 void WebTestProxyBase::DidFinishDocumentLoad(blink::WebLocalFrame* frame) {
1101 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1102 PrintFrameDescription(delegate_, frame);
1103 delegate_->PrintMessage(" - didFinishDocumentLoadForFrame\n");
1107 void WebTestProxyBase::DidHandleOnloadEvents(blink::WebLocalFrame* frame) {
1108 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1109 PrintFrameDescription(delegate_, frame);
1110 delegate_->PrintMessage(" - didHandleOnloadEventsForFrame\n");
1114 void WebTestProxyBase::DidFailLoad(blink::WebLocalFrame* frame,
1115 const blink::WebURLError& error,
1116 blink::WebHistoryCommitType commit_type) {
1117 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1118 PrintFrameDescription(delegate_, frame);
1119 delegate_->PrintMessage(" - didFailLoadWithError\n");
1121 CheckDone(frame, MainResourceLoadFailed);
1124 void WebTestProxyBase::DidFinishLoad(blink::WebLocalFrame* frame) {
1125 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1126 PrintFrameDescription(delegate_, frame);
1127 delegate_->PrintMessage(" - didFinishLoadForFrame\n");
1129 CheckDone(frame, LoadFinished);
1132 void WebTestProxyBase::DidDetectXSS(blink::WebLocalFrame* frame,
1133 const blink::WebURL& insecure_url,
1134 bool did_block_entire_page) {
1135 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks())
1136 delegate_->PrintMessage("didDetectXSS\n");
1139 void WebTestProxyBase::DidDispatchPingLoader(blink::WebLocalFrame* frame,
1140 const blink::WebURL& url) {
1141 if (test_interfaces_->GetTestRunner()->shouldDumpPingLoaderCallbacks())
1142 delegate_->PrintMessage(std::string("PingLoader dispatched to '") +
1143 URLDescription(url).c_str() + "'.\n");
1146 void WebTestProxyBase::WillRequestResource(
1147 blink::WebLocalFrame* frame,
1148 const blink::WebCachedURLRequest& request) {
1149 if (test_interfaces_->GetTestRunner()->shouldDumpResourceRequestCallbacks()) {
1150 PrintFrameDescription(delegate_, frame);
1151 delegate_->PrintMessage(std::string(" - ") +
1152 request.initiatorName().utf8().data());
1153 delegate_->PrintMessage(std::string(" requested '") +
1154 URLDescription(request.urlRequest().url()).c_str() +
1155 "'\n");
1159 void WebTestProxyBase::WillSendRequest(
1160 blink::WebLocalFrame* frame,
1161 unsigned identifier,
1162 blink::WebURLRequest& request,
1163 const blink::WebURLResponse& redirect_response) {
1164 // Need to use GURL for host() and SchemeIs()
1165 GURL url = request.url();
1166 std::string request_url = url.possibly_invalid_spec();
1168 GURL main_document_url = request.firstPartyForCookies();
1170 if (redirect_response.isNull() &&
1171 (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks() ||
1172 test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities())) {
1173 DCHECK(resource_identifier_map_.find(identifier) ==
1174 resource_identifier_map_.end());
1175 resource_identifier_map_[identifier] =
1176 DescriptionSuitableForTestResult(request_url);
1179 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1180 if (resource_identifier_map_.find(identifier) ==
1181 resource_identifier_map_.end())
1182 delegate_->PrintMessage("<unknown>");
1183 else
1184 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1185 delegate_->PrintMessage(" - willSendRequest <NSURLRequest URL ");
1186 delegate_->PrintMessage(
1187 DescriptionSuitableForTestResult(request_url).c_str());
1188 delegate_->PrintMessage(", main document URL ");
1189 delegate_->PrintMessage(URLDescription(main_document_url).c_str());
1190 delegate_->PrintMessage(", http method ");
1191 delegate_->PrintMessage(request.httpMethod().utf8().data());
1192 delegate_->PrintMessage("> redirectResponse ");
1193 PrintResponseDescription(delegate_, redirect_response);
1194 delegate_->PrintMessage("\n");
1197 if (test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities()) {
1198 delegate_->PrintMessage(
1199 DescriptionSuitableForTestResult(request_url).c_str());
1200 delegate_->PrintMessage(" has priority ");
1201 delegate_->PrintMessage(PriorityDescription(request.priority()));
1202 delegate_->PrintMessage("\n");
1205 if (test_interfaces_->GetTestRunner()->httpHeadersToClear()) {
1206 const std::set<std::string>* clearHeaders =
1207 test_interfaces_->GetTestRunner()->httpHeadersToClear();
1208 for (std::set<std::string>::const_iterator header = clearHeaders->begin();
1209 header != clearHeaders->end();
1210 ++header)
1211 request.clearHTTPHeaderField(blink::WebString::fromUTF8(*header));
1214 std::string host = url.host();
1215 if (!host.empty() &&
1216 (url.SchemeIs(url::kHttpScheme) || url.SchemeIs(url::kHttpsScheme))) {
1217 if (!IsLocalHost(host) && !IsTestHost(host) &&
1218 !HostIsUsedBySomeTestsToGenerateError(host) &&
1219 ((!main_document_url.SchemeIs(url::kHttpScheme) &&
1220 !main_document_url.SchemeIs(url::kHttpsScheme)) ||
1221 IsLocalHost(main_document_url.host())) &&
1222 !delegate_->AllowExternalPages()) {
1223 delegate_->PrintMessage(std::string("Blocked access to external URL ") +
1224 request_url + "\n");
1225 BlockRequest(request);
1226 return;
1230 // Set the new substituted URL.
1231 request.setURL(delegate_->RewriteLayoutTestsURL(request.url().spec()));
1234 void WebTestProxyBase::DidReceiveResponse(
1235 blink::WebLocalFrame* frame,
1236 unsigned identifier,
1237 const blink::WebURLResponse& response) {
1238 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1239 if (resource_identifier_map_.find(identifier) ==
1240 resource_identifier_map_.end())
1241 delegate_->PrintMessage("<unknown>");
1242 else
1243 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1244 delegate_->PrintMessage(" - didReceiveResponse ");
1245 PrintResponseDescription(delegate_, response);
1246 delegate_->PrintMessage("\n");
1248 if (test_interfaces_->GetTestRunner()
1249 ->shouldDumpResourceResponseMIMETypes()) {
1250 GURL url = response.url();
1251 blink::WebString mime_type = response.mimeType();
1252 delegate_->PrintMessage(url.ExtractFileName());
1253 delegate_->PrintMessage(" has MIME type ");
1254 // Simulate NSURLResponse's mapping of empty/unknown MIME types to
1255 // application/octet-stream
1256 delegate_->PrintMessage(mime_type.isEmpty() ? "application/octet-stream"
1257 : mime_type.utf8().data());
1258 delegate_->PrintMessage("\n");
1262 void WebTestProxyBase::DidChangeResourcePriority(
1263 blink::WebLocalFrame* frame,
1264 unsigned identifier,
1265 const blink::WebURLRequest::Priority& priority,
1266 int intra_priority_value) {
1267 if (test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities()) {
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(
1274 base::StringPrintf(" changed priority to %s, intra_priority %d\n",
1275 PriorityDescription(priority).c_str(),
1276 intra_priority_value));
1280 void WebTestProxyBase::DidFinishResourceLoad(blink::WebLocalFrame* frame,
1281 unsigned identifier) {
1282 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1283 if (resource_identifier_map_.find(identifier) ==
1284 resource_identifier_map_.end())
1285 delegate_->PrintMessage("<unknown>");
1286 else
1287 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1288 delegate_->PrintMessage(" - didFinishLoading\n");
1290 resource_identifier_map_.erase(identifier);
1291 CheckDone(frame, ResourceLoadCompleted);
1294 void WebTestProxyBase::DidAddMessageToConsole(
1295 const blink::WebConsoleMessage& message,
1296 const blink::WebString& source_name,
1297 unsigned source_line) {
1298 // This matches win DumpRenderTree's UIDelegate.cpp.
1299 if (!log_console_output_)
1300 return;
1301 std::string level;
1302 switch (message.level) {
1303 case blink::WebConsoleMessage::LevelDebug:
1304 level = "DEBUG";
1305 break;
1306 case blink::WebConsoleMessage::LevelLog:
1307 level = "MESSAGE";
1308 break;
1309 case blink::WebConsoleMessage::LevelInfo:
1310 level = "INFO";
1311 break;
1312 case blink::WebConsoleMessage::LevelWarning:
1313 level = "WARNING";
1314 break;
1315 case blink::WebConsoleMessage::LevelError:
1316 level = "ERROR";
1317 break;
1318 default:
1319 level = "MESSAGE";
1321 delegate_->PrintMessage(std::string("CONSOLE ") + level + ": ");
1322 if (source_line) {
1323 delegate_->PrintMessage(base::StringPrintf("line %d: ", source_line));
1325 if (!message.text.isEmpty()) {
1326 std::string new_message;
1327 new_message = message.text.utf8();
1328 size_t file_protocol = new_message.find("file://");
1329 if (file_protocol != std::string::npos) {
1330 new_message = new_message.substr(0, file_protocol) +
1331 URLSuitableForTestResult(new_message.substr(file_protocol));
1333 delegate_->PrintMessage(new_message);
1335 delegate_->PrintMessage(std::string("\n"));
1338 void WebTestProxyBase::CheckDone(blink::WebLocalFrame* frame,
1339 CheckDoneReason reason) {
1340 if (frame != test_interfaces_->GetTestRunner()->topLoadingFrame())
1341 return;
1342 if (reason != MainResourceLoadFailed &&
1343 (frame->isResourceLoadInProgress() || frame->isLoading()))
1344 return;
1345 test_interfaces_->GetTestRunner()->setTopLoadingFrame(frame, true);
1348 blink::WebNavigationPolicy WebTestProxyBase::DecidePolicyForNavigation(
1349 const blink::WebFrameClient::NavigationPolicyInfo& info) {
1350 if (test_interfaces_->GetTestRunner()->shouldDumpNavigationPolicy()) {
1351 delegate_->PrintMessage("Default policy for navigation to '" +
1352 URLDescription(info.urlRequest.url()) + "' is '" +
1353 WebNavigationPolicyToString(info.defaultPolicy) +
1354 "'\n");
1357 blink::WebNavigationPolicy result;
1358 if (!test_interfaces_->GetTestRunner()->policyDelegateEnabled())
1359 return info.defaultPolicy;
1361 delegate_->PrintMessage(
1362 std::string("Policy delegate: attempt to load ") +
1363 URLDescription(info.urlRequest.url()) + " with navigation type '" +
1364 WebNavigationTypeToString(info.navigationType) + "'\n");
1365 if (test_interfaces_->GetTestRunner()->policyDelegateIsPermissive())
1366 result = blink::WebNavigationPolicyCurrentTab;
1367 else
1368 result = blink::WebNavigationPolicyIgnore;
1370 if (test_interfaces_->GetTestRunner()->policyDelegateShouldNotifyDone()) {
1371 test_interfaces_->GetTestRunner()->policyDelegateDone();
1372 result = blink::WebNavigationPolicyIgnore;
1375 return result;
1378 bool WebTestProxyBase::WillCheckAndDispatchMessageEvent(
1379 blink::WebLocalFrame* source_frame,
1380 blink::WebFrame* target_frame,
1381 blink::WebSecurityOrigin target,
1382 blink::WebDOMMessageEvent event) {
1383 if (test_interfaces_->GetTestRunner()->shouldInterceptPostMessage()) {
1384 delegate_->PrintMessage("intercepted postMessage\n");
1385 return true;
1388 return false;
1391 void WebTestProxyBase::PostSpellCheckEvent(const blink::WebString& event_name) {
1392 if (test_interfaces_->GetTestRunner()->shouldDumpSpellCheckCallbacks()) {
1393 delegate_->PrintMessage(std::string("SpellCheckEvent: ") +
1394 event_name.utf8().data() + "\n");
1398 void WebTestProxyBase::ResetInputMethod() {
1399 // If a composition text exists, then we need to let the browser process
1400 // to cancel the input method's ongoing composition session.
1401 if (web_widget_)
1402 web_widget_->confirmComposition();
1405 blink::WebString WebTestProxyBase::acceptLanguages() {
1406 return blink::WebString::fromUTF8(accept_languages_);
1409 } // namespace test_runner