Remove uses of willRequestResouce in content shell
[chromium-blink-merge.git] / components / test_runner / web_test_proxy.cc
blob23f020db37573726c6a8f21b68937a90a0e0985b
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/test_runner/web_test_proxy.h"
7 #include <cctype>
9 #include "base/callback_helpers.h"
10 #include "base/command_line.h"
11 #include "base/i18n/rtl.h"
12 #include "base/logging.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/time/time.h"
18 #include "base/trace_event/trace_event.h"
19 #include "components/test_runner/accessibility_controller.h"
20 #include "components/test_runner/event_sender.h"
21 #include "components/test_runner/mock_color_chooser.h"
22 #include "components/test_runner/mock_credential_manager_client.h"
23 #include "components/test_runner/mock_screen_orientation_client.h"
24 #include "components/test_runner/mock_web_speech_recognizer.h"
25 #include "components/test_runner/mock_web_user_media_client.h"
26 #include "components/test_runner/spell_check_client.h"
27 #include "components/test_runner/test_interfaces.h"
28 #include "components/test_runner/test_plugin.h"
29 #include "components/test_runner/test_runner.h"
30 #include "components/test_runner/web_test_delegate.h"
31 #include "components/test_runner/web_test_interfaces.h"
32 #include "components/test_runner/web_test_runner.h"
33 // FIXME: Including platform_canvas.h here is a layering violation.
34 #include "skia/ext/platform_canvas.h"
35 #include "third_party/WebKit/public/platform/Platform.h"
36 #include "third_party/WebKit/public/platform/WebCString.h"
37 #include "third_party/WebKit/public/platform/WebClipboard.h"
38 #include "third_party/WebKit/public/platform/WebCompositeAndReadbackAsyncCallback.h"
39 #include "third_party/WebKit/public/platform/WebLayoutAndPaintAsyncCallback.h"
40 #include "third_party/WebKit/public/platform/WebURLError.h"
41 #include "third_party/WebKit/public/platform/WebURLRequest.h"
42 #include "third_party/WebKit/public/platform/WebURLResponse.h"
43 #include "third_party/WebKit/public/web/WebAXEnums.h"
44 #include "third_party/WebKit/public/web/WebAXObject.h"
45 #include "third_party/WebKit/public/web/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", base::CompareCase::INSENSITIVE_ASCII);
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 base::TimeDelta animate_time = base::TimeTicks::Now() - base::TimeTicks();
762 base::TimeDelta interval = base::TimeDelta::FromMicroseconds(16666);
763 blink::WebBeginFrameArgs args(animate_time.InSecondsF(),
764 (animate_time + interval).InSecondsF(),
765 interval.InSecondsF());
767 animate_scheduled_ = false;
768 web_widget_->beginFrame(args);
769 web_widget_->layout();
770 if (blink::WebPagePopup* popup = web_widget_->pagePopup()) {
771 popup->beginFrame(args);
772 popup->layout();
777 void WebTestProxyBase::PostAccessibilityEvent(const blink::WebAXObject& obj,
778 blink::WebAXEvent event) {
779 // Only hook the accessibility events occured during the test run.
780 // This check prevents false positives in WebLeakDetector.
781 // The pending tasks in browser/renderer message queue may trigger
782 // accessibility events,
783 // and AccessibilityController will hold on to their target nodes if we don't
784 // ignore them here.
785 if (!test_interfaces_->GetTestRunner()->TestIsRunning())
786 return;
788 if (event == blink::WebAXEventFocus)
789 test_interfaces_->GetAccessibilityController()->SetFocusedElement(obj);
791 const char* event_name = NULL;
792 switch (event) {
793 case blink::WebAXEventActiveDescendantChanged:
794 event_name = "ActiveDescendantChanged";
795 break;
796 case blink::WebAXEventAlert:
797 event_name = "Alert";
798 break;
799 case blink::WebAXEventAriaAttributeChanged:
800 event_name = "AriaAttributeChanged";
801 break;
802 case blink::WebAXEventAutocorrectionOccured:
803 event_name = "AutocorrectionOccured";
804 break;
805 case blink::WebAXEventBlur:
806 event_name = "Blur";
807 break;
808 case blink::WebAXEventCheckedStateChanged:
809 event_name = "CheckedStateChanged";
810 break;
811 case blink::WebAXEventChildrenChanged:
812 event_name = "ChildrenChanged";
813 break;
814 case blink::WebAXEventFocus:
815 event_name = "Focus";
816 break;
817 case blink::WebAXEventHide:
818 event_name = "Hide";
819 break;
820 case blink::WebAXEventInvalidStatusChanged:
821 event_name = "InvalidStatusChanged";
822 break;
823 case blink::WebAXEventLayoutComplete:
824 event_name = "LayoutComplete";
825 break;
826 case blink::WebAXEventLiveRegionChanged:
827 event_name = "LiveRegionChanged";
828 break;
829 case blink::WebAXEventLoadComplete:
830 event_name = "LoadComplete";
831 break;
832 case blink::WebAXEventLocationChanged:
833 event_name = "LocationChanged";
834 break;
835 case blink::WebAXEventMenuListItemSelected:
836 event_name = "MenuListItemSelected";
837 break;
838 case blink::WebAXEventMenuListItemUnselected:
839 event_name = "MenuListItemUnselected";
840 break;
841 case blink::WebAXEventMenuListValueChanged:
842 event_name = "MenuListValueChanged";
843 break;
844 case blink::WebAXEventRowCollapsed:
845 event_name = "RowCollapsed";
846 break;
847 case blink::WebAXEventRowCountChanged:
848 event_name = "RowCountChanged";
849 break;
850 case blink::WebAXEventRowExpanded:
851 event_name = "RowExpanded";
852 break;
853 case blink::WebAXEventScrollPositionChanged:
854 event_name = "ScrollPositionChanged";
855 break;
856 case blink::WebAXEventScrolledToAnchor:
857 event_name = "ScrolledToAnchor";
858 break;
859 case blink::WebAXEventSelectedChildrenChanged:
860 event_name = "SelectedChildrenChanged";
861 break;
862 case blink::WebAXEventSelectedTextChanged:
863 event_name = "SelectedTextChanged";
864 break;
865 case blink::WebAXEventShow:
866 event_name = "Show";
867 break;
868 case blink::WebAXEventTextChanged:
869 event_name = "TextChanged";
870 break;
871 case blink::WebAXEventTextInserted:
872 event_name = "TextInserted";
873 break;
874 case blink::WebAXEventTextRemoved:
875 event_name = "TextRemoved";
876 break;
877 case blink::WebAXEventValueChanged:
878 event_name = "ValueChanged";
879 break;
880 default:
881 event_name = "Unknown";
882 break;
885 test_interfaces_->GetAccessibilityController()->NotificationReceived(
886 obj, event_name);
888 if (test_interfaces_->GetAccessibilityController()
889 ->ShouldLogAccessibilityEvents()) {
890 std::string message("AccessibilityNotification - ");
891 message += event_name;
893 blink::WebNode node = obj.node();
894 if (!node.isNull() && node.isElementNode()) {
895 blink::WebElement element = node.to<blink::WebElement>();
896 if (element.hasAttribute("id")) {
897 message += " - id:";
898 message += element.getAttribute("id").utf8().data();
902 delegate_->PrintMessage(message + "\n");
906 void WebTestProxyBase::StartDragging(blink::WebLocalFrame* frame,
907 const blink::WebDragData& data,
908 blink::WebDragOperationsMask mask,
909 const blink::WebImage& image,
910 const blink::WebPoint& point) {
911 if (test_interfaces_->GetTestRunner()->shouldDumpDragImage()) {
912 if (drag_image_.isNull())
913 drag_image_ = image;
915 // When running a test, we need to fake a drag drop operation otherwise
916 // Windows waits for real mouse events to know when the drag is over.
917 test_interfaces_->GetEventSender()->DoDragDrop(data, mask);
920 // The output from these methods in layout test mode should match that
921 // expected by the layout tests. See EditingDelegate.m in DumpRenderTree.
923 void WebTestProxyBase::DidChangeSelection(bool is_empty_callback) {
924 if (test_interfaces_->GetTestRunner()->shouldDumpEditingCallbacks())
925 delegate_->PrintMessage(
926 "EDITING DELEGATE: "
927 "webViewDidChangeSelection:WebViewDidChangeSelectionNotification\n");
930 void WebTestProxyBase::DidChangeContents() {
931 if (test_interfaces_->GetTestRunner()->shouldDumpEditingCallbacks())
932 delegate_->PrintMessage(
933 "EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification\n");
936 bool WebTestProxyBase::CreateView(blink::WebLocalFrame* frame,
937 const blink::WebURLRequest& request,
938 const blink::WebWindowFeatures& features,
939 const blink::WebString& frame_name,
940 blink::WebNavigationPolicy policy,
941 bool suppress_opener) {
942 if (test_interfaces_->GetTestRunner()->shouldDumpNavigationPolicy()) {
943 delegate_->PrintMessage("Default policy for createView for '" +
944 URLDescription(request.url()) + "' is '" +
945 WebNavigationPolicyToString(policy) + "'\n");
948 if (!test_interfaces_->GetTestRunner()->canOpenWindows())
949 return false;
950 if (test_interfaces_->GetTestRunner()->shouldDumpCreateView())
951 delegate_->PrintMessage(std::string("createView(") +
952 URLDescription(request.url()) + ")\n");
953 return true;
956 blink::WebPlugin* WebTestProxyBase::CreatePlugin(
957 blink::WebLocalFrame* frame,
958 const blink::WebPluginParams& params) {
959 if (TestPlugin::IsSupportedMimeType(params.mimeType))
960 return TestPlugin::create(frame, params, delegate_);
961 return delegate_->CreatePluginPlaceholder(frame, params);
964 void WebTestProxyBase::SetStatusText(const blink::WebString& text) {
965 if (!test_interfaces_->GetTestRunner()->shouldDumpStatusCallbacks())
966 return;
967 delegate_->PrintMessage(
968 std::string("UI DELEGATE STATUS CALLBACK: setStatusText:") +
969 text.utf8().data() + "\n");
972 void WebTestProxyBase::DidStopLoading() {
973 if (test_interfaces_->GetTestRunner()->shouldDumpProgressFinishedCallback())
974 delegate_->PrintMessage("postProgressFinishedNotification\n");
977 void WebTestProxyBase::ShowContextMenu(
978 const blink::WebContextMenuData& context_menu_data) {
979 test_interfaces_->GetEventSender()->SetContextMenuData(context_menu_data);
982 blink::WebUserMediaClient* WebTestProxyBase::GetUserMediaClient() {
983 if (!user_media_client_.get())
984 user_media_client_.reset(new MockWebUserMediaClient(delegate_));
985 return user_media_client_.get();
988 // Simulate a print by going into print mode and then exit straight away.
989 void WebTestProxyBase::PrintPage(blink::WebLocalFrame* frame) {
990 blink::WebSize page_size_in_pixels = web_widget_->size();
991 if (page_size_in_pixels.isEmpty())
992 return;
993 blink::WebPrintParams printParams(page_size_in_pixels);
994 frame->printBegin(printParams);
995 frame->printEnd();
998 blink::WebSpeechRecognizer* WebTestProxyBase::GetSpeechRecognizer() {
999 return GetSpeechRecognizerMock();
1002 bool WebTestProxyBase::RequestPointerLock() {
1003 return test_interfaces_->GetTestRunner()->RequestPointerLock();
1006 void WebTestProxyBase::RequestPointerUnlock() {
1007 test_interfaces_->GetTestRunner()->RequestPointerUnlock();
1010 bool WebTestProxyBase::IsPointerLocked() {
1011 return test_interfaces_->GetTestRunner()->isPointerLocked();
1014 void WebTestProxyBase::DidFocus() {
1015 delegate_->SetFocus(this, true);
1018 void WebTestProxyBase::DidBlur() {
1019 delegate_->SetFocus(this, false);
1022 void WebTestProxyBase::SetToolTipText(const blink::WebString& text,
1023 blink::WebTextDirection direction) {
1024 test_interfaces_->GetTestRunner()->setToolTipText(text);
1027 void WebTestProxyBase::DidOpenChooser() {
1028 chooser_count_++;
1031 void WebTestProxyBase::DidCloseChooser() {
1032 chooser_count_--;
1035 bool WebTestProxyBase::IsChooserShown() {
1036 return 0 < chooser_count_;
1039 void WebTestProxyBase::LoadURLExternally(
1040 blink::WebLocalFrame* frame,
1041 const blink::WebURLRequest& request,
1042 blink::WebNavigationPolicy policy,
1043 const blink::WebString& suggested_name) {
1044 if (test_interfaces_->GetTestRunner()->shouldWaitUntilExternalURLLoad()) {
1045 if (policy == blink::WebNavigationPolicyDownload) {
1046 delegate_->PrintMessage(
1047 std::string("Downloading URL with suggested filename \"") +
1048 suggested_name.utf8() + "\"\n");
1049 } else {
1050 delegate_->PrintMessage(std::string("Loading URL externally - \"") +
1051 URLDescription(request.url()) + "\"\n");
1053 delegate_->TestFinished();
1057 void WebTestProxyBase::DidStartProvisionalLoad(blink::WebLocalFrame* frame) {
1058 if (!test_interfaces_->GetTestRunner()->topLoadingFrame())
1059 test_interfaces_->GetTestRunner()->setTopLoadingFrame(frame, false);
1061 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1062 PrintFrameDescription(delegate_, frame);
1063 delegate_->PrintMessage(" - didStartProvisionalLoadForFrame\n");
1066 if (test_interfaces_->GetTestRunner()
1067 ->shouldDumpUserGestureInFrameLoadCallbacks()) {
1068 PrintFrameuserGestureStatus(
1069 delegate_, frame, " - in didStartProvisionalLoadForFrame\n");
1073 void WebTestProxyBase::DidReceiveServerRedirectForProvisionalLoad(
1074 blink::WebLocalFrame* frame) {
1075 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1076 PrintFrameDescription(delegate_, frame);
1077 delegate_->PrintMessage(
1078 " - didReceiveServerRedirectForProvisionalLoadForFrame\n");
1082 bool WebTestProxyBase::DidFailProvisionalLoad(
1083 blink::WebLocalFrame* frame,
1084 const blink::WebURLError& error,
1085 blink::WebHistoryCommitType commit_type) {
1086 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1087 PrintFrameDescription(delegate_, frame);
1088 delegate_->PrintMessage(" - didFailProvisionalLoadWithError\n");
1090 CheckDone(frame, MainResourceLoadFailed);
1091 return !frame->provisionalDataSource();
1094 void WebTestProxyBase::DidCommitProvisionalLoad(
1095 blink::WebLocalFrame* frame,
1096 const blink::WebHistoryItem& history_item,
1097 blink::WebHistoryCommitType history_type) {
1098 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1099 PrintFrameDescription(delegate_, frame);
1100 delegate_->PrintMessage(" - didCommitLoadForFrame\n");
1104 void WebTestProxyBase::DidReceiveTitle(blink::WebLocalFrame* frame,
1105 const blink::WebString& title,
1106 blink::WebTextDirection direction) {
1107 blink::WebCString title8 = title.utf8();
1109 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1110 PrintFrameDescription(delegate_, frame);
1111 delegate_->PrintMessage(std::string(" - didReceiveTitle: ") +
1112 title8.data() + "\n");
1115 if (test_interfaces_->GetTestRunner()->shouldDumpTitleChanges())
1116 delegate_->PrintMessage(std::string("TITLE CHANGED: '") + title8.data() +
1117 "'\n");
1120 void WebTestProxyBase::DidChangeIcon(blink::WebLocalFrame* frame,
1121 blink::WebIconURL::Type icon_type) {
1122 if (test_interfaces_->GetTestRunner()->shouldDumpIconChanges()) {
1123 PrintFrameDescription(delegate_, frame);
1124 delegate_->PrintMessage(std::string(" - didChangeIcons\n"));
1128 void WebTestProxyBase::DidFinishDocumentLoad(blink::WebLocalFrame* frame) {
1129 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1130 PrintFrameDescription(delegate_, frame);
1131 delegate_->PrintMessage(" - didFinishDocumentLoadForFrame\n");
1135 void WebTestProxyBase::DidHandleOnloadEvents(blink::WebLocalFrame* frame) {
1136 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1137 PrintFrameDescription(delegate_, frame);
1138 delegate_->PrintMessage(" - didHandleOnloadEventsForFrame\n");
1142 void WebTestProxyBase::DidFailLoad(blink::WebLocalFrame* frame,
1143 const blink::WebURLError& error,
1144 blink::WebHistoryCommitType commit_type) {
1145 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1146 PrintFrameDescription(delegate_, frame);
1147 delegate_->PrintMessage(" - didFailLoadWithError\n");
1149 CheckDone(frame, MainResourceLoadFailed);
1152 void WebTestProxyBase::DidFinishLoad(blink::WebLocalFrame* frame) {
1153 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks()) {
1154 PrintFrameDescription(delegate_, frame);
1155 delegate_->PrintMessage(" - didFinishLoadForFrame\n");
1157 CheckDone(frame, LoadFinished);
1160 void WebTestProxyBase::DidDetectXSS(blink::WebLocalFrame* frame,
1161 const blink::WebURL& insecure_url,
1162 bool did_block_entire_page) {
1163 if (test_interfaces_->GetTestRunner()->shouldDumpFrameLoadCallbacks())
1164 delegate_->PrintMessage("didDetectXSS\n");
1167 void WebTestProxyBase::DidDispatchPingLoader(blink::WebLocalFrame* frame,
1168 const blink::WebURL& url) {
1169 if (test_interfaces_->GetTestRunner()->shouldDumpPingLoaderCallbacks())
1170 delegate_->PrintMessage(std::string("PingLoader dispatched to '") +
1171 URLDescription(url).c_str() + "'.\n");
1174 void WebTestProxyBase::WillSendRequest(
1175 blink::WebLocalFrame* frame,
1176 unsigned identifier,
1177 blink::WebURLRequest& request,
1178 const blink::WebURLResponse& redirect_response) {
1179 // Need to use GURL for host() and SchemeIs()
1180 GURL url = request.url();
1181 std::string request_url = url.possibly_invalid_spec();
1183 GURL main_document_url = request.firstPartyForCookies();
1185 if (redirect_response.isNull() &&
1186 (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks() ||
1187 test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities())) {
1188 DCHECK(resource_identifier_map_.find(identifier) ==
1189 resource_identifier_map_.end());
1190 resource_identifier_map_[identifier] =
1191 DescriptionSuitableForTestResult(request_url);
1194 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1195 if (resource_identifier_map_.find(identifier) ==
1196 resource_identifier_map_.end())
1197 delegate_->PrintMessage("<unknown>");
1198 else
1199 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1200 delegate_->PrintMessage(" - willSendRequest <NSURLRequest URL ");
1201 delegate_->PrintMessage(
1202 DescriptionSuitableForTestResult(request_url).c_str());
1203 delegate_->PrintMessage(", main document URL ");
1204 delegate_->PrintMessage(URLDescription(main_document_url).c_str());
1205 delegate_->PrintMessage(", http method ");
1206 delegate_->PrintMessage(request.httpMethod().utf8().data());
1207 delegate_->PrintMessage("> redirectResponse ");
1208 PrintResponseDescription(delegate_, redirect_response);
1209 delegate_->PrintMessage("\n");
1212 if (test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities()) {
1213 delegate_->PrintMessage(
1214 DescriptionSuitableForTestResult(request_url).c_str());
1215 delegate_->PrintMessage(" has priority ");
1216 delegate_->PrintMessage(PriorityDescription(request.priority()));
1217 delegate_->PrintMessage("\n");
1220 if (test_interfaces_->GetTestRunner()->httpHeadersToClear()) {
1221 const std::set<std::string>* clearHeaders =
1222 test_interfaces_->GetTestRunner()->httpHeadersToClear();
1223 for (std::set<std::string>::const_iterator header = clearHeaders->begin();
1224 header != clearHeaders->end();
1225 ++header)
1226 request.clearHTTPHeaderField(blink::WebString::fromUTF8(*header));
1229 std::string host = url.host();
1230 if (!host.empty() &&
1231 (url.SchemeIs(url::kHttpScheme) || url.SchemeIs(url::kHttpsScheme))) {
1232 if (!IsLocalHost(host) && !IsTestHost(host) &&
1233 !HostIsUsedBySomeTestsToGenerateError(host) &&
1234 ((!main_document_url.SchemeIs(url::kHttpScheme) &&
1235 !main_document_url.SchemeIs(url::kHttpsScheme)) ||
1236 IsLocalHost(main_document_url.host())) &&
1237 !delegate_->AllowExternalPages()) {
1238 delegate_->PrintMessage(std::string("Blocked access to external URL ") +
1239 request_url + "\n");
1240 BlockRequest(request);
1241 return;
1245 // Set the new substituted URL.
1246 request.setURL(delegate_->RewriteLayoutTestsURL(request.url().spec()));
1249 void WebTestProxyBase::DidReceiveResponse(
1250 blink::WebLocalFrame* frame,
1251 unsigned identifier,
1252 const blink::WebURLResponse& response) {
1253 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1254 if (resource_identifier_map_.find(identifier) ==
1255 resource_identifier_map_.end())
1256 delegate_->PrintMessage("<unknown>");
1257 else
1258 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1259 delegate_->PrintMessage(" - didReceiveResponse ");
1260 PrintResponseDescription(delegate_, response);
1261 delegate_->PrintMessage("\n");
1263 if (test_interfaces_->GetTestRunner()
1264 ->shouldDumpResourceResponseMIMETypes()) {
1265 GURL url = response.url();
1266 blink::WebString mime_type = response.mimeType();
1267 delegate_->PrintMessage(url.ExtractFileName());
1268 delegate_->PrintMessage(" has MIME type ");
1269 // Simulate NSURLResponse's mapping of empty/unknown MIME types to
1270 // application/octet-stream
1271 delegate_->PrintMessage(mime_type.isEmpty() ? "application/octet-stream"
1272 : mime_type.utf8().data());
1273 delegate_->PrintMessage("\n");
1277 void WebTestProxyBase::DidChangeResourcePriority(
1278 blink::WebLocalFrame* frame,
1279 unsigned identifier,
1280 const blink::WebURLRequest::Priority& priority,
1281 int intra_priority_value) {
1282 if (test_interfaces_->GetTestRunner()->shouldDumpResourcePriorities()) {
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(
1289 base::StringPrintf(" changed priority to %s, intra_priority %d\n",
1290 PriorityDescription(priority).c_str(),
1291 intra_priority_value));
1295 void WebTestProxyBase::DidFinishResourceLoad(blink::WebLocalFrame* frame,
1296 unsigned identifier) {
1297 if (test_interfaces_->GetTestRunner()->shouldDumpResourceLoadCallbacks()) {
1298 if (resource_identifier_map_.find(identifier) ==
1299 resource_identifier_map_.end())
1300 delegate_->PrintMessage("<unknown>");
1301 else
1302 delegate_->PrintMessage(resource_identifier_map_[identifier]);
1303 delegate_->PrintMessage(" - didFinishLoading\n");
1305 resource_identifier_map_.erase(identifier);
1306 CheckDone(frame, ResourceLoadCompleted);
1309 void WebTestProxyBase::DidAddMessageToConsole(
1310 const blink::WebConsoleMessage& message,
1311 const blink::WebString& source_name,
1312 unsigned source_line) {
1313 // This matches win DumpRenderTree's UIDelegate.cpp.
1314 if (!log_console_output_)
1315 return;
1316 std::string level;
1317 switch (message.level) {
1318 case blink::WebConsoleMessage::LevelDebug:
1319 level = "DEBUG";
1320 break;
1321 case blink::WebConsoleMessage::LevelLog:
1322 level = "MESSAGE";
1323 break;
1324 case blink::WebConsoleMessage::LevelInfo:
1325 level = "INFO";
1326 break;
1327 case blink::WebConsoleMessage::LevelWarning:
1328 level = "WARNING";
1329 break;
1330 case blink::WebConsoleMessage::LevelError:
1331 level = "ERROR";
1332 break;
1333 default:
1334 level = "MESSAGE";
1336 delegate_->PrintMessage(std::string("CONSOLE ") + level + ": ");
1337 if (source_line) {
1338 delegate_->PrintMessage(base::StringPrintf("line %d: ", source_line));
1340 if (!message.text.isEmpty()) {
1341 std::string new_message;
1342 new_message = message.text.utf8();
1343 size_t file_protocol = new_message.find("file://");
1344 if (file_protocol != std::string::npos) {
1345 new_message = new_message.substr(0, file_protocol) +
1346 URLSuitableForTestResult(new_message.substr(file_protocol));
1348 delegate_->PrintMessage(new_message);
1350 delegate_->PrintMessage(std::string("\n"));
1353 void WebTestProxyBase::CheckDone(blink::WebLocalFrame* frame,
1354 CheckDoneReason reason) {
1355 if (frame != test_interfaces_->GetTestRunner()->topLoadingFrame())
1356 return;
1357 if (reason != MainResourceLoadFailed &&
1358 (frame->isResourceLoadInProgress() || frame->isLoading()))
1359 return;
1360 test_interfaces_->GetTestRunner()->setTopLoadingFrame(frame, true);
1363 blink::WebNavigationPolicy WebTestProxyBase::DecidePolicyForNavigation(
1364 const blink::WebFrameClient::NavigationPolicyInfo& info) {
1365 if (test_interfaces_->GetTestRunner()->shouldDumpNavigationPolicy()) {
1366 delegate_->PrintMessage("Default policy for navigation to '" +
1367 URLDescription(info.urlRequest.url()) + "' is '" +
1368 WebNavigationPolicyToString(info.defaultPolicy) +
1369 "'\n");
1372 blink::WebNavigationPolicy result;
1373 if (!test_interfaces_->GetTestRunner()->policyDelegateEnabled())
1374 return info.defaultPolicy;
1376 delegate_->PrintMessage(
1377 std::string("Policy delegate: attempt to load ") +
1378 URLDescription(info.urlRequest.url()) + " with navigation type '" +
1379 WebNavigationTypeToString(info.navigationType) + "'\n");
1380 if (test_interfaces_->GetTestRunner()->policyDelegateIsPermissive())
1381 result = blink::WebNavigationPolicyCurrentTab;
1382 else
1383 result = blink::WebNavigationPolicyIgnore;
1385 if (test_interfaces_->GetTestRunner()->policyDelegateShouldNotifyDone()) {
1386 test_interfaces_->GetTestRunner()->policyDelegateDone();
1387 result = blink::WebNavigationPolicyIgnore;
1390 return result;
1393 bool WebTestProxyBase::WillCheckAndDispatchMessageEvent(
1394 blink::WebLocalFrame* source_frame,
1395 blink::WebFrame* target_frame,
1396 blink::WebSecurityOrigin target,
1397 blink::WebDOMMessageEvent event) {
1398 if (test_interfaces_->GetTestRunner()->shouldInterceptPostMessage()) {
1399 delegate_->PrintMessage("intercepted postMessage\n");
1400 return true;
1403 return false;
1406 void WebTestProxyBase::PostSpellCheckEvent(const blink::WebString& event_name) {
1407 if (test_interfaces_->GetTestRunner()->shouldDumpSpellCheckCallbacks()) {
1408 delegate_->PrintMessage(std::string("SpellCheckEvent: ") +
1409 event_name.utf8().data() + "\n");
1413 void WebTestProxyBase::ResetInputMethod() {
1414 // If a composition text exists, then we need to let the browser process
1415 // to cancel the input method's ongoing composition session.
1416 if (web_widget_)
1417 web_widget_->confirmComposition();
1420 blink::WebString WebTestProxyBase::acceptLanguages() {
1421 return blink::WebString::fromUTF8(accept_languages_);
1424 } // namespace test_runner