[Chromium] Layout test does not return correct misspelling positions if there are...
[WebKit-https.git] / Tools / DumpRenderTree / chromium / WebViewHost.cpp
1 /*
2  * Copyright (C) 2010, 2011 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "WebViewHost.h"
33
34 #include "LayoutTestController.h"
35 #include "TestNavigationController.h"
36 #include "TestShell.h"
37 #include "TestWebPlugin.h"
38 #include "TestWebWorker.h"
39 #include "WebCString.h"
40 #include "WebCompositor.h"
41 #include "WebConsoleMessage.h"
42 #include "WebContextMenuData.h"
43 #include "WebDataSource.h"
44 #include "WebDeviceOrientationClientMock.h"
45 #include "WebDragData.h"
46 #include "WebElement.h"
47 #include "WebFrame.h"
48 #include "WebGeolocationClientMock.h"
49 #include "WebHistoryItem.h"
50 #include "WebKit.h"
51 #include "WebKitPlatformSupport.h"
52 #include "WebNode.h"
53 #include "WebPluginParams.h"
54 #include "WebPopupMenu.h"
55 #include "WebPopupType.h"
56 #include "WebRange.h"
57 #include "WebRect.h"
58 #include "WebScreenInfo.h"
59 #include "WebSize.h"
60 #include "WebSpeechInputControllerMock.h"
61 #include "WebStorageNamespace.h"
62 #include "WebTextCheckingCompletion.h"
63 #include "WebTextCheckingResult.h"
64 #include "WebThread.h"
65 #include "WebURLRequest.h"
66 #include "WebURLResponse.h"
67 #include "WebView.h"
68 #include "WebWindowFeatures.h"
69 #include "skia/ext/platform_canvas.h"
70 #include "webkit/support/webkit_support.h"
71
72 #include <wtf/Assertions.h>
73 #include <wtf/PassOwnPtr.h>
74 #include <wtf/Threading.h>
75 #include <wtf/Vector.h>
76
77 using namespace WebCore;
78 using namespace WebKit;
79 using namespace std;
80
81 static const int screenWidth = 1920;
82 static const int screenHeight = 1080;
83 static const int screenUnavailableBorder = 8;
84
85 // WebNavigationType debugging strings taken from PolicyDelegate.mm.
86 static const char* linkClickedString = "link clicked";
87 static const char* formSubmittedString = "form submitted";
88 static const char* backForwardString = "back/forward";
89 static const char* reloadString = "reload";
90 static const char* formResubmittedString = "form resubmitted";
91 static const char* otherString = "other";
92 static const char* illegalString = "illegal value";
93
94 static int nextPageID = 1;
95
96 // Used to write a platform neutral file:/// URL by only taking the filename
97 // (e.g., converts "file:///tmp/foo.txt" to just "foo.txt").
98 static string urlSuitableForTestResult(const string& url)
99 {
100     if (url.empty() || string::npos == url.find("file://"))
101         return url;
102
103     size_t pos = url.rfind('/');
104     if (pos == string::npos) {
105 #if OS(WINDOWS)
106         pos = url.rfind('\\');
107         if (pos == string::npos)
108             pos = 0;
109 #else
110         pos = 0;
111 #endif
112     }
113     string filename = url.substr(pos + 1);
114     if (filename.empty())
115         return "file:"; // A WebKit test has this in its expected output.
116     return filename;
117 }
118
119 // Used to write a platform neutral file:/// URL by taking the
120 // filename and its directory. (e.g., converts
121 // "file:///tmp/foo/bar.txt" to just "bar.txt").
122 static string descriptionSuitableForTestResult(const string& url)
123 {
124     if (url.empty() || string::npos == url.find("file://"))
125         return url;
126
127     size_t pos = url.rfind('/');
128     if (pos == string::npos || !pos)
129         return "ERROR:" + url;
130     pos = url.rfind('/', pos - 1);
131     if (pos == string::npos)
132         return "ERROR:" + url;
133
134     return url.substr(pos + 1);
135 }
136
137 // Adds a file called "DRTFakeFile" to dragData (CF_HDROP). Use to fake
138 // dragging a file.
139 static void addDRTFakeFileToDataObject(WebDragData* dragData)
140 {
141     dragData->appendToFilenames(WebString::fromUTF8("DRTFakeFile"));
142 }
143
144 // Get a debugging string from a WebNavigationType.
145 static const char* webNavigationTypeToString(WebNavigationType type)
146 {
147     switch (type) {
148     case WebKit::WebNavigationTypeLinkClicked:
149         return linkClickedString;
150     case WebKit::WebNavigationTypeFormSubmitted:
151         return formSubmittedString;
152     case WebKit::WebNavigationTypeBackForward:
153         return backForwardString;
154     case WebKit::WebNavigationTypeReload:
155         return reloadString;
156     case WebKit::WebNavigationTypeFormResubmitted:
157         return formResubmittedString;
158     case WebKit::WebNavigationTypeOther:
159         return otherString;
160     }
161     return illegalString;
162 }
163
164 static string URLDescription(const GURL& url)
165 {
166     if (url.SchemeIs("file"))
167         return url.ExtractFileName();
168     return url.possibly_invalid_spec();
169 }
170
171 static void printResponseDescription(const WebURLResponse& response)
172 {
173     if (response.isNull()) {
174         fputs("(null)", stdout);
175         return;
176     }
177     string url = response.url().spec();
178     printf("<NSURLResponse %s, http status code %d>",
179            descriptionSuitableForTestResult(url).c_str(),
180            response.httpStatusCode());
181 }
182
183 static void printNodeDescription(const WebNode& node, int exception)
184 {
185     if (exception) {
186         fputs("ERROR", stdout);
187         return;
188     }
189     if (node.isNull()) {
190         fputs("(null)", stdout);
191         return;
192     }
193     fputs(node.nodeName().utf8().data(), stdout);
194     const WebNode& parent = node.parentNode();
195     if (!parent.isNull()) {
196         fputs(" > ", stdout);
197         printNodeDescription(parent, 0);
198     }
199 }
200
201 static void printRangeDescription(const WebRange& range)
202 {
203     if (range.isNull()) {
204         fputs("(null)", stdout);
205         return;
206     }
207     printf("range from %d of ", range.startOffset());
208     int exception = 0;
209     WebNode startNode = range.startContainer(exception);
210     printNodeDescription(startNode, exception);
211     printf(" to %d of ", range.endOffset());
212     WebNode endNode = range.endContainer(exception);
213     printNodeDescription(endNode, exception);
214 }
215
216 static string editingActionDescription(WebEditingAction action)
217 {
218     switch (action) {
219     case WebKit::WebEditingActionTyped:
220         return "WebViewInsertActionTyped";
221     case WebKit::WebEditingActionPasted:
222         return "WebViewInsertActionPasted";
223     case WebKit::WebEditingActionDropped:
224         return "WebViewInsertActionDropped";
225     }
226     return "(UNKNOWN ACTION)";
227 }
228
229 static string textAffinityDescription(WebTextAffinity affinity)
230 {
231     switch (affinity) {
232     case WebKit::WebTextAffinityUpstream:
233         return "NSSelectionAffinityUpstream";
234     case WebKit::WebTextAffinityDownstream:
235         return "NSSelectionAffinityDownstream";
236     }
237     return "(UNKNOWN AFFINITY)";
238 }
239
240 // WebViewClient -------------------------------------------------------------
241
242 WebView* WebViewHost::createView(WebFrame*, const WebURLRequest& request, const WebWindowFeatures&, const WebString&)
243 {
244     if (!layoutTestController()->canOpenWindows())
245         return 0;
246     if (layoutTestController()->shouldDumpCreateView())
247         fprintf(stdout, "createView(%s)\n", URLDescription(request.url()).c_str());
248     return m_shell->createNewWindow(WebURL())->webView();
249 }
250
251 WebWidget* WebViewHost::createPopupMenu(WebPopupType type)
252 {
253     switch (type) {
254     case WebKit::WebPopupTypeNone:
255         break;
256     case WebKit::WebPopupTypeSelect:
257     case WebKit::WebPopupTypeSuggestion:
258         m_popupmenus.append(WebPopupMenu::create(0));
259         return m_popupmenus.last();
260     }
261     return 0;
262 }
263
264 WebWidget* WebViewHost::createPopupMenu(const WebPopupMenuInfo&)
265 {
266     // Do not use this method. It's been replaced by createExternalPopupMenu.
267     ASSERT_NOT_REACHED();
268     return 0;
269 }
270
271 WebStorageNamespace* WebViewHost::createSessionStorageNamespace(unsigned quota)
272 {
273     return WebKit::WebStorageNamespace::createSessionStorageNamespace(quota);
274 }
275
276 void WebViewHost::didAddMessageToConsole(const WebConsoleMessage& message, const WebString& sourceName, unsigned sourceLine)
277 {
278     // This matches win DumpRenderTree's UIDelegate.cpp.
279     if (!m_logConsoleOutput)
280         return;
281     string newMessage;
282     if (!message.text.isEmpty()) {
283         newMessage = message.text.utf8();
284         size_t fileProtocol = newMessage.find("file://");
285         if (fileProtocol != string::npos) {
286             newMessage = newMessage.substr(0, fileProtocol)
287                 + urlSuitableForTestResult(newMessage.substr(fileProtocol));
288         }
289     }
290     printf("CONSOLE MESSAGE: line %d: %s\n", sourceLine, newMessage.data());
291 }
292
293 void WebViewHost::didStartLoading()
294 {
295     m_shell->setIsLoading(true);
296 }
297
298 void WebViewHost::didStopLoading()
299 {
300     if (layoutTestController()->shouldDumpProgressFinishedCallback())
301         fputs("postProgressFinishedNotification\n", stdout);
302     m_shell->setIsLoading(false);
303 }
304
305 // The output from these methods in layout test mode should match that
306 // expected by the layout tests. See EditingDelegate.m in DumpRenderTree.
307
308 bool WebViewHost::shouldBeginEditing(const WebRange& range)
309 {
310     if (layoutTestController()->shouldDumpEditingCallbacks()) {
311         fputs("EDITING DELEGATE: shouldBeginEditingInDOMRange:", stdout);
312         printRangeDescription(range);
313         fputs("\n", stdout);
314     }
315     return layoutTestController()->acceptsEditing();
316 }
317
318 bool WebViewHost::shouldEndEditing(const WebRange& range)
319 {
320     if (layoutTestController()->shouldDumpEditingCallbacks()) {
321         fputs("EDITING DELEGATE: shouldEndEditingInDOMRange:", stdout);
322         printRangeDescription(range);
323         fputs("\n", stdout);
324     }
325     return layoutTestController()->acceptsEditing();
326 }
327
328 bool WebViewHost::shouldInsertNode(const WebNode& node, const WebRange& range, WebEditingAction action)
329 {
330     if (layoutTestController()->shouldDumpEditingCallbacks()) {
331         fputs("EDITING DELEGATE: shouldInsertNode:", stdout);
332         printNodeDescription(node, 0);
333         fputs(" replacingDOMRange:", stdout);
334         printRangeDescription(range);
335         printf(" givenAction:%s\n", editingActionDescription(action).c_str());
336     }
337     return layoutTestController()->acceptsEditing();
338 }
339
340 bool WebViewHost::shouldInsertText(const WebString& text, const WebRange& range, WebEditingAction action)
341 {
342     if (layoutTestController()->shouldDumpEditingCallbacks()) {
343         printf("EDITING DELEGATE: shouldInsertText:%s replacingDOMRange:", text.utf8().data());
344         printRangeDescription(range);
345         printf(" givenAction:%s\n", editingActionDescription(action).c_str());
346     }
347     return layoutTestController()->acceptsEditing();
348 }
349
350 bool WebViewHost::shouldChangeSelectedRange(
351     const WebRange& fromRange, const WebRange& toRange, WebTextAffinity affinity, bool stillSelecting)
352 {
353     if (layoutTestController()->shouldDumpEditingCallbacks()) {
354         fputs("EDITING DELEGATE: shouldChangeSelectedDOMRange:", stdout);
355         printRangeDescription(fromRange);
356         fputs(" toDOMRange:", stdout);
357         printRangeDescription(toRange);
358         printf(" affinity:%s stillSelecting:%s\n",
359                textAffinityDescription(affinity).c_str(),
360                (stillSelecting ? "TRUE" : "FALSE"));
361     }
362     return layoutTestController()->acceptsEditing();
363 }
364
365 bool WebViewHost::shouldDeleteRange(const WebRange& range)
366 {
367     if (layoutTestController()->shouldDumpEditingCallbacks()) {
368         fputs("EDITING DELEGATE: shouldDeleteDOMRange:", stdout);
369         printRangeDescription(range);
370         fputs("\n", stdout);
371     }
372     return layoutTestController()->acceptsEditing();
373 }
374
375 bool WebViewHost::shouldApplyStyle(const WebString& style, const WebRange& range)
376 {
377     if (layoutTestController()->shouldDumpEditingCallbacks()) {
378         printf("EDITING DELEGATE: shouldApplyStyle:%s toElementsInDOMRange:", style.utf8().data());
379         printRangeDescription(range);
380         fputs("\n", stdout);
381     }
382     return layoutTestController()->acceptsEditing();
383 }
384
385 bool WebViewHost::isSmartInsertDeleteEnabled()
386 {
387     return m_smartInsertDeleteEnabled;
388 }
389
390 bool WebViewHost::isSelectTrailingWhitespaceEnabled()
391 {
392     return m_selectTrailingWhitespaceEnabled;
393 }
394
395 void WebViewHost::didBeginEditing()
396 {
397     if (!layoutTestController()->shouldDumpEditingCallbacks())
398         return;
399     fputs("EDITING DELEGATE: webViewDidBeginEditing:WebViewDidBeginEditingNotification\n", stdout);
400 }
401
402 void WebViewHost::didChangeSelection(bool isEmptySelection)
403 {
404     if (layoutTestController()->shouldDumpEditingCallbacks())
405         fputs("EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification\n", stdout);
406     // No need to update clipboard with the selected text in DRT.
407 }
408
409 void WebViewHost::didChangeContents()
410 {
411     if (!layoutTestController()->shouldDumpEditingCallbacks())
412         return;
413     fputs("EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification\n", stdout);
414 }
415
416 void WebViewHost::didEndEditing()
417 {
418     if (!layoutTestController()->shouldDumpEditingCallbacks())
419         return;
420     fputs("EDITING DELEGATE: webViewDidEndEditing:WebViewDidEndEditingNotification\n", stdout);
421 }
422
423 bool WebViewHost::handleCurrentKeyboardEvent()
424 {
425     if (m_editCommandName.empty())
426         return false;
427     WebFrame* frame = webView()->focusedFrame();
428     if (!frame)
429         return false;
430
431     return frame->executeCommand(WebString::fromUTF8(m_editCommandName), WebString::fromUTF8(m_editCommandValue));
432 }
433
434 void WebViewHost::spellCheck(const WebString& text, int& misspelledOffset, int& misspelledLength, WebVector<WebString>* optionalSuggestions)
435 {
436     // Check the spelling of the given text.
437     m_spellcheck.spellCheckWord(text, &misspelledOffset, &misspelledLength);
438 }
439
440 void WebViewHost::requestCheckingOfText(const WebString& text, WebTextCheckingCompletion* completion)
441 {
442     m_lastRequestedTextCheckingCompletion = completion;
443     m_lastRequestedTextCheckString = text;
444     postDelayedTask(new HostMethodTask(this, &WebViewHost::finishLastTextCheck), 0);
445 }
446
447 void WebViewHost::finishLastTextCheck()
448 {
449     Vector<WebTextCheckingResult> results;
450     // FIXME: Do the grammar check.
451     int offset = 0;
452     String text(m_lastRequestedTextCheckString.data(), m_lastRequestedTextCheckString.length());
453     while (text.length()) {
454         int misspelledPosition = 0;
455         int misspelledLength = 0;
456         m_spellcheck.spellCheckWord(WebString(text.characters(), text.length()), &misspelledPosition, &misspelledLength);
457         if (!misspelledLength)
458             break;
459         results.append(WebTextCheckingResult(WebTextCheckingResult::ErrorSpelling, offset + misspelledPosition, misspelledLength));
460         text = text.substring(misspelledPosition + misspelledLength);
461         offset += misspelledPosition + misspelledLength;
462     }
463
464     m_lastRequestedTextCheckingCompletion->didFinishCheckingText(results);
465     m_lastRequestedTextCheckingCompletion = 0;
466 }
467
468
469 WebString WebViewHost::autoCorrectWord(const WebString&)
470 {
471     // Returns an empty string as Mac WebKit ('WebKitSupport/WebEditorClient.mm')
472     // does. (If this function returns a non-empty string, WebKit replaces the
473     // given misspelled string with the result one. This process executes some
474     // editor commands and causes layout-test failures.)
475     return WebString();
476 }
477
478 void WebViewHost::runModalAlertDialog(WebFrame*, const WebString& message)
479 {
480     printf("ALERT: %s\n", message.utf8().data());
481 }
482
483 bool WebViewHost::runModalConfirmDialog(WebFrame*, const WebString& message)
484 {
485     printf("CONFIRM: %s\n", message.utf8().data());
486     return true;
487 }
488
489 bool WebViewHost::runModalPromptDialog(WebFrame* frame, const WebString& message,
490                                        const WebString& defaultValue, WebString*)
491 {
492     printf("PROMPT: %s, default text: %s\n", message.utf8().data(), defaultValue.utf8().data());
493     return true;
494 }
495
496 bool WebViewHost::runModalBeforeUnloadDialog(WebFrame*, const WebString& message)
497 {
498     printf("CONFIRM NAVIGATION: %s\n", message.utf8().data());
499     return !layoutTestController()->shouldStayOnPageAfterHandlingBeforeUnload();
500 }
501
502 void WebViewHost::showContextMenu(WebFrame*, const WebContextMenuData& contextMenuData)
503 {
504     m_lastContextMenuData = adoptPtr(new WebContextMenuData(contextMenuData));
505 }
506
507 void WebViewHost::clearContextMenuData()
508 {
509     m_lastContextMenuData.clear();
510 }
511
512 WebContextMenuData* WebViewHost::lastContextMenuData() const
513 {
514     return m_lastContextMenuData.get();
515 }
516
517 void WebViewHost::setStatusText(const WebString& text)
518 {
519     if (!layoutTestController()->shouldDumpStatusCallbacks())
520         return;
521     // When running tests, write to stdout.
522     printf("UI DELEGATE STATUS CALLBACK: setStatusText:%s\n", text.utf8().data());
523 }
524
525 void WebViewHost::startDragging(const WebDragData& data, WebDragOperationsMask mask, const WebImage&, const WebPoint&)
526 {
527     WebDragData mutableDragData = data;
528     if (layoutTestController()->shouldAddFileToPasteboard()) {
529         // Add a file called DRTFakeFile to the drag&drop clipboard.
530         addDRTFakeFileToDataObject(&mutableDragData);
531     }
532
533     // When running a test, we need to fake a drag drop operation otherwise
534     // Windows waits for real mouse events to know when the drag is over.
535     m_shell->eventSender()->doDragDrop(mutableDragData, mask);
536 }
537
538 void WebViewHost::navigateBackForwardSoon(int offset)
539 {
540     navigationController()->goToOffset(offset);
541 }
542
543 int WebViewHost::historyBackListCount()
544 {
545     return navigationController()->lastCommittedEntryIndex();
546 }
547
548 int WebViewHost::historyForwardListCount()
549 {
550     int currentIndex =navigationController()->lastCommittedEntryIndex();
551     return navigationController()->entryCount() - currentIndex - 1;
552 }
553
554 void WebViewHost::postAccessibilityNotification(const WebAccessibilityObject& obj, WebAccessibilityNotification notification)
555 {
556     if (notification == WebAccessibilityNotificationFocusedUIElementChanged)
557         m_shell->accessibilityController()->setFocusedElement(obj);
558
559     const char* notificationName;
560     switch (notification) {
561     case WebAccessibilityNotificationActiveDescendantChanged:
562         notificationName = "ActiveDescendantChanged";
563         break;
564     case WebAccessibilityNotificationCheckedStateChanged:
565         notificationName = "CheckedStateChanged";
566         break;
567     case WebAccessibilityNotificationChildrenChanged:
568         notificationName = "ChildrenChanged";
569         break;
570     case WebAccessibilityNotificationFocusedUIElementChanged:
571         notificationName = "FocusedUIElementChanged";
572         break;
573     case WebAccessibilityNotificationLayoutComplete:
574         notificationName = "LayoutComplete";
575         break;
576     case WebAccessibilityNotificationLoadComplete:
577         notificationName = "LoadComplete";
578         break;
579     case WebAccessibilityNotificationSelectedChildrenChanged:
580         notificationName = "SelectedChildrenChanged";
581         break;
582     case WebAccessibilityNotificationSelectedTextChanged:
583         notificationName = "SelectedTextChanged";
584         break;
585     case WebAccessibilityNotificationValueChanged:
586         notificationName = "ValueChanged";
587         break;
588     case WebAccessibilityNotificationScrolledToAnchor:
589         notificationName = "ScrolledToAnchor";
590         break;
591     case WebAccessibilityNotificationLiveRegionChanged:
592         notificationName = "LiveRegionChanged";
593         break;
594     case WebAccessibilityNotificationMenuListValueChanged:
595         notificationName = "MenuListValueChanged";
596         break;
597     case WebAccessibilityNotificationRowCountChanged:
598         notificationName = "RowCountChanged";
599         break;
600     case WebAccessibilityNotificationRowCollapsed:
601         notificationName = "RowCollapsed";
602         break;
603     case WebAccessibilityNotificationRowExpanded:
604         notificationName = "RowExpanded";
605         break;
606     default:
607         notificationName = "UnknownNotification";
608         break;
609     }
610
611     m_shell->accessibilityController()->notificationReceived(obj, notificationName);
612
613     if (m_shell->accessibilityController()->shouldLogAccessibilityEvents()) {
614         printf("AccessibilityNotification - %s", notificationName);
615
616         WebKit::WebNode node = obj.node();
617         if (!node.isNull() && node.isElementNode()) {
618             WebKit::WebElement element = node.to<WebKit::WebElement>();
619             if (element.hasAttribute("id"))
620                 printf(" - id:%s", element.getAttribute("id").utf8().data());
621         }
622
623         printf("\n");
624     }
625 }
626
627 WebNotificationPresenter* WebViewHost::notificationPresenter()
628 {
629     return m_shell->notificationPresenter();
630 }
631
632 WebKit::WebGeolocationClient* WebViewHost::geolocationClient()
633 {
634     return geolocationClientMock();
635 }
636
637 WebKit::WebGeolocationClientMock* WebViewHost::geolocationClientMock()
638 {
639     if (!m_geolocationClientMock)
640         m_geolocationClientMock = adoptPtr(WebGeolocationClientMock::create());
641     return m_geolocationClientMock.get();
642 }
643
644 WebSpeechInputController* WebViewHost::speechInputController(WebKit::WebSpeechInputListener* listener)
645 {
646     if (!m_speechInputControllerMock)
647         m_speechInputControllerMock = adoptPtr(WebSpeechInputControllerMock::create(listener));
648     return m_speechInputControllerMock.get();
649 }
650
651 WebDeviceOrientationClientMock* WebViewHost::deviceOrientationClientMock()
652 {
653     if (!m_deviceOrientationClientMock.get())
654         m_deviceOrientationClientMock = adoptPtr(WebDeviceOrientationClientMock::create());
655     return m_deviceOrientationClientMock.get();
656 }
657
658 MockSpellCheck* WebViewHost::mockSpellCheck()
659 {
660     return &m_spellcheck;
661 }
662
663 WebDeviceOrientationClient* WebViewHost::deviceOrientationClient()
664 {
665     return deviceOrientationClientMock();
666 }
667
668 // WebWidgetClient -----------------------------------------------------------
669
670 void WebViewHost::didInvalidateRect(const WebRect& rect)
671 {
672     updatePaintRect(rect);
673 }
674
675 void WebViewHost::didScrollRect(int, int, const WebRect& clipRect)
676 {
677     // This is used for optimizing painting when the renderer is scrolled. We're
678     // currently not doing any optimizations so just invalidate the region.
679     didInvalidateRect(clipRect);
680 }
681
682 void WebViewHost::scheduleComposite()
683 {
684     WebSize widgetSize = webWidget()->size();
685     WebRect clientRect(0, 0, widgetSize.width, widgetSize.height);
686     didInvalidateRect(clientRect);
687 }
688
689 #if ENABLE(REQUEST_ANIMATION_FRAME)
690 void WebViewHost::scheduleAnimation()
691 {
692     postDelayedTask(new HostMethodTask(this, &WebViewHost::scheduleComposite), 0);
693 }
694 #endif
695
696 void WebViewHost::didFocus()
697 {
698     m_shell->setFocus(webWidget(), true);
699 }
700
701 void WebViewHost::didBlur()
702 {
703     m_shell->setFocus(webWidget(), false);
704 }
705
706 WebScreenInfo WebViewHost::screenInfo()
707 {
708     // We don't need to set actual values.
709     WebScreenInfo info;
710     info.depth = 24;
711     info.depthPerComponent = 8;
712     info.isMonochrome = false;
713     info.rect = WebRect(0, 0, screenWidth, screenHeight);
714     // Use values different from info.rect for testing.
715     info.availableRect = WebRect(screenUnavailableBorder, screenUnavailableBorder,
716                                  screenWidth - screenUnavailableBorder * 2,
717                                  screenHeight - screenUnavailableBorder * 2);
718     return info;
719 }
720
721 void WebViewHost::show(WebNavigationPolicy)
722 {
723     m_hasWindow = true;
724     WebSize size = webWidget()->size();
725     updatePaintRect(WebRect(0, 0, size.width, size.height));
726 }
727
728
729
730 void WebViewHost::closeWidget()
731 {
732     m_hasWindow = false;
733     m_shell->closeWindow(this);
734     // No more code here, we should be deleted at this point.
735 }
736
737 void WebViewHost::closeWidgetSoon()
738 {
739     postDelayedTask(new HostMethodTask(this, &WebViewHost::closeWidget), 0);
740 }
741
742 void WebViewHost::didChangeCursor(const WebCursorInfo& cursorInfo)
743 {
744     if (!hasWindow())
745         return;
746     m_currentCursor = cursorInfo;
747 }
748
749 WebRect WebViewHost::windowRect()
750 {
751     return m_windowRect;
752 }
753
754 void WebViewHost::setWindowRect(const WebRect& rect)
755 {
756     m_windowRect = rect;
757     const int border2 = TestShell::virtualWindowBorder * 2;
758     if (m_windowRect.width <= border2)
759         m_windowRect.width = 1 + border2;
760     if (m_windowRect.height <= border2)
761         m_windowRect.height = 1 + border2;
762     int width = m_windowRect.width - border2;
763     int height = m_windowRect.height - border2;
764     discardBackingStore();
765     webWidget()->resize(WebSize(width, height));
766     updatePaintRect(WebRect(0, 0, width, height));
767 }
768
769 WebRect WebViewHost::rootWindowRect()
770 {
771     return windowRect();
772 }
773
774 WebRect WebViewHost::windowResizerRect()
775 {
776     // Not necessary.
777     return WebRect();
778 }
779
780 void WebViewHost::runModal()
781 {
782     bool oldState = webkit_support::MessageLoopNestableTasksAllowed();
783     webkit_support::MessageLoopSetNestableTasksAllowed(true);
784     m_inModalLoop = true;
785     webkit_support::RunMessageLoop();
786     webkit_support::MessageLoopSetNestableTasksAllowed(oldState);
787 }
788
789 bool WebViewHost::enterFullScreen()
790 {
791     postDelayedTask(new HostMethodTask(this, &WebViewHost::enterFullScreenNow), 0);
792     return true;
793 }
794
795 void WebViewHost::exitFullScreen()
796 {
797     postDelayedTask(new HostMethodTask(this, &WebViewHost::exitFullScreenNow), 0);
798 }
799
800 // WebFrameClient ------------------------------------------------------------
801
802 WebPlugin* WebViewHost::createPlugin(WebFrame* frame, const WebPluginParams& params)
803 {
804     if (params.mimeType == TestWebPlugin::mimeType())
805         return new TestWebPlugin(frame, params);
806
807     return webkit_support::CreateWebPlugin(frame, params);
808 }
809
810 WebWorker* WebViewHost::createWorker(WebFrame*, WebWorkerClient*)
811 {
812     return new TestWebWorker();
813 }
814
815 WebMediaPlayer* WebViewHost::createMediaPlayer(WebFrame* frame, WebMediaPlayerClient* client)
816 {
817     return webkit_support::CreateMediaPlayer(frame, client);
818 }
819
820 WebApplicationCacheHost* WebViewHost::createApplicationCacheHost(WebFrame* frame, WebApplicationCacheHostClient* client)
821 {
822     return webkit_support::CreateApplicationCacheHost(frame, client);
823 }
824
825 void WebViewHost::didUpdateLayout(WebFrame*)
826 {
827 #if OS(MAC_OS_X)
828     static bool queryingPreferredSize = false;
829     if (queryingPreferredSize)
830         return;
831
832     queryingPreferredSize = true;
833     // Query preferred width to emulate the same functionality in Chromium:
834     // see RenderView::CheckPreferredSize (src/content/renderer/render_view.cc)
835     // and TabContentsViewMac::RenderViewCreated (src/chrome/browser/tab_contents/tab_contents_view_mac.mm)
836     webView()->mainFrame()->contentsPreferredWidth();
837     webView()->mainFrame()->documentElementScrollHeight();
838     queryingPreferredSize = false;
839 #endif
840 }
841
842
843 void WebViewHost::loadURLExternally(WebFrame* frame, const WebURLRequest& request, WebNavigationPolicy policy)
844 {
845     loadURLExternally(frame, request, policy, WebString());
846 }
847
848 void WebViewHost::loadURLExternally(WebFrame*, const WebURLRequest& request, WebNavigationPolicy policy, const WebString& downloadName)
849 {
850     ASSERT(policy !=  WebKit::WebNavigationPolicyCurrentTab);
851     WebViewHost* another = m_shell->createNewWindow(request.url());
852     if (another)
853         another->show(policy);
854 }
855
856 WebNavigationPolicy WebViewHost::decidePolicyForNavigation(
857     WebFrame*, const WebURLRequest& request,
858     WebNavigationType type, const WebNode& originatingNode,
859     WebNavigationPolicy defaultPolicy, bool isRedirect)
860 {
861     WebNavigationPolicy result;
862     if (!m_policyDelegateEnabled)
863         return defaultPolicy;
864
865     printf("Policy delegate: attempt to load %s with navigation type '%s'",
866            URLDescription(request.url()).c_str(), webNavigationTypeToString(type));
867     if (!originatingNode.isNull()) {
868         fputs(" originating from ", stdout);
869         printNodeDescription(originatingNode, 0);
870     }
871     fputs("\n", stdout);
872     if (m_policyDelegateIsPermissive)
873         result = WebKit::WebNavigationPolicyCurrentTab;
874     else
875         result = WebKit::WebNavigationPolicyIgnore;
876
877     if (m_policyDelegateShouldNotifyDone)
878         layoutTestController()->policyDelegateDone();
879     return result;
880 }
881
882 bool WebViewHost::canHandleRequest(WebFrame*, const WebURLRequest& request)
883 {
884     GURL url = request.url();
885     // Just reject the scheme used in
886     // LayoutTests/http/tests/misc/redirect-to-external-url.html
887     return !url.SchemeIs("spaceballs");
888 }
889
890 WebURLError WebViewHost::cannotHandleRequestError(WebFrame*, const WebURLRequest& request)
891 {
892     WebURLError error;
893     // A WebKit layout test expects the following values.
894     // unableToImplementPolicyWithError() below prints them.
895     error.domain = WebString::fromUTF8("WebKitErrorDomain");
896     error.reason = 101;
897     error.unreachableURL = request.url();
898     return error;
899 }
900
901 WebURLError WebViewHost::cancelledError(WebFrame*, const WebURLRequest& request)
902 {
903     return webkit_support::CreateCancelledError(request);
904 }
905
906 void WebViewHost::unableToImplementPolicyWithError(WebFrame* frame, const WebURLError& error)
907 {
908     printf("Policy delegate: unable to implement policy with error domain '%s', "
909            "error code %d, in frame '%s'\n",
910            error.domain.utf8().data(), error.reason, frame->name().utf8().data());
911 }
912
913 void WebViewHost::willPerformClientRedirect(WebFrame* frame, const WebURL& from, const WebURL& to,
914                                             double interval, double fire_time)
915 {
916     if (m_shell->shouldDumpFrameLoadCallbacks()) {
917         printFrameDescription(frame);
918         printf(" - willPerformClientRedirectToURL: %s \n", to.spec().data());
919     }
920
921     if (m_shell->shouldDumpUserGestureInFrameLoadCallbacks())
922         printFrameUserGestureStatus(frame, " - in willPerformClientRedirect\n");
923 }
924
925 void WebViewHost::didCancelClientRedirect(WebFrame* frame)
926 {
927     if (!m_shell->shouldDumpFrameLoadCallbacks())
928         return;
929     printFrameDescription(frame);
930     fputs(" - didCancelClientRedirectForFrame\n", stdout);
931 }
932
933 void WebViewHost::didCreateDataSource(WebFrame*, WebDataSource* ds)
934 {
935     ds->setExtraData(m_pendingExtraData.leakPtr());
936     if (!layoutTestController()->deferMainResourceDataLoad())
937         ds->setDeferMainResourceDataLoad(false);
938 }
939
940 void WebViewHost::didStartProvisionalLoad(WebFrame* frame)
941 {
942     if (m_shell->shouldDumpFrameLoadCallbacks()) {
943         printFrameDescription(frame);
944         fputs(" - didStartProvisionalLoadForFrame\n", stdout);
945     }
946
947     if (m_shell->shouldDumpUserGestureInFrameLoadCallbacks())
948         printFrameUserGestureStatus(frame, " - in didStartProvisionalLoadForFrame\n");
949
950     if (!m_topLoadingFrame)
951         m_topLoadingFrame = frame;
952
953     if (layoutTestController()->stopProvisionalFrameLoads()) {
954         printFrameDescription(frame);
955         fputs(" - stopping load in didStartProvisionalLoadForFrame callback\n", stdout);
956         frame->stopLoading();
957     }
958     updateAddressBar(frame->view());
959 }
960
961 void WebViewHost::didReceiveServerRedirectForProvisionalLoad(WebFrame* frame)
962 {
963     if (m_shell->shouldDumpFrameLoadCallbacks()) {
964         printFrameDescription(frame);
965         fputs(" - didReceiveServerRedirectForProvisionalLoadForFrame\n", stdout);
966     }
967     updateAddressBar(frame->view());
968 }
969
970 void WebViewHost::didFailProvisionalLoad(WebFrame* frame, const WebURLError& error)
971 {
972     if (m_shell->shouldDumpFrameLoadCallbacks()) {
973         printFrameDescription(frame);
974         fputs(" - didFailProvisionalLoadWithError\n", stdout);
975     }
976
977     locationChangeDone(frame);
978
979     // Don't display an error page if we're running layout tests, because
980     // DumpRenderTree doesn't.
981 }
982
983 void WebViewHost::didCommitProvisionalLoad(WebFrame* frame, bool isNewNavigation)
984 {
985     if (m_shell->shouldDumpFrameLoadCallbacks()) {
986         printFrameDescription(frame);
987         fputs(" - didCommitLoadForFrame\n", stdout);
988     }
989     updateForCommittedLoad(frame, isNewNavigation);
990 }
991
992 void WebViewHost::didClearWindowObject(WebFrame* frame)
993 {
994     m_shell->bindJSObjectsToWindow(frame);
995 }
996
997 void WebViewHost::didReceiveTitle(WebFrame* frame, const WebString& title, WebTextDirection direction)
998 {
999     WebCString title8 = title.utf8();
1000
1001     if (m_shell->shouldDumpFrameLoadCallbacks()) {
1002         printFrameDescription(frame);
1003         printf(" - didReceiveTitle: %s\n", title8.data());
1004     }
1005
1006     if (layoutTestController()->shouldDumpTitleChanges())
1007         printf("TITLE CHANGED: %s\n", title8.data());
1008
1009     setPageTitle(title);
1010     layoutTestController()->setTitleTextDirection(direction);
1011 }
1012
1013 void WebViewHost::didFinishDocumentLoad(WebFrame* frame)
1014 {
1015     if (m_shell->shouldDumpFrameLoadCallbacks()) {
1016         printFrameDescription(frame);
1017         fputs(" - didFinishDocumentLoadForFrame\n", stdout);
1018     } else {
1019         unsigned pendingUnloadEvents = frame->unloadListenerCount();
1020         if (pendingUnloadEvents) {
1021             printFrameDescription(frame);
1022             printf(" - has %u onunload handler(s)\n", pendingUnloadEvents);
1023         }
1024     }
1025 }
1026
1027 void WebViewHost::didHandleOnloadEvents(WebFrame* frame)
1028 {
1029     if (m_shell->shouldDumpFrameLoadCallbacks()) {
1030         printFrameDescription(frame);
1031         fputs(" - didHandleOnloadEventsForFrame\n", stdout);
1032     }
1033 }
1034
1035 void WebViewHost::didFailLoad(WebFrame* frame, const WebURLError& error)
1036 {
1037     if (m_shell->shouldDumpFrameLoadCallbacks()) {
1038         printFrameDescription(frame);
1039         fputs(" - didFailLoadWithError\n", stdout);
1040     }
1041     locationChangeDone(frame);
1042 }
1043
1044 void WebViewHost::didFinishLoad(WebFrame* frame)
1045 {
1046     if (m_shell->shouldDumpFrameLoadCallbacks()) {
1047         printFrameDescription(frame);
1048         fputs(" - didFinishLoadForFrame\n", stdout);
1049     }
1050     updateAddressBar(frame->view());
1051     locationChangeDone(frame);
1052 }
1053
1054 void WebViewHost::didNavigateWithinPage(WebFrame* frame, bool isNewNavigation)
1055 {
1056     frame->dataSource()->setExtraData(m_pendingExtraData.leakPtr());
1057
1058     updateForCommittedLoad(frame, isNewNavigation);
1059 }
1060
1061 void WebViewHost::didChangeLocationWithinPage(WebFrame* frame)
1062 {
1063     if (m_shell->shouldDumpFrameLoadCallbacks()) {
1064         printFrameDescription(frame);
1065         fputs(" - didChangeLocationWithinPageForFrame\n", stdout);
1066     }
1067 }
1068
1069 void WebViewHost::assignIdentifierToRequest(WebFrame*, unsigned identifier, const WebURLRequest& request)
1070 {
1071      if (!m_shell->shouldDumpResourceLoadCallbacks())
1072         return;
1073     ASSERT(!m_resourceIdentifierMap.contains(identifier));
1074     m_resourceIdentifierMap.set(identifier, descriptionSuitableForTestResult(request.url().spec()));
1075 }
1076
1077 void WebViewHost::removeIdentifierForRequest(unsigned identifier)
1078 {
1079     m_resourceIdentifierMap.remove(identifier);
1080 }
1081
1082 void WebViewHost::willSendRequest(WebFrame*, unsigned identifier, WebURLRequest& request, const WebURLResponse& redirectResponse)
1083 {
1084     // Need to use GURL for host() and SchemeIs()
1085     GURL url = request.url();
1086     string requestURL = url.possibly_invalid_spec();
1087
1088     if (layoutTestController()->shouldDumpResourceLoadCallbacks()) {
1089         GURL mainDocumentURL = request.firstPartyForCookies();
1090         printResourceDescription(identifier);
1091         printf(" - willSendRequest <NSURLRequest URL %s, main document URL %s,"
1092                " http method %s> redirectResponse ",
1093                descriptionSuitableForTestResult(requestURL).c_str(),
1094                URLDescription(mainDocumentURL).c_str(),
1095                request.httpMethod().utf8().data());
1096         printResponseDescription(redirectResponse);
1097         fputs("\n", stdout);
1098     }
1099
1100     if (!redirectResponse.isNull() && m_blocksRedirects) {
1101         fputs("Returning null for this redirect\n", stdout);
1102         // To block the request, we set its URL to an empty one.
1103         request.setURL(WebURL());
1104         return;
1105     }
1106
1107     if (m_requestReturnNull) {
1108         // To block the request, we set its URL to an empty one.
1109         request.setURL(WebURL());
1110         return;
1111     }
1112
1113     string host = url.host();
1114     // 255.255.255.255 is used in some tests that expect to get back an error.
1115     if (!host.empty() && (url.SchemeIs("http") || url.SchemeIs("https"))
1116         && host != "127.0.0.1"
1117         && host != "255.255.255.255"
1118         && host != "localhost"
1119         && !m_shell->allowExternalPages()) {
1120         printf("Blocked access to external URL %s\n", requestURL.c_str());
1121
1122         // To block the request, we set its URL to an empty one.
1123         request.setURL(WebURL());
1124         return;
1125     }
1126
1127     HashSet<String>::const_iterator end = m_clearHeaders.end();
1128     for (HashSet<String>::const_iterator header = m_clearHeaders.begin(); header != end; ++header)
1129         request.clearHTTPHeaderField(WebString(header->characters(), header->length()));
1130
1131     // Set the new substituted URL.
1132     request.setURL(webkit_support::RewriteLayoutTestsURL(request.url().spec()));
1133 }
1134
1135 void WebViewHost::didReceiveResponse(WebFrame*, unsigned identifier, const WebURLResponse& response)
1136 {
1137     if (m_shell->shouldDumpResourceLoadCallbacks()) {
1138         printResourceDescription(identifier);
1139         fputs(" - didReceiveResponse ", stdout);
1140         printResponseDescription(response);
1141         fputs("\n", stdout);
1142     }
1143     if (m_shell->shouldDumpResourceResponseMIMETypes()) {
1144         GURL url = response.url();
1145         WebString mimeType = response.mimeType();
1146         printf("%s has MIME type %s\n",
1147             url.ExtractFileName().c_str(),
1148             // Simulate NSURLResponse's mapping of empty/unknown MIME types to application/octet-stream
1149             mimeType.isEmpty() ? "application/octet-stream" : mimeType.utf8().data());
1150     }
1151 }
1152
1153 void WebViewHost::didFinishResourceLoad(WebFrame*, unsigned identifier)
1154 {
1155     if (m_shell->shouldDumpResourceLoadCallbacks()) {
1156         printResourceDescription(identifier);
1157         fputs(" - didFinishLoading\n", stdout);
1158     }
1159     removeIdentifierForRequest(identifier);
1160 }
1161
1162 void WebViewHost::didFailResourceLoad(WebFrame*, unsigned identifier, const WebURLError& error)
1163 {
1164     if (m_shell->shouldDumpResourceLoadCallbacks()) {
1165         printResourceDescription(identifier);
1166         fputs(" - didFailLoadingWithError: ", stdout);
1167         fputs(webkit_support::MakeURLErrorDescription(error).c_str(), stdout);
1168         fputs("\n", stdout);
1169     }
1170     removeIdentifierForRequest(identifier);
1171 }
1172
1173 void WebViewHost::didDisplayInsecureContent(WebFrame*)
1174 {
1175     if (m_shell->shouldDumpFrameLoadCallbacks())
1176         fputs("didDisplayInsecureContent\n", stdout);
1177 }
1178
1179 void WebViewHost::didRunInsecureContent(WebFrame*, const WebSecurityOrigin& origin, const WebURL& insecureURL)
1180 {
1181     if (m_shell->shouldDumpFrameLoadCallbacks())
1182         fputs("didRunInsecureContent\n", stdout);
1183 }
1184
1185 void WebViewHost::didDetectXSS(WebFrame*, const WebURL&, bool)
1186 {
1187     if (m_shell->shouldDumpFrameLoadCallbacks())
1188         fputs("didDetectXSS\n", stdout);
1189 }
1190
1191 void WebViewHost::openFileSystem(WebFrame* frame, WebFileSystem::Type type, long long size, bool create, WebFileSystemCallbacks* callbacks)
1192 {
1193     webkit_support::OpenFileSystem(frame, type, size, create, callbacks);
1194 }
1195
1196 // Public functions -----------------------------------------------------------
1197
1198 WebViewHost::WebViewHost(TestShell* shell)
1199     : m_shell(shell)
1200     , m_webWidget(0)
1201     , m_lastRequestedTextCheckingCompletion(0)
1202 {
1203     WTF::initializeThreading();
1204
1205     m_compositorThread = adoptPtr(WebKit::webKitPlatformSupport()->createThread("Compositor"));
1206     WebCompositor::setThread(m_compositorThread.get());
1207
1208     reset();
1209 }
1210
1211 WebViewHost::~WebViewHost()
1212 {
1213     // DevTools frontend page is supposed to be navigated only once and
1214     // loading another URL in that Page is an error.
1215     if (m_shell->devToolsWebView() != this) {
1216         // Navigate to an empty page to fire all the destruction logic for the
1217         // current page.
1218         loadURLForFrame(GURL("about:blank"), WebString());
1219     }
1220
1221     for (Vector<WebKit::WebWidget*>::iterator it = m_popupmenus.begin();
1222          it < m_popupmenus.end(); ++it)
1223         (*it)->close();
1224
1225     webWidget()->close();
1226     if (m_inModalLoop)
1227         webkit_support::QuitMessageLoop();
1228 }
1229
1230 void WebViewHost::setWebWidget(WebKit::WebWidget* widget)
1231 {
1232     m_webWidget = widget;
1233     webView()->setSpellCheckClient(this);
1234 }
1235
1236 WebView* WebViewHost::webView() const
1237 {
1238     ASSERT(m_webWidget);
1239     // DRT does not support popup widgets. So m_webWidget is always a WebView.
1240     return static_cast<WebView*>(m_webWidget);
1241 }
1242
1243 WebWidget* WebViewHost::webWidget() const
1244 {
1245     ASSERT(m_webWidget);
1246     return m_webWidget;
1247 }
1248
1249 void WebViewHost::reset()
1250 {
1251     m_policyDelegateEnabled = false;
1252     m_policyDelegateIsPermissive = false;
1253     m_policyDelegateShouldNotifyDone = false;
1254     m_topLoadingFrame = 0;
1255     m_pageId = -1;
1256     m_lastPageIdUpdated = -1;
1257     m_hasWindow = false;
1258     m_inModalLoop = false;
1259     m_smartInsertDeleteEnabled = true;
1260     m_logConsoleOutput = true;
1261 #if OS(WINDOWS)
1262     m_selectTrailingWhitespaceEnabled = true;
1263 #else
1264     m_selectTrailingWhitespaceEnabled = false;
1265 #endif
1266     m_blocksRedirects = false;
1267     m_requestReturnNull = false;
1268     m_isPainting = false;
1269     m_canvas.clear();
1270
1271     m_navigationController = adoptPtr(new TestNavigationController(this));
1272
1273     m_pendingExtraData.clear();
1274     m_resourceIdentifierMap.clear();
1275     m_clearHeaders.clear();
1276     m_editCommandName.clear();
1277     m_editCommandValue.clear();
1278
1279     if (m_geolocationClientMock.get())
1280         m_geolocationClientMock->resetMock();
1281
1282     if (m_speechInputControllerMock.get())
1283         m_speechInputControllerMock->clearResults();
1284
1285     m_currentCursor = WebCursorInfo();
1286     m_windowRect = WebRect();
1287     m_paintRect = WebRect();
1288
1289     if (m_webWidget) {
1290         webView()->mainFrame()->setName(WebString());
1291         webView()->settings()->setMinimumTimerInterval(webkit_support::GetForegroundTabTimerInterval());
1292     }
1293 }
1294
1295 void WebViewHost::setSelectTrailingWhitespaceEnabled(bool enabled)
1296 {
1297     m_selectTrailingWhitespaceEnabled = enabled;
1298     // In upstream WebKit, smart insert/delete is mutually exclusive with select
1299     // trailing whitespace, however, we allow both because Chromium on Windows
1300     // allows both.
1301 }
1302
1303 void WebViewHost::setSmartInsertDeleteEnabled(bool enabled)
1304 {
1305     m_smartInsertDeleteEnabled = enabled;
1306     // In upstream WebKit, smart insert/delete is mutually exclusive with select
1307     // trailing whitespace, however, we allow both because Chromium on Windows
1308     // allows both.
1309 }
1310
1311 void WebViewHost::setLogConsoleOutput(bool enabled)
1312 {
1313     m_logConsoleOutput = enabled;
1314 }
1315
1316 void WebViewHost::setCustomPolicyDelegate(bool isCustom, bool isPermissive)
1317 {
1318     m_policyDelegateEnabled = isCustom;
1319     m_policyDelegateIsPermissive = isPermissive;
1320 }
1321
1322 void WebViewHost::waitForPolicyDelegate()
1323 {
1324     m_policyDelegateEnabled = true;
1325     m_policyDelegateShouldNotifyDone = true;
1326 }
1327
1328 void WebViewHost::setEditCommand(const string& name, const string& value)
1329 {
1330     m_editCommandName = name;
1331     m_editCommandValue = value;
1332 }
1333
1334 void WebViewHost::clearEditCommand()
1335 {
1336     m_editCommandName.clear();
1337     m_editCommandValue.clear();
1338 }
1339
1340 void WebViewHost::loadURLForFrame(const WebURL& url, const WebString& frameName)
1341 {
1342     if (!url.isValid())
1343         return;
1344     TestShell::resizeWindowForTest(this, url);
1345     navigationController()->loadEntry(TestNavigationEntry::create(-1, url, WebString(), frameName).get());
1346 }
1347
1348 bool WebViewHost::navigate(const TestNavigationEntry& entry, bool reload)
1349 {
1350     // Get the right target frame for the entry.
1351     WebFrame* frame = webView()->mainFrame();
1352     if (!entry.targetFrame().isEmpty())
1353         frame = webView()->findFrameByName(entry.targetFrame());
1354
1355     // TODO(mpcomplete): should we clear the target frame, or should
1356     // back/forward navigations maintain the target frame?
1357
1358     // A navigation resulting from loading a javascript URL should not be
1359     // treated as a browser initiated event. Instead, we want it to look as if
1360     // the page initiated any load resulting from JS execution.
1361     if (!GURL(entry.URL()).SchemeIs("javascript"))
1362         setPendingExtraData(adoptPtr(new TestShellExtraData(entry.pageID())));
1363
1364     // If we are reloading, then WebKit will use the state of the current page.
1365     // Otherwise, we give it the state to navigate to.
1366     if (reload) {
1367         frame->reload(false);
1368     } else if (!entry.contentState().isNull()) {
1369         ASSERT(entry.pageID() != -1);
1370         frame->loadHistoryItem(entry.contentState());
1371     } else {
1372         ASSERT(entry.pageID() == -1);
1373         frame->loadRequest(WebURLRequest(entry.URL()));
1374     }
1375
1376     // In case LoadRequest failed before DidCreateDataSource was called.
1377     setPendingExtraData(nullptr);
1378
1379     // Restore focus to the main frame prior to loading new request.
1380     // This makes sure that we don't have a focused iframe. Otherwise, that
1381     // iframe would keep focus when the SetFocus called immediately after
1382     // LoadRequest, thus making some tests fail (see http://b/issue?id=845337
1383     // for more details).
1384     webView()->setFocusedFrame(frame);
1385     m_shell->setFocus(webView(), true);
1386
1387     return true;
1388 }
1389
1390 // Private functions ----------------------------------------------------------
1391
1392 LayoutTestController* WebViewHost::layoutTestController() const
1393 {
1394     return m_shell->layoutTestController();
1395 }
1396
1397 void WebViewHost::updateAddressBar(WebView* webView)
1398 {
1399     WebFrame* mainFrame = webView->mainFrame();
1400     WebDataSource* dataSource = mainFrame->dataSource();
1401     if (!dataSource)
1402         dataSource = mainFrame->provisionalDataSource();
1403     if (!dataSource)
1404         return;
1405
1406     setAddressBarURL(dataSource->request().url());
1407 }
1408
1409 void WebViewHost::locationChangeDone(WebFrame* frame)
1410 {
1411     if (frame != m_topLoadingFrame)
1412         return;
1413     m_topLoadingFrame = 0;
1414     layoutTestController()->locationChangeDone();
1415 }
1416
1417 void WebViewHost::updateForCommittedLoad(WebFrame* frame, bool isNewNavigation)
1418 {
1419     // Code duplicated from RenderView::DidCommitLoadForFrame.
1420     TestShellExtraData* extraData = static_cast<TestShellExtraData*>(frame->dataSource()->extraData());
1421
1422     if (isNewNavigation) {
1423         // New navigation.
1424         updateSessionHistory(frame);
1425         m_pageId = nextPageID++;
1426     } else if (extraData && extraData->pendingPageID != -1 && !extraData->requestCommitted) {
1427         // This is a successful session history navigation!
1428         updateSessionHistory(frame);
1429         m_pageId = extraData->pendingPageID;
1430     }
1431
1432     // Don't update session history multiple times.
1433     if (extraData)
1434         extraData->requestCommitted = true;
1435
1436     updateURL(frame);
1437 }
1438
1439 void WebViewHost::updateURL(WebFrame* frame)
1440 {
1441     WebDataSource* ds = frame->dataSource();
1442     ASSERT(ds);
1443     const WebURLRequest& request = ds->request();
1444     RefPtr<TestNavigationEntry> entry(TestNavigationEntry::create());
1445
1446     // The referrer will be empty on https->http transitions. It
1447     // would be nice if we could get the real referrer from somewhere.
1448     entry->setPageID(m_pageId);
1449     if (ds->hasUnreachableURL())
1450         entry->setURL(ds->unreachableURL());
1451     else
1452         entry->setURL(request.url());
1453
1454     const WebHistoryItem& historyItem = frame->currentHistoryItem();
1455     if (!historyItem.isNull())
1456         entry->setContentState(historyItem);
1457
1458     navigationController()->didNavigateToEntry(entry.get());
1459     updateAddressBar(frame->view());
1460     m_lastPageIdUpdated = max(m_lastPageIdUpdated, m_pageId);
1461 }
1462
1463 void WebViewHost::updateSessionHistory(WebFrame* frame)
1464 {
1465     // If we have a valid page ID at this point, then it corresponds to the page
1466     // we are navigating away from. Otherwise, this is the first navigation, so
1467     // there is no past session history to record.
1468     if (m_pageId == -1)
1469         return;
1470
1471     TestNavigationEntry* entry = navigationController()->entryWithPageID(m_pageId);
1472     if (!entry)
1473         return;
1474
1475     const WebHistoryItem& historyItem = webView()->mainFrame()->previousHistoryItem();
1476     if (historyItem.isNull())
1477         return;
1478
1479     entry->setContentState(historyItem);
1480 }
1481
1482 void WebViewHost::printFrameDescription(WebFrame* webframe)
1483 {
1484     string name8 = webframe->name().utf8();
1485     if (webframe == webView()->mainFrame()) {
1486         if (!name8.length()) {
1487             fputs("main frame", stdout);
1488             return;
1489         }
1490         printf("main frame \"%s\"", name8.c_str());
1491         return;
1492     }
1493     if (!name8.length()) {
1494         fputs("frame (anonymous)", stdout);
1495         return;
1496     }
1497     printf("frame \"%s\"", name8.c_str());
1498 }
1499
1500 void WebViewHost::printFrameUserGestureStatus(WebFrame* webframe, const char* msg)
1501 {
1502     bool isUserGesture = webframe->isProcessingUserGesture();
1503     printf("Frame with user gesture \"%s\"%s", isUserGesture ? "true" : "false", msg);
1504 }
1505
1506 void WebViewHost::printResourceDescription(unsigned identifier)
1507 {
1508     ResourceMap::iterator it = m_resourceIdentifierMap.find(identifier);
1509     printf("%s", it != m_resourceIdentifierMap.end() ? it->second.c_str() : "<unknown>");
1510 }
1511
1512 void WebViewHost::setPendingExtraData(PassOwnPtr<TestShellExtraData> extraData)
1513 {
1514     m_pendingExtraData = extraData;
1515 }
1516
1517 void WebViewHost::setPageTitle(const WebString&)
1518 {
1519     // Nothing to do in layout test.
1520 }
1521
1522 void WebViewHost::setAddressBarURL(const WebURL&)
1523 {
1524     // Nothing to do in layout test.
1525 }
1526
1527 void WebViewHost::enterFullScreenNow()
1528 {
1529     webView()->willEnterFullScreen();
1530     webView()->didEnterFullScreen();
1531 }
1532
1533 void WebViewHost::exitFullScreenNow()
1534 {
1535     webView()->willExitFullScreen();
1536     webView()->didExitFullScreen();
1537 }
1538
1539 // Painting functions ---------------------------------------------------------
1540
1541 void WebViewHost::updatePaintRect(const WebRect& rect)
1542 {
1543     // m_paintRect = m_paintRect U rect
1544     if (rect.isEmpty())
1545         return;
1546     if (m_paintRect.isEmpty()) {
1547         m_paintRect = rect;
1548         return;
1549     }
1550     int left = min(m_paintRect.x, rect.x);
1551     int top = min(m_paintRect.y, rect.y);
1552     int right = max(m_paintRect.x + m_paintRect.width, rect.x + rect.width);
1553     int bottom = max(m_paintRect.y + m_paintRect.height, rect.y + rect.height);
1554     m_paintRect = WebRect(left, top, right - left, bottom - top);
1555 }
1556
1557 void WebViewHost::paintRect(const WebRect& rect)
1558 {
1559     ASSERT(!m_isPainting);
1560     ASSERT(canvas());
1561     m_isPainting = true;
1562 #if USE(CG)
1563     webWidget()->paint(skia::BeginPlatformPaint(canvas()), rect);
1564     skia::EndPlatformPaint(canvas());
1565 #else
1566     webWidget()->paint(canvas(), rect);
1567 #endif
1568     m_isPainting = false;
1569 }
1570
1571 void WebViewHost::paintInvalidatedRegion()
1572 {
1573 #if ENABLE(REQUEST_ANIMATION_FRAME)
1574     webWidget()->animate(0.0);
1575 #endif
1576     webWidget()->layout();
1577     WebSize widgetSize = webWidget()->size();
1578     WebRect clientRect(0, 0, widgetSize.width, widgetSize.height);
1579
1580     // Paint the canvas if necessary. Allow painting to generate extra rects
1581     // for the first two calls. This is necessary because some WebCore rendering
1582     // objects update their layout only when painted.
1583     // Store the total area painted in total_paint. Then tell the gdk window
1584     // to update that area after we're done painting it.
1585     for (int i = 0; i < 3; ++i) {
1586         // m_paintRect = intersect(m_paintRect , clientRect)
1587         int left = max(m_paintRect.x, clientRect.x);
1588         int top = max(m_paintRect.y, clientRect.y);
1589         int right = min(m_paintRect.x + m_paintRect.width, clientRect.x + clientRect.width);
1590         int bottom = min(m_paintRect.y + m_paintRect.height, clientRect.y + clientRect.height);
1591         if (left >= right || top >= bottom)
1592             m_paintRect = WebRect();
1593         else
1594             m_paintRect = WebRect(left, top, right - left, bottom - top);
1595
1596         if (m_paintRect.isEmpty())
1597             continue;
1598         WebRect rect(m_paintRect);
1599         m_paintRect = WebRect();
1600         paintRect(rect);
1601     }
1602     ASSERT(m_paintRect.isEmpty());
1603 }
1604
1605 void WebViewHost::paintPagesWithBoundaries()
1606 {
1607     ASSERT(!m_isPainting);
1608     ASSERT(canvas());
1609     m_isPainting = true;
1610
1611     WebSize pageSizeInPixels = webWidget()->size();
1612     WebFrame* webFrame = webView()->mainFrame();
1613
1614     int pageCount = webFrame->printBegin(pageSizeInPixels);
1615     int totalHeight = pageCount * (pageSizeInPixels.height + 1) - 1;
1616
1617     SkCanvas* testCanvas = skia::TryCreateBitmapCanvas(pageSizeInPixels.width, totalHeight, true);
1618     if (testCanvas) {
1619         discardBackingStore();
1620         m_canvas = adoptPtr(testCanvas);
1621     } else {
1622         webFrame->printEnd();
1623         return;
1624     }
1625
1626 #if WEBKIT_USING_SKIA
1627     WebCanvas* webCanvas = canvas();
1628 #elif WEBKIT_USING_CG
1629     const SkBitmap& canvasBitmap = canvas()->getDevice()->accessBitmap(false);
1630     WebCanvas* webCanvas = CGBitmapContextCreate(canvasBitmap.getPixels(),
1631                                                  pageSizeInPixels.width, totalHeight,
1632                                                  8, pageSizeInPixels.width * 4,
1633                                                  CGColorSpaceCreateDeviceRGB(),
1634                                                  kCGImageAlphaPremultipliedFirst |
1635                                                  kCGBitmapByteOrder32Host);
1636     CGContextTranslateCTM(webCanvas, 0.0, totalHeight);
1637     CGContextScaleCTM(webCanvas, 1.0, -1.0f);
1638 #endif
1639
1640     webFrame->printPagesWithBoundaries(webCanvas, pageSizeInPixels);
1641     webFrame->printEnd();
1642
1643     m_isPainting = false;
1644 }
1645
1646 SkCanvas* WebViewHost::canvas()
1647 {
1648     if (m_canvas)
1649         return m_canvas.get();
1650     WebSize widgetSize = webWidget()->size();
1651     resetScrollRect();
1652     m_canvas = adoptPtr(skia::CreateBitmapCanvas(widgetSize.width, widgetSize.height, true));
1653     return m_canvas.get();
1654 }
1655
1656 void WebViewHost::resetScrollRect()
1657 {
1658 }
1659
1660 void WebViewHost::discardBackingStore()
1661 {
1662     m_canvas.clear();
1663 }
1664
1665 // Paints the entire canvas a semi-transparent black (grayish). This is used
1666 // by the layout tests in fast/repaint. The alpha value matches upstream.
1667 void WebViewHost::displayRepaintMask()
1668 {
1669     canvas()->drawARGB(167, 0, 0, 0);
1670 }