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