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