Don't preload rarely seen large images
[chromium-blink-merge.git] / components / test_runner / web_test_proxy.cc
blob4b2b43a7a9aa6dc5041fee0c13cc0bc7ce233ab3
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/trace_event/trace_event.h"
18 #include "components/test_runner/accessibility_controller.h"
19 #include "components/test_runner/event_sender.h"
20 #include "components/test_runner/mock_color_chooser.h"
21 #include "components/test_runner/mock_credential_manager_client.h"
22 #include "components/test_runner/mock_screen_orientation_client.h"
23 #include "components/test_runner/mock_web_speech_recognizer.h"
24 #include "components/test_runner/mock_web_user_media_client.h"
25 #include "components/test_runner/spell_check_client.h"
26 #include "components/test_runner/test_interfaces.h"
27 #include "components/test_runner/test_plugin.h"
28 #include "components/test_runner/test_runner.h"
29 #include "components/test_runner/web_test_delegate.h"
30 #include "components/test_runner/web_test_interfaces.h"
31 #include "components/test_runner/web_test_runner.h"
32 // FIXME: Including platform_canvas.h here is a layering violation.
33 #include "skia/ext/platform_canvas.h"
34 #include "third_party/WebKit/public/platform/Platform.h"
35 #include "third_party/WebKit/public/platform/WebCString.h"
36 #include "third_party/WebKit/public/platform/WebClipboard.h"
37 #include "third_party/WebKit/public/platform/WebCompositeAndReadbackAsyncCallback.h"
38 #include "third_party/WebKit/public/platform/WebLayoutAndPaintAsyncCallback.h"
39 #include "third_party/WebKit/public/platform/WebURLError.h"
40 #include "third_party/WebKit/public/platform/WebURLRequest.h"
41 #include "third_party/WebKit/public/platform/WebURLResponse.h"
42 #include "third_party/WebKit/public/web/WebAXEnums.h"
43 #include "third_party/WebKit/public/web/WebAXObject.h"
44 #include "third_party/WebKit/public/web/WebCachedURLRequest.h"
45 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
46 #include "third_party/WebKit/public/web/WebDataSource.h"
47 #include "third_party/WebKit/public/web/WebDocument.h"
48 #include "third_party/WebKit/public/web/WebElement.h"
49 #include "third_party/WebKit/public/web/WebHistoryItem.h"
50 #include "third_party/WebKit/public/web/WebLocalFrame.h"
51 #include "third_party/WebKit/public/web/WebNode.h"
52 #include "third_party/WebKit/public/web/WebPagePopup.h"
53 #include "third_party/WebKit/public/web/WebPluginParams.h"
54 #include "third_party/WebKit/public/web/WebPrintParams.h"
55 #include "third_party/WebKit/public/web/WebRange.h"
56 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
57 #include "third_party/WebKit/public/web/WebView.h"
58 #include "third_party/WebKit/public/web/WebWidgetClient.h"
60 namespace test_runner {
62 namespace {
64 class CaptureCallback : public blink::WebCompositeAndReadbackAsyncCallback {
65 public:
66 CaptureCallback(const base::Callback<void(const SkBitmap&)>& callback);
67 virtual ~CaptureCallback();
69 void set_wait_for_popup(bool wait) { wait_for_popup_ = wait; }
70 void set_popup_position(const gfx::Point& position) {
71 popup_position_ = position;
74 // WebCompositeAndReadbackAsyncCallback implementation.
75 virtual void didCompositeAndReadback(const SkBitmap& bitmap);
77 private:
78 base::Callback<void(const SkBitmap&)> callback_;
79 SkBitmap main_bitmap_;
80 bool wait_for_popup_;
81 gfx::Point popup_position_;
84 class LayoutAndPaintCallback : public blink::WebLayoutAndPaintAsyncCallback {
85 public:
86 LayoutAndPaintCallback(const base::Closure& callback)
87 : callback_(callback), wait_for_popup_(false) {
89 virtual ~LayoutAndPaintCallback() {
92 void set_wait_for_popup(bool wait) { wait_for_popup_ = wait; }
94 // WebLayoutAndPaintAsyncCallback implementation.
95 virtual void didLayoutAndPaint();
97 private:
98 base::Closure callback_;
99 bool wait_for_popup_;
102 class HostMethodTask : public WebMethodTask<WebTestProxyBase> {
103 public:
104 typedef void (WebTestProxyBase::*CallbackMethodType)();
105 HostMethodTask(WebTestProxyBase* object, CallbackMethodType callback)
106 : WebMethodTask<WebTestProxyBase>(object), callback_(callback) {}
108 void RunIfValid() override { (object_->*callback_)(); }
110 private:
111 CallbackMethodType callback_;
114 void PrintFrameDescription(WebTestDelegate* delegate, blink::WebFrame* frame) {
115 std::string name8 = frame->uniqueName().utf8();
116 if (frame == frame->view()->mainFrame()) {
117 if (!name8.length()) {
118 delegate->PrintMessage("main frame");
119 return;
121 delegate->PrintMessage(std::string("main frame \"") + name8 + "\"");
122 return;
124 if (!name8.length()) {
125 delegate->PrintMessage("frame (anonymous)");
126 return;
128 delegate->PrintMessage(std::string("frame \"") + name8 + "\"");
131 void PrintFrameuserGestureStatus(WebTestDelegate* delegate,
132 blink::WebFrame* frame,
133 const char* msg) {
134 bool is_user_gesture =
135 blink::WebUserGestureIndicator::isProcessingUserGesture();
136 delegate->PrintMessage(std::string("Frame with user gesture \"") +
137 (is_user_gesture ? "true" : "false") + "\"" + msg);
140 // Used to write a platform neutral file:/// URL by taking the
141 // filename and its directory. (e.g., converts
142 // "file:///tmp/foo/bar.txt" to just "bar.txt").
143 std::string DescriptionSuitableForTestResult(const std::string& url) {
144 if (url.empty() || std::string::npos == url.find("file://"))
145 return url;
147 size_t pos = url.rfind('/');
148 if (pos == std::string::npos || !pos)
149 return "ERROR:" + url;
150 pos = url.rfind('/', pos - 1);
151 if (pos == std::string::npos)
152 return "ERROR:" + url;
154 return url.substr(pos + 1);
157 void PrintResponseDescription(WebTestDelegate* delegate,
158 const blink::WebURLResponse& response) {
159 if (response.isNull()) {
160 delegate->PrintMessage("(null)");
161 return;
163 delegate->PrintMessage(base::StringPrintf(
164 "<NSURLResponse %s, http status code %d>",
165 DescriptionSuitableForTestResult(response.url().spec()).c_str(),
166 response.httpStatusCode()));
169 std::string URLDescription(const GURL& url) {
170 if (url.SchemeIs(url::kFileScheme))
171 return url.ExtractFileName();
172 return url.possibly_invalid_spec();
175 std::string PriorityDescription(
176 const blink::WebURLRequest::Priority& priority) {
177 switch (priority) {
178 case blink::WebURLRequest::PriorityVeryLow:
179 return "VeryLow";
180 case blink::WebURLRequest::PriorityLow:
181 return "Low";
182 case blink::WebURLRequest::PriorityMedium:
183 return "Medium";
184 case blink::WebURLRequest::PriorityHigh:
185 return "High";
186 case blink::WebURLRequest::PriorityVeryHigh:
187 return "VeryHigh";
188 case blink::WebURLRequest::PriorityUnresolved:
189 default:
190 return "Unresolved";
194 void BlockRequest(blink::WebURLRequest& request) {
195 request.setURL(GURL("255.255.255.255"));
198 bool IsLocalHost(const std::string& host) {
199 return host == "127.0.0.1" || host == "localhost";
202 bool IsTestHost(const std::string& host) {
203 return base::EndsWith(host, ".test", false);
206 bool HostIsUsedBySomeTestsToGenerateError(const std::string& host) {
207 return host == "255.255.255.255";
210 // Used to write a platform neutral file:/// URL by only taking the filename
211 // (e.g., converts "file:///tmp/foo.txt" to just "foo.txt").
212 std::string URLSuitableForTestResult(const std::string& url) {
213 if (url.empty() || std::string::npos == url.find("file://"))
214 return url;
216 size_t pos = url.rfind('/');
217 if (pos == std::string::npos) {
218 #ifdef WIN32
219 pos = url.rfind('\\');
220 if (pos == std::string::npos)
221 pos = 0;
222 #else
223 pos = 0;
224 #endif
226 std::string filename = url.substr(pos + 1);
227 if (filename.empty())
228 return "file:"; // A WebKit test has this in its expected output.
229 return filename;
232 // WebNavigationType debugging strings taken from PolicyDelegate.mm.
233 const char* kLinkClickedString = "link clicked";
234 const char* kFormSubmittedString = "form submitted";
235 const char* kBackForwardString = "back/forward";
236 const char* kReloadString = "reload";
237 const char* kFormResubmittedString = "form resubmitted";
238 const char* kOtherString = "other";
239 const char* kIllegalString = "illegal value";
241 // Get a debugging string from a WebNavigationType.
242 const char* WebNavigationTypeToString(blink::WebNavigationType type) {
243 switch (type) {
244 case blink::WebNavigationTypeLinkClicked:
245 return kLinkClickedString;
246 case blink::WebNavigationTypeFormSubmitted:
247 return kFormSubmittedString;
248 case blink::WebNavigationTypeBackForward:
249 return kBackForwardString;
250 case blink::WebNavigationTypeReload:
251 return kReloadString;
252 case blink::WebNavigationTypeFormResubmitted:
253 return kFormResubmittedString;
254 case blink::WebNavigationTypeOther:
255 return kOtherString;
257 return kIllegalString;
260 const char* kPolicyIgnore = "Ignore";
261 const char* kPolicyDownload = "download";
262 const char* kPolicyCurrentTab = "current tab";
263 const char* kPolicyNewBackgroundTab = "new background tab";
264 const char* kPolicyNewForegroundTab = "new foreground tab";
265 const char* kPolicyNewWindow = "new window";
266 const char* kPolicyNewPopup = "new popup";
268 const char* WebNavigationPolicyToString(blink::WebNavigationPolicy policy) {
269 switch (policy) {
270 case blink::WebNavigationPolicyIgnore:
271 return kPolicyIgnore;
272 case blink::WebNavigationPolicyDownload:
273 return kPolicyDownload;
274 case blink::WebNavigationPolicyCurrentTab:
275 return kPolicyCurrentTab;
276 case blink::WebNavigationPolicyNewBackgroundTab:
277 return kPolicyNewBackgroundTab;
278 case blink::WebNavigationPolicyNewForegroundTab:
279 return kPolicyNewForegroundTab;
280 case blink::WebNavigationPolicyNewWindow:
281 return kPolicyNewWindow;
282 case blink::WebNavigationPolicyNewPopup:
283 return kPolicyNewPopup;
285 return kIllegalString;
288 std::string DumpFrameHeaderIfNeeded(blink::WebFrame* frame) {
289 std::string result;
291 // Add header for all but the main frame. Skip empty frames.
292 if (frame->parent() && !frame->document().documentElement().isNull()) {
293 result.append("\n--------\nFrame: '");
294 result.append(frame->uniqueName().utf8().data());
295 result.append("'\n--------\n");
298 return result;
301 std::string DumpFramesAsMarkup(blink::WebFrame* frame, bool recursive) {
302 std::string result = DumpFrameHeaderIfNeeded(frame);
303 result.append(frame->contentAsMarkup().utf8());
304 result.append("\n");
306 if (recursive) {
307 for (blink::WebFrame* child = frame->firstChild(); child;
308 child = child->nextSibling())
309 result.append(DumpFramesAsMarkup(child, recursive));
312 return result;
315 std::string DumpDocumentText(blink::WebFrame* frame) {
316 return frame->document().contentAsTextForTesting().utf8();
319 std::string DumpFramesAsText(blink::WebFrame* frame, bool recursive) {
320 std::string result = DumpFrameHeaderIfNeeded(frame);
321 result.append(DumpDocumentText(frame));
322 result.append("\n");
324 if (recursive) {
325 for (blink::WebFrame* child = frame->firstChild(); child;
326 child = child->nextSibling())
327 result.append(DumpFramesAsText(child, recursive));
330 return result;
333 std::string DumpFramesAsPrintedText(blink::WebFrame* frame, bool recursive) {
334 // Cannot do printed format for anything other than HTML
335 if (!frame->document().isHTMLDocument())
336 return std::string();
338 std::string result = DumpFrameHeaderIfNeeded(frame);
339 result.append(
340 frame->layoutTreeAsText(blink::WebFrame::LayoutAsTextPrinting).utf8());
341 result.append("\n");
343 if (recursive) {
344 for (blink::WebFrame* child = frame->firstChild(); child;
345 child = child->nextSibling())
346 result.append(DumpFramesAsPrintedText(child, recursive));
349 return result;
352 std::string DumpFrameScrollPosition(blink::WebFrame* frame, bool recursive) {
353 std::string result;
354 blink::WebSize offset = frame->scrollOffset();
355 if (offset.width > 0 || offset.height > 0) {
356 if (frame->parent()) {
357 result =
358 std::string("frame '") + frame->uniqueName().utf8().data() + "' ";
360 base::StringAppendF(
361 &result, "scrolled to %d,%d\n", offset.width, offset.height);
364 if (!recursive)
365 return result;
366 for (blink::WebFrame* child = frame->firstChild(); child;
367 child = child->nextSibling())
368 result += DumpFrameScrollPosition(child, recursive);
369 return result;
372 std::string DumpAllBackForwardLists(TestInterfaces* interfaces,
373 WebTestDelegate* delegate) {
374 std::string result;
375 const std::vector<WebTestProxyBase*>& window_list =
376 interfaces->GetWindowList();
377 for (size_t i = 0; i < window_list.size(); ++i)
378 result.append(delegate->DumpHistoryForWindow(window_list.at(i)));
379 return result;
383 WebTestProxyBase::WebTestProxyBase()
384 : web_test_interfaces_(NULL),
385 test_interfaces_(NULL),
386 delegate_(NULL),
387 web_widget_(NULL),
388 spellcheck_(new SpellCheckClient(this)),
389 chooser_count_(0) {
390 Reset();
393 WebTestProxyBase::~WebTestProxyBase() {
394 test_interfaces_->WindowClosed(this);
397 void WebTestProxyBase::SetInterfaces(WebTestInterfaces* interfaces) {
398 web_test_interfaces_ = interfaces;
399 test_interfaces_ = interfaces->GetTestInterfaces();
400 test_interfaces_->WindowOpened(this);
403 WebTestInterfaces* WebTestProxyBase::GetInterfaces() {
404 return web_test_interfaces_;
407 void WebTestProxyBase::SetDelegate(WebTestDelegate* delegate) {
408 delegate_ = delegate;
409 spellcheck_->SetDelegate(delegate);
410 if (speech_recognizer_.get())
411 speech_recognizer_->SetDelegate(delegate);
414 WebTestDelegate* WebTestProxyBase::GetDelegate() {
415 return delegate_;
418 blink::WebView* WebTestProxyBase::GetWebView() const {
419 DCHECK(web_widget_);
420 // TestRunner does not support popup widgets. So |web_widget|_ is always a
421 // WebView.
422 return static_cast<blink::WebView*>(web_widget_);
425 void WebTestProxyBase::Reset() {
426 drag_image_.reset();
427 animate_scheduled_ = false;
428 resource_identifier_map_.clear();
429 log_console_output_ = true;
430 accept_languages_ = "";
433 blink::WebSpellCheckClient* WebTestProxyBase::GetSpellCheckClient() const {
434 return spellcheck_.get();
437 blink::WebColorChooser* WebTestProxyBase::CreateColorChooser(
438 blink::WebColorChooserClient* client,
439 const blink::WebColor& color,
440 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
441 // This instance is deleted by WebCore::ColorInputType
442 return new MockColorChooser(client, delegate_, this);
445 bool WebTestProxyBase::RunFileChooser(
446 const blink::WebFileChooserParams& params,
447 blink::WebFileChooserCompletion* completion) {
448 delegate_->PrintMessage("Mock: Opening a file chooser.\n");
449 // FIXME: Add ability to set file names to a file upload control.
450 return false;
453 void WebTestProxyBase::ShowValidationMessage(
454 const blink::WebString& main_message,
455 blink::WebTextDirection main_message_hint,
456 const blink::WebString& sub_message,
457 blink::WebTextDirection sub_message_hint) {
458 base::string16 wrapped_main_text = main_message;
459 base::string16 wrapped_sub_text = sub_message;
461 if (main_message_hint == blink::WebTextDirectionLeftToRight) {
462 wrapped_main_text =
463 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_main_text);
464 } else if (main_message_hint == blink::WebTextDirectionRightToLeft &&
465 !base::i18n::IsRTL()) {
466 base::i18n::WrapStringWithRTLFormatting(&wrapped_main_text);
469 if (!wrapped_sub_text.empty()) {
470 if (sub_message_hint == blink::WebTextDirectionLeftToRight) {
471 wrapped_sub_text =
472 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_sub_text);
473 } else if (sub_message_hint == blink::WebTextDirectionRightToLeft) {
474 base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text);
477 delegate_->PrintMessage("ValidationMessageClient: main-message=" +
478 base::UTF16ToUTF8(wrapped_main_text) +
479 " sub-message=" +
480 base::UTF16ToUTF8(wrapped_sub_text) + "\n");
483 std::string WebTestProxyBase::CaptureTree(
484 bool debug_render_tree,
485 bool dump_line_box_trees) {
486 bool should_dump_custom_text =
487 test_interfaces_->GetTestRunner()->shouldDumpAsCustomText();
488 bool should_dump_as_text =
489 test_interfaces_->GetTestRunner()->shouldDumpAsText();
490 bool should_dump_as_markup =
491 test_interfaces_->GetTestRunner()->shouldDumpAsMarkup();
492 bool should_dump_as_printed = test_interfaces_->GetTestRunner()->isPrinting();
493 blink::WebFrame* frame = GetWebView()->mainFrame();
494 std::string data_utf8;
495 if (should_dump_custom_text) {
496 // Append a newline for the test driver.
497 data_utf8 = test_interfaces_->GetTestRunner()->customDumpText() + "\n";
498 } else if (should_dump_as_text) {
499 bool recursive =
500 test_interfaces_->GetTestRunner()->shouldDumpChildFramesAsText();
501 data_utf8 = should_dump_as_printed ?
502 DumpFramesAsPrintedText(frame, recursive) :
503 DumpFramesAsText(frame, recursive);
504 } else if (should_dump_as_markup) {
505 bool recursive =
506 test_interfaces_->GetTestRunner()->shouldDumpChildFramesAsMarkup();
507 // Append a newline for the test driver.
508 data_utf8 = DumpFramesAsMarkup(frame, recursive);
509 } else {
510 bool recursive = test_interfaces_->GetTestRunner()
511 ->shouldDumpChildFrameScrollPositions();
512 blink::WebFrame::LayoutAsTextControls layout_text_behavior =
513 blink::WebFrame::LayoutAsTextNormal;
514 if (should_dump_as_printed)
515 layout_text_behavior |= blink::WebFrame::LayoutAsTextPrinting;
516 if (debug_render_tree)
517 layout_text_behavior |= blink::WebFrame::LayoutAsTextDebug;
518 if (dump_line_box_trees)
519 layout_text_behavior |= blink::WebFrame::LayoutAsTextWithLineTrees;
520 data_utf8 = frame->layoutTreeAsText(layout_text_behavior).utf8();
521 data_utf8 += DumpFrameScrollPosition(frame, recursive);
524 if (test_interfaces_->GetTestRunner()->ShouldDumpBackForwardList())
525 data_utf8 += DumpAllBackForwardLists(test_interfaces_, delegate_);
527 return data_utf8;
530 void WebTestProxyBase::DrawSelectionRect(SkCanvas* canvas) {
531 // See if we need to draw the selection bounds rect. Selection bounds
532 // rect is the rect enclosing the (possibly transformed) selection.
533 // The rect should be drawn after everything is laid out and painted.
534 if (!test_interfaces_->GetTestRunner()->shouldDumpSelectionRect())
535 return;
536 // If there is a selection rect - draw a red 1px border enclosing rect
537 blink::WebRect wr = GetWebView()->mainFrame()->selectionBoundsRect();
538 if (wr.isEmpty())
539 return;
540 // Render a red rectangle bounding selection rect
541 SkPaint paint;
542 paint.setColor(0xFFFF0000); // Fully opaque red
543 paint.setStyle(SkPaint::kStroke_Style);
544 paint.setFlags(SkPaint::kAntiAlias_Flag);
545 paint.setStrokeWidth(1.0f);
546 SkIRect rect; // Bounding rect
547 rect.set(wr.x, wr.y, wr.x + wr.width, wr.y + wr.height);
548 canvas->drawIRect(rect, paint);
551 void WebTestProxyBase::SetAcceptLanguages(const std::string& accept_languages) {
552 bool notify = accept_languages_ != accept_languages;
553 accept_languages_ = accept_languages;
555 if (notify)
556 GetWebView()->acceptLanguagesChanged();
559 void WebTestProxyBase::CopyImageAtAndCapturePixels(
560 int x, int y, const base::Callback<void(const SkBitmap&)>& callback) {
561 DCHECK(!callback.is_null());
562 uint64_t sequence_number = blink::Platform::current()->clipboard()->
563 sequenceNumber(blink::WebClipboard::Buffer());
564 GetWebView()->copyImageAt(blink::WebPoint(x, y));
565 if (sequence_number == blink::Platform::current()->clipboard()->
566 sequenceNumber(blink::WebClipboard::Buffer())) {
567 SkBitmap emptyBitmap;
568 callback.Run(emptyBitmap);
569 return;
572 blink::WebData data = blink::Platform::current()->clipboard()->readImage(
573 blink::WebClipboard::Buffer());
574 blink::WebImage image = blink::WebImage::fromData(data, blink::WebSize());
575 const SkBitmap& bitmap = image.getSkBitmap();
576 SkAutoLockPixels autoLock(bitmap);
577 callback.Run(bitmap);
580 void WebTestProxyBase::CapturePixelsForPrinting(
581 const base::Callback<void(const SkBitmap&)>& callback) {
582 web_widget_->layout();
584 blink::WebSize page_size_in_pixels = web_widget_->size();
585 blink::WebFrame* web_frame = GetWebView()->mainFrame();
587 int page_count = web_frame->printBegin(page_size_in_pixels);
588 int totalHeight = page_count * (page_size_in_pixels.height + 1) - 1;
590 bool is_opaque = false;
591 skia::RefPtr<SkCanvas> canvas(skia::AdoptRef(skia::TryCreateBitmapCanvas(
592 page_size_in_pixels.width, totalHeight, is_opaque)));
593 if (!canvas) {
594 callback.Run(SkBitmap());
595 return;
597 web_frame->printPagesWithBoundaries(canvas.get(), page_size_in_pixels);
598 web_frame->printEnd();
600 DrawSelectionRect(canvas.get());
601 SkBaseDevice* device = skia::GetTopDevice(*canvas);
602 const SkBitmap& bitmap = device->accessBitmap(false);
603 callback.Run(bitmap);
606 CaptureCallback::CaptureCallback(
607 const base::Callback<void(const SkBitmap&)>& callback)
608 : callback_(callback), wait_for_popup_(false) {
611 CaptureCallback::~CaptureCallback() {
614 void CaptureCallback::didCompositeAndReadback(const SkBitmap& bitmap) {
615 TRACE_EVENT2("shell",
616 "CaptureCallback::didCompositeAndReadback",
617 "x",
618 bitmap.info().width(),
619 "y",
620 bitmap.info().height());
621 if (!wait_for_popup_) {
622 callback_.Run(bitmap);
623 delete this;
624 return;
626 if (main_bitmap_.isNull()) {
627 bitmap.deepCopyTo(&main_bitmap_);
628 return;
630 SkCanvas canvas(main_bitmap_);
631 canvas.drawBitmap(bitmap, popup_position_.x(), popup_position_.y());
632 callback_.Run(main_bitmap_);
633 delete this;
636 void WebTestProxyBase::CapturePixelsAsync(
637 const base::Callback<void(const SkBitmap&)>& callback) {
638 TRACE_EVENT0("shell", "WebTestProxyBase::CapturePixelsAsync");
639 DCHECK(!callback.is_null());
641 if (test_interfaces_->GetTestRunner()->shouldDumpDragImage()) {
642 if (drag_image_.isNull()) {
643 // This means the test called dumpDragImage but did not initiate a drag.
644 // Return a blank image so that the test fails.
645 SkBitmap bitmap;
646 bitmap.allocN32Pixels(1, 1);
648 SkAutoLockPixels lock(bitmap);
649 bitmap.eraseColor(0);
651 callback.Run(bitmap);
652 return;
655 callback.Run(drag_image_.getSkBitmap());
656 return;
659 if (test_interfaces_->GetTestRunner()->isPrinting()) {
660 base::ThreadTaskRunnerHandle::Get()->PostTask(
661 FROM_HERE, base::Bind(&WebTestProxyBase::CapturePixelsForPrinting,
662 base::Unretained(this), callback));
663 return;
666 CaptureCallback* capture_callback = new CaptureCallback(base::Bind(
667 &WebTestProxyBase::DidCapturePixelsAsync, base::Unretained(this),
668 callback));
669 web_widget_->compositeAndReadbackAsync(capture_callback);
670 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
671 capture_callback->set_wait_for_popup(true);
672 capture_callback->set_popup_position(popup->positionRelativeToOwner());
673 popup->compositeAndReadbackAsync(capture_callback);
677 void WebTestProxyBase::DidCapturePixelsAsync(
678 const base::Callback<void(const SkBitmap&)>& callback,
679 const SkBitmap& bitmap) {
680 SkCanvas canvas(bitmap);
681 DrawSelectionRect(&canvas);
682 if (!callback.is_null())
683 callback.Run(bitmap);
686 void WebTestProxyBase::SetLogConsoleOutput(bool enabled) {
687 log_console_output_ = enabled;
690 void LayoutAndPaintCallback::didLayoutAndPaint() {
691 TRACE_EVENT0("shell", "LayoutAndPaintCallback::didLayoutAndPaint");
692 if (wait_for_popup_) {
693 wait_for_popup_ = false;
694 return;
697 if (!callback_.is_null())
698 callback_.Run();
699 delete this;
702 void WebTestProxyBase::LayoutAndPaintAsyncThen(const base::Closure& callback) {
703 TRACE_EVENT0("shell", "WebTestProxyBase::LayoutAndPaintAsyncThen");
705 LayoutAndPaintCallback* layout_and_paint_callback =
706 new LayoutAndPaintCallback(callback);
707 web_widget_->layoutAndPaintAsync(layout_and_paint_callback);
708 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
709 layout_and_paint_callback->set_wait_for_popup(true);
710 popup->layoutAndPaintAsync(layout_and_paint_callback);
714 void WebTestProxyBase::GetScreenOrientationForTesting(
715 blink::WebScreenInfo& screen_info) {
716 if (!screen_orientation_client_)
717 return;
718 // Override screen orientation information with mock data.
719 screen_info.orientationType =
720 screen_orientation_client_->CurrentOrientationType();
721 screen_info.orientationAngle =
722 screen_orientation_client_->CurrentOrientationAngle();
725 MockScreenOrientationClient*
726 WebTestProxyBase::GetScreenOrientationClientMock() {
727 if (!screen_orientation_client_.get()) {
728 screen_orientation_client_.reset(new MockScreenOrientationClient);
730 return screen_orientation_client_.get();
733 MockWebSpeechRecognizer* WebTestProxyBase::GetSpeechRecognizerMock() {
734 if (!speech_recognizer_.get()) {
735 speech_recognizer_.reset(new MockWebSpeechRecognizer());
736 speech_recognizer_->SetDelegate(delegate_);
738 return speech_recognizer_.get();
741 MockCredentialManagerClient*
742 WebTestProxyBase::GetCredentialManagerClientMock() {
743 if (!credential_manager_client_.get())
744 credential_manager_client_.reset(new MockCredentialManagerClient());
745 return credential_manager_client_.get();
748 void WebTestProxyBase::ScheduleAnimation() {
749 if (!test_interfaces_->GetTestRunner()->TestIsRunning())
750 return;
752 if (!animate_scheduled_) {
753 animate_scheduled_ = true;
754 delegate_->PostDelayedTask(
755 new HostMethodTask(this, &WebTestProxyBase::AnimateNow), 1);
759 void WebTestProxyBase::AnimateNow() {
760 if (animate_scheduled_) {
761 animate_scheduled_ = false;
762 web_widget_->beginFrame(blink::WebBeginFrameArgs(0.0, 0.0, 0.0));
763 web_widget_->layout();
764 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
765 popup->beginFrame(blink::WebBeginFrameArgs(0.0, 0.0, 0.0));
766 popup->layout();
771 void WebTestProxyBase::PostAccessibilityEvent(const blink::WebAXObject& obj,
772 blink::WebAXEvent event) {
773 // Only hook the accessibility events occured during the test run.
774 // This check prevents false positives in WebLeakDetector.
775 // The pending tasks in browser/renderer message queue may trigger
776 // accessibility events,
777 // and AccessibilityController will hold on to their target nodes if we don't
778 // ignore them here.
779 if (!test_interfaces_->GetTestRunner()->TestIsRunning())
780 return;
782 if (event == blink::WebAXEventFocus)
783 test_interfaces_->GetAccessibilityController()->SetFocusedElement(obj);
785 const char* event_name = NULL;
786 switch (event) {
787 case blink::WebAXEventActiveDescendantChanged:
788 event_name = "ActiveDescendantChanged";
789 break;
790 case blink::WebAXEventAlert:
791 event_name = "Alert";
792 break;
793 case blink::WebAXEventAriaAttributeChanged:
794 event_name = "AriaAttributeChanged";
795 break;
796 case blink::WebAXEventAutocorrectionOccured:
797 event_name = "AutocorrectionOccured";
798 break;
799 case blink::WebAXEventBlur:
800 event_name = "Blur";
801 break;
802 case blink::WebAXEventCheckedStateChanged:
803 event_name = "CheckedStateChanged";
804 break;
805 case blink::WebAXEventChildrenChanged:
806 event_name = "ChildrenChanged";
807 break;
808 case blink::WebAXEventFocus:
809 event_name = "Focus";
810 break;
811 case blink::WebAXEventHide:
812 event_name = "Hide";
813 break;
814 case blink::WebAXEventInvalidStatusChanged:
815 event_name = "InvalidStatusChanged";
816 break;
817 case blink::WebAXEventLayoutComplete:
818 event_name = "LayoutComplete";
819 break;
820 case blink::WebAXEventLiveRegionChanged:
821 event_name = "LiveRegionChanged";
822 break;
823 case blink::WebAXEventLoadComplete:
824 event_name = "LoadComplete";
825 break;
826 case blink::WebAXEventLocationChanged:
827 event_name = "LocationChanged";
828 break;
829 case blink::WebAXEventMenuListItemSelected:
830 event_name = "MenuListItemSelected";
831 break;
832 case blink::WebAXEventMenuListItemUnselected:
833 event_name = "MenuListItemUnselected";
834 break;
835 case blink::WebAXEventMenuListValueChanged:
836 event_name = "MenuListValueChanged";
837 break;
838 case blink::WebAXEventRowCollapsed:
839 event_name = "RowCollapsed";
840 break;
841 case blink::WebAXEventRowCountChanged:
842 event_name = "RowCountChanged";
843 break;
844 case blink::WebAXEventRowExpanded:
845 event_name = "RowExpanded";
846 break;
847 case blink::WebAXEventScrollPositionChanged:
848 event_name = "ScrollPositionChanged";
849 break;
850 case blink::WebAXEventScrolledToAnchor:
851 event_name = "ScrolledToAnchor";
852 break;
853 case blink::WebAXEventSelectedChildrenChanged:
854 event_name = "SelectedChildrenChanged";
855 break;
856 case blink::WebAXEventSelectedTextChanged:
857 event_name = "SelectedTextChanged";
858 break;
859 case blink::WebAXEventShow:
860 event_name = "Show";
861 break;
862 case blink::WebAXEventTextChanged:
863 event_name = "TextChanged";
864 break;
865 case blink::WebAXEventTextInserted:
866 event_name = "TextInserted";
867 break;
868 case blink::WebAXEventTextRemoved:
869 event_name = "TextRemoved";
870 break;
871 case blink::WebAXEventValueChanged:
872 event_name = "ValueChanged";
873 break;
874 default:
875 event_name = "Unknown";
876 break;
879 test_interfaces_->GetAccessibilityController()->NotificationReceived(
880 obj, event_name);
882 if (test_interfaces_->GetAccessibilityController()
883 ->ShouldLogAccessibilityEvents()) {
884 std::string message("AccessibilityNotification - ");
885 message += event_name;
887 blink::WebNode node = obj.node();
888 if (!node.isNull() && node.isElementNode()) {
889 blink::WebElement element = node.to<blink::WebElement>();
890 if (element.hasAttribute("id")) {
891 message += " - id:";
892 message += element.getAttribute("id").utf8().data();
896 delegate_->PrintMessage(message + "\n");
900 void WebTestProxyBase::StartDragging(blink::WebLocalFrame* frame,
901 const blink::WebDragData& data,
902 blink::WebDragOperationsMask mask,
903 const blink::WebImage& image,
904 const blink::WebPoint& point) {
905 if (test_interfaces_->GetTestRunner()->shouldDumpDragImage()) {
906 if (drag_image_.isNull())
907 drag_image_ = image;
909 // When running a test, we need to fake a drag drop operation otherwise
910 // Windows waits for real mouse events to know when the drag is over.
911 test_interfaces_->GetEventSender()->DoDragDrop(data, mask);
914 // The output from these methods in layout test mode should match that
915 // expected by the layout tests. See EditingDelegate.m in DumpRenderTree.
917 void WebTestProxyBase::DidChangeSelection(bool is_empty_callback) {
918 if (test_interfaces_->GetTestRunner()->shouldDumpEditingCallbacks())
919 delegate_->PrintMessage(
920 "EDITING DELEGATE: "
921 "webViewDidChangeSelection:WebViewDidChangeSelectionNotification\n");
924 void WebTestProxyBase::DidChangeContents() {
925 if (test_interfaces_->GetTestRunner()->shouldDumpEditingCallbacks())
926 delegate_->PrintMessage(
927 "EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification\n");
930 bool WebTestProxyBase::CreateView(blink::WebLocalFrame* frame,
931 const blink::WebURLRequest& request,
932 const blink::WebWindowFeatures& features,
933 const blink::WebString& frame_name,
934 blink::WebNavigationPolicy policy,
935 bool suppress_opener) {
936 if (test_interfaces_->GetTestRunner()->shouldDumpNavigationPolicy()) {
937 delegate_->PrintMessage("Default policy for createView for '" +
938 URLDescription(request.url()) + "' is '" +
939 WebNavigationPolicyToString(policy) + "'\n");
942 if (!test_interfaces_->GetTestRunner()->canOpenWindows())
943 return false;
944 if (test_interfaces_->GetTestRunner()->shouldDumpCreateView())
945 delegate_->PrintMessage(std::string("createView(") +
946 URLDescription(request.url()) + ")\n");
947 return true;
950 blink::WebPlugin* WebTestProxyBase::CreatePlugin(
951 blink::WebLocalFrame* frame,
952 const blink::WebPluginParams& params) {
953 if (TestPlugin::IsSupportedMimeType(params.mimeType))
954 return TestPlugin::create(frame, params, delegate_);
955 return delegate_->CreatePluginPlaceholder(frame, params);
958 void WebTestProxyBase::SetStatusText(const blink::WebString& text) {
959 if (!test_interfaces_->GetTestRunner()->shouldDumpStatusCallbacks())
960 return;
961 delegate_->PrintMessage(
962 std::string("UI DELEGATE STATUS CALLBACK: setStatusText:") +
963 text.utf8().data() + "\n");
966 void WebTestProxyBase::DidStopLoading() {
967 if (test_interfaces_->GetTestRunner()->shouldDumpProgressFinishedCallback())
968 delegate_->PrintMessage("postProgressFinishedNotification\n");
971 void WebTestProxyBase::ShowContextMenu(
972 const blink::WebContextMenuData& context_menu_data) {
973 test_interfaces_->GetEventSender()->SetContextMenuData(context_menu_data);
976 blink::WebUserMediaClient* WebTestProxyBase::GetUserMediaClient() {
977 if (!user_media_client_.get())
978 user_media_client_.reset(new MockWebUserMediaClient(delegate_));
979 return user_media_client_.get();
982 // Simulate a print by going into print mode and then exit straight away.
983 void WebTestProxyBase::PrintPage(blink::WebLocalFrame* frame) {
984 blink::WebSize page_size_in_pixels = web_widget_->size();
985 if (page_size_in_pixels.isEmpty())
986 return;
987 blink::WebPrintParams printParams(page_size_in_pixels);
988 frame->printBegin(printParams);
989 frame->printEnd();
992 blink::WebSpeechRecognizer* WebTestProxyBase::GetSpeechRecognizer() {
993 return GetSpeechRecognizerMock();
996 bool WebTestProxyBase::RequestPointerLock() {
997 return test_interfaces_->GetTestRunner()->RequestPointerLock();
1000 void WebTestProxyBase::RequestPointerUnlock() {
1001 test_interfaces_->GetTestRunner()->RequestPointerUnlock();
1004 bool WebTestProxyBase::IsPointerLocked() {
1005 return test_interfaces_->GetTestRunner()->isPointerLocked();
1008 void WebTestProxyBase::DidFocus() {
1009 delegate_->SetFocus(this, true);
1012 void WebTestProxyBase::DidBlur() {
1013 delegate_->SetFocus(this, false);
1016 void WebTestProxyBase::SetToolTipText(const blink::WebString& text,
1017 blink::WebTextDirection direction) {
1018 test_interfaces_->GetTestRunner()->setToolTipText(text);
1021 void WebTestProxyBase::DidOpenChooser() {
1022 chooser_count_++;
1025 void WebTestProxyBase::DidCloseChooser() {
1026 chooser_count_--;
1029 bool WebTestProxyBase::IsChooserShown() {
1030 return 0 < chooser_count_;
1033 void WebTestProxyBase::LoadURLExternally(
1034 blink::WebLocalFrame* frame,
1035 const blink::WebURLRequest& request,
1036 blink::WebNavigationPolicy policy,
1037 const blink::WebString& suggested_name) {
1038 if (test_interfaces_->GetTestRunner()->shouldWaitUntilExternalURLLoad()) {
1039 if (policy == blink::WebNavigationPolicyDownload) {
1040 delegate_->PrintMessage(
1041 std::string("Downloading URL with suggested filename \"") +
1042 suggested_name.utf8() + "\"\n");
1043 } else {
1044 delegate_->PrintMessage(std::string("Loading URL externally - \"") +
1045 URLDescription(request.url()) + "\"\n");
1047 delegate_->TestFinished();
1051 void WebTestProxyBase::DidStartProvisionalLoad(blink::WebLocalFrame* frame) {
1052 if (!test_interfaces_->GetTestRunner()->topLoadingFrame())
1053 test_interfaces_->GetTestRunner()->setTopLoadingFrame(frame, false);
1055 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1056 PrintFrameDescription(delegate_, frame);
1057 delegate_->PrintMessage(" - didStartProvisionalLoadForFrame\n");
1060 if (test_interfaces_->GetTestRunner()
1061 ->shouldDumpUserGestureInFrameLoadCallbacks()) {
1062 PrintFrameuserGestureStatus(
1063 delegate_, frame, " - in didStartProvisionalLoadForFrame\n");
1067 void WebTestProxyBase::DidReceiveServerRedirectForProvisionalLoad(
1068 blink::WebLocalFrame* frame) {
1069 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1070 PrintFrameDescription(delegate_, frame);
1071 delegate_->PrintMessage(
1072 " - didReceiveServerRedirectForProvisionalLoadForFrame\n");
1076 bool WebTestProxyBase::DidFailProvisionalLoad(
1077 blink::WebLocalFrame* frame,
1078 const blink::WebURLError& error,
1079 blink::WebHistoryCommitType commit_type) {
1080 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1081 PrintFrameDescription(delegate_, frame);
1082 delegate_->PrintMessage(" - didFailProvisionalLoadWithError\n");
1084 CheckDone(frame, MainResourceLoadFailed);
1085 return !frame->provisionalDataSource();
1088 void WebTestProxyBase::DidCommitProvisionalLoad(
1089 blink::WebLocalFrame* frame,
1090 const blink::WebHistoryItem& history_item,
1091 blink::WebHistoryCommitType history_type) {
1092 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1093 PrintFrameDescription(delegate_, frame);
1094 delegate_->PrintMessage(" - didCommitLoadForFrame\n");
1098 void WebTestProxyBase::DidReceiveTitle(blink::WebLocalFrame* frame,
1099 const blink::WebString& title,
1100 blink::WebTextDirection direction) {
1101 blink::WebCString title8 = title.utf8();
1103 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1104 PrintFrameDescription(delegate_, frame);
1105 delegate_->PrintMessage(std::string(" - didReceiveTitle: ") +
1106 title8.data() + "\n");
1109 if (test_interfaces_->GetTestRunner()->shouldDumpTitleChanges())
1110 delegate_->PrintMessage(std::string("TITLE CHANGED: '") + title8.data() +
1111 "'\n");
1114 void WebTestProxyBase::DidChangeIcon(blink::WebLocalFrame* frame,
1115 blink::WebIconURL::Type icon_type) {
1116 if (test_interfaces_->GetTestRunner()->shouldDumpIconChanges()) {
1117 PrintFrameDescription(delegate_, frame);
1118 delegate_->PrintMessage(std::string(" - didChangeIcons\n"));
1122 void WebTestProxyBase::DidFinishDocumentLoad(blink::WebLocalFrame* frame) {
1123 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1124 PrintFrameDescription(delegate_, frame);
1125 delegate_->PrintMessage(" - didFinishDocumentLoadForFrame\n");
1129 void WebTestProxyBase::DidHandleOnloadEvents(blink::WebLocalFrame* frame) {
1130 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1131 PrintFrameDescription(delegate_, frame);
1132 delegate_->PrintMessage(" - didHandleOnloadEventsForFrame\n");
1136 void WebTestProxyBase::DidFailLoad(blink::WebLocalFrame* frame,
1137 const blink::WebURLError& error,
1138 blink::WebHistoryCommitType commit_type) {
1139 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1140 PrintFrameDescription(delegate_, frame);
1141 delegate_->PrintMessage(" - didFailLoadWithError\n");
1143 CheckDone(frame, MainResourceLoadFailed);
1146 void WebTestProxyBase::DidFinishLoad(blink::WebLocalFrame* frame) {
1147 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1148 PrintFrameDescription(delegate_, frame);
1149 delegate_->PrintMessage(" - didFinishLoadForFrame\n");
1151 CheckDone(frame, LoadFinished);
1154 void WebTestProxyBase::DidDetectXSS(blink::WebLocalFrame* frame,
1155 const blink::WebURL& insecure_url,
1156 bool did_block_entire_page) {
1157 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks())
1158 delegate_->PrintMessage("didDetectXSS\n");
1161 void WebTestProxyBase::DidDispatchPingLoader(blink::WebLocalFrame* frame,
1162 const blink::WebURL& url) {
1163 if (test_interfaces_->GetTestRunner()->shouldDumpPingLoaderCallbacks())
1164 delegate_->PrintMessage(std::string("PingLoader dispatched to '") +
1165 URLDescription(url).c_str() + "'.\n");
1168 void WebTestProxyBase::WillRequestResource(
1169 blink::WebLocalFrame* frame,
1170 const blink::WebCachedURLRequest& request) {
1171 if (test_interfaces_->GetTestRunner()->shouldDumpResourceRequestCallbacks()) {
1172 PrintFrameDescription(delegate_, frame);
1173 delegate_->PrintMessage(std::string(" - ") +
1174 request.initiatorName().utf8().data());
1175 delegate_->PrintMessage(std::string(" requested '") +
1176 URLDescription(request.urlRequest().url()).c_str() +
1177 "'\n");
1181 void WebTestProxyBase::WillSendRequest(
1182 blink::WebLocalFrame* frame,
1183 unsigned identifier,
1184 blink::WebURLRequest& request,
1185 const blink::WebURLResponse& redirect_response) {
1186 // Need to use GURL for host() and SchemeIs()
1187 GURL url = request.url();
1188 std::string request_url = url.possibly_invalid_spec();
1190 GURL main_document_url = request.firstPartyForCookies();
1192 if (redirect_response.isNull() &&
1193 (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks() ||
1194 test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities())) {
1195 DCHECK(resource_identifier_map_.find(identifier) ==
1196 resource_identifier_map_.end());
1197 resource_identifier_map_[identifier] =
1198 DescriptionSuitableForTestResult(request_url);
1201 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1202 if (resource_identifier_map_.find(identifier) ==
1203 resource_identifier_map_.end())
1204 delegate_->PrintMessage("<unknown>");
1205 else
1206 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1207 delegate_->PrintMessage(" - willSendRequest <NSURLRequest URL ");
1208 delegate_->PrintMessage(
1209 DescriptionSuitableForTestResult(request_url).c_str());
1210 delegate_->PrintMessage(", main document URL ");
1211 delegate_->PrintMessage(URLDescription(main_document_url).c_str());
1212 delegate_->PrintMessage(", http method ");
1213 delegate_->PrintMessage(request.httpMethod().utf8().data());
1214 delegate_->PrintMessage("> redirectResponse ");
1215 PrintResponseDescription(delegate_, redirect_response);
1216 delegate_->PrintMessage("\n");
1219 if (test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities()) {
1220 delegate_->PrintMessage(
1221 DescriptionSuitableForTestResult(request_url).c_str());
1222 delegate_->PrintMessage(" has priority ");
1223 delegate_->PrintMessage(PriorityDescription(request.priority()));
1224 delegate_->PrintMessage("\n");
1227 if (test_interfaces_->GetTestRunner()->httpHeadersToClear()) {
1228 const std::set<std::string>* clearHeaders =
1229 test_interfaces_->GetTestRunner()->httpHeadersToClear();
1230 for (std::set<std::string>::const_iterator header = clearHeaders->begin();
1231 header != clearHeaders->end();
1232 ++header)
1233 request.clearHTTPHeaderField(blink::WebString::fromUTF8(*header));
1236 std::string host = url.host();
1237 if (!host.empty() &&
1238 (url.SchemeIs(url::kHttpScheme) || url.SchemeIs(url::kHttpsScheme))) {
1239 if (!IsLocalHost(host) && !IsTestHost(host) &&
1240 !HostIsUsedBySomeTestsToGenerateError(host) &&
1241 ((!main_document_url.SchemeIs(url::kHttpScheme) &&
1242 !main_document_url.SchemeIs(url::kHttpsScheme)) ||
1243 IsLocalHost(main_document_url.host())) &&
1244 !delegate_->AllowExternalPages()) {
1245 delegate_->PrintMessage(std::string("Blocked access to external URL ") +
1246 request_url + "\n");
1247 BlockRequest(request);
1248 return;
1252 // Set the new substituted URL.
1253 request.setURL(delegate_->RewriteLayoutTestsURL(request.url().spec()));
1256 void WebTestProxyBase::DidReceiveResponse(
1257 blink::WebLocalFrame* frame,
1258 unsigned identifier,
1259 const blink::WebURLResponse& response) {
1260 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1261 if (resource_identifier_map_.find(identifier) ==
1262 resource_identifier_map_.end())
1263 delegate_->PrintMessage("<unknown>");
1264 else
1265 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1266 delegate_->PrintMessage(" - didReceiveResponse ");
1267 PrintResponseDescription(delegate_, response);
1268 delegate_->PrintMessage("\n");
1270 if (test_interfaces_->GetTestRunner()
1271 ->shouldDumpResourceResponseMIMETypes()) {
1272 GURL url = response.url();
1273 blink::WebString mime_type = response.mimeType();
1274 delegate_->PrintMessage(url.ExtractFileName());
1275 delegate_->PrintMessage(" has MIME type ");
1276 // Simulate NSURLResponse's mapping of empty/unknown MIME types to
1277 // application/octet-stream
1278 delegate_->PrintMessage(mime_type.isEmpty() ? "application/octet-stream"
1279 : mime_type.utf8().data());
1280 delegate_->PrintMessage("\n");
1284 void WebTestProxyBase::DidChangeResourcePriority(
1285 blink::WebLocalFrame* frame,
1286 unsigned identifier,
1287 const blink::WebURLRequest::Priority& priority,
1288 int intra_priority_value) {
1289 if (test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities()) {
1290 if (resource_identifier_map_.find(identifier) ==
1291 resource_identifier_map_.end())
1292 delegate_->PrintMessage("<unknown>");
1293 else
1294 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1295 delegate_->PrintMessage(
1296 base::StringPrintf(" changed priority to %s, intra_priority %d\n",
1297 PriorityDescription(priority).c_str(),
1298 intra_priority_value));
1302 void WebTestProxyBase::DidFinishResourceLoad(blink::WebLocalFrame* frame,
1303 unsigned identifier) {
1304 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1305 if (resource_identifier_map_.find(identifier) ==
1306 resource_identifier_map_.end())
1307 delegate_->PrintMessage("<unknown>");
1308 else
1309 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1310 delegate_->PrintMessage(" - didFinishLoading\n");
1312 resource_identifier_map_.erase(identifier);
1313 CheckDone(frame, ResourceLoadCompleted);
1316 void WebTestProxyBase::DidAddMessageToConsole(
1317 const blink::WebConsoleMessage& message,
1318 const blink::WebString& source_name,
1319 unsigned source_line) {
1320 // This matches win DumpRenderTree's UIDelegate.cpp.
1321 if (!log_console_output_)
1322 return;
1323 std::string level;
1324 switch (message.level) {
1325 case blink::WebConsoleMessage::LevelDebug:
1326 level = "DEBUG";
1327 break;
1328 case blink::WebConsoleMessage::LevelLog:
1329 level = "MESSAGE";
1330 break;
1331 case blink::WebConsoleMessage::LevelInfo:
1332 level = "INFO";
1333 break;
1334 case blink::WebConsoleMessage::LevelWarning:
1335 level = "WARNING";
1336 break;
1337 case blink::WebConsoleMessage::LevelError:
1338 level = "ERROR";
1339 break;
1340 default:
1341 level = "MESSAGE";
1343 delegate_->PrintMessage(std::string("CONSOLE ") + level + ": ");
1344 if (source_line) {
1345 delegate_->PrintMessage(base::StringPrintf("line %d: ", source_line));
1347 if (!message.text.isEmpty()) {
1348 std::string new_message;
1349 new_message = message.text.utf8();
1350 size_t file_protocol = new_message.find("file://");
1351 if (file_protocol != std::string::npos) {
1352 new_message = new_message.substr(0, file_protocol) +
1353 URLSuitableForTestResult(new_message.substr(file_protocol));
1355 delegate_->PrintMessage(new_message);
1357 delegate_->PrintMessage(std::string("\n"));
1360 void WebTestProxyBase::CheckDone(blink::WebLocalFrame* frame,
1361 CheckDoneReason reason) {
1362 if (frame != test_interfaces_->GetTestRunner()->topLoadingFrame())
1363 return;
1364 if (reason != MainResourceLoadFailed &&
1365 (frame->isResourceLoadInProgress() || frame->isLoading()))
1366 return;
1367 test_interfaces_->GetTestRunner()->setTopLoadingFrame(frame, true);
1370 blink::WebNavigationPolicy WebTestProxyBase::DecidePolicyForNavigation(
1371 const blink::WebFrameClient::NavigationPolicyInfo& info) {
1372 if (test_interfaces_->GetTestRunner()->shouldDumpNavigationPolicy()) {
1373 delegate_->PrintMessage("Default policy for navigation to '" +
1374 URLDescription(info.urlRequest.url()) + "' is '" +
1375 WebNavigationPolicyToString(info.defaultPolicy) +
1376 "'\n");
1379 blink::WebNavigationPolicy result;
1380 if (!test_interfaces_->GetTestRunner()->policyDelegateEnabled())
1381 return info.defaultPolicy;
1383 delegate_->PrintMessage(
1384 std::string("Policy delegate: attempt to load ") +
1385 URLDescription(info.urlRequest.url()) + " with navigation type '" +
1386 WebNavigationTypeToString(info.navigationType) + "'\n");
1387 if (test_interfaces_->GetTestRunner()->policyDelegateIsPermissive())
1388 result = blink::WebNavigationPolicyCurrentTab;
1389 else
1390 result = blink::WebNavigationPolicyIgnore;
1392 if (test_interfaces_->GetTestRunner()->policyDelegateShouldNotifyDone()) {
1393 test_interfaces_->GetTestRunner()->policyDelegateDone();
1394 result = blink::WebNavigationPolicyIgnore;
1397 return result;
1400 bool WebTestProxyBase::WillCheckAndDispatchMessageEvent(
1401 blink::WebLocalFrame* source_frame,
1402 blink::WebFrame* target_frame,
1403 blink::WebSecurityOrigin target,
1404 blink::WebDOMMessageEvent event) {
1405 if (test_interfaces_->GetTestRunner()->shouldInterceptPostMessage()) {
1406 delegate_->PrintMessage("intercepted postMessage\n");
1407 return true;
1410 return false;
1413 void WebTestProxyBase::PostSpellCheckEvent(const blink::WebString& event_name) {
1414 if (test_interfaces_->GetTestRunner()->shouldDumpSpellCheckCallbacks()) {
1415 delegate_->PrintMessage(std::string("SpellCheckEvent: ") +
1416 event_name.utf8().data() + "\n");
1420 void WebTestProxyBase::ResetInputMethod() {
1421 // If a composition text exists, then we need to let the browser process
1422 // to cancel the input method's ongoing composition session.
1423 if (web_widget_)
1424 web_widget_->confirmComposition();
1427 blink::WebString WebTestProxyBase::acceptLanguages() {
1428 return blink::WebString::fromUTF8(accept_languages_);
1431 } // namespace test_runner