Fixed a typo I made in r103871.
[WebKit-https.git] / Source / WebKit2 / WebProcess / WebPage / WebPage.cpp
1 /*
2  * Copyright (C) 2010, 2011 Apple 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
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "WebPage.h"
28
29 #include "Arguments.h"
30 #include "DataReference.h"
31 #include "DecoderAdapter.h"
32 #include "DrawingArea.h"
33 #include "InjectedBundle.h"
34 #include "InjectedBundleBackForwardList.h"
35 #include "LayerTreeHost.h"
36 #include "MessageID.h"
37 #include "NetscapePlugin.h"
38 #include "NotificationPermissionRequestManager.h"
39 #include "PageOverlay.h"
40 #include "PluginProxy.h"
41 #include "PluginView.h"
42 #include "PrintInfo.h"
43 #include "RunLoop.h"
44 #include "SessionState.h"
45 #include "ShareableBitmap.h"
46 #include "WebBackForwardList.h"
47 #include "WebBackForwardListItem.h"
48 #include "WebBackForwardListProxy.h"
49 #include "WebChromeClient.h"
50 #include "WebContextMenu.h"
51 #include "WebContextMenuClient.h"
52 #include "WebContextMessages.h"
53 #include "WebCoreArgumentCoders.h"
54 #include "WebDragClient.h"
55 #include "WebEditorClient.h"
56 #include "WebEvent.h"
57 #include "WebEventConversion.h"
58 #include "WebFrame.h"
59 #include "WebFullScreenManager.h"
60 #include "WebGeolocationClient.h"
61 #include "WebGeometry.h"
62 #include "WebImage.h"
63 #include "WebInspector.h"
64 #include "WebInspectorClient.h"
65 #include "WebNotificationClient.h"
66 #include "WebOpenPanelResultListener.h"
67 #include "WebPageCreationParameters.h"
68 #include "WebPageGroupProxy.h"
69 #include "WebPageProxyMessages.h"
70 #include "WebPopupMenu.h"
71 #include "WebPreferencesStore.h"
72 #include "WebProcess.h"
73 #include "WebProcessProxyMessages.h"
74 #include <JavaScriptCore/APICast.h>
75 #include <WebCore/AbstractDatabase.h>
76 #include <WebCore/ArchiveResource.h>
77 #include <WebCore/Chrome.h>
78 #include <WebCore/ContextMenuController.h>
79 #include <WebCore/DocumentFragment.h>
80 #include <WebCore/DocumentLoader.h>
81 #include <WebCore/DocumentMarkerController.h>
82 #include <WebCore/DragController.h>
83 #include <WebCore/DragData.h>
84 #include <WebCore/DragSession.h>
85 #include <WebCore/EventHandler.h>
86 #include <WebCore/FocusController.h>
87 #include <WebCore/FormState.h>
88 #include <WebCore/Frame.h>
89 #include <WebCore/FrameLoadRequest.h>
90 #include <WebCore/FrameLoaderTypes.h>
91 #include <WebCore/FrameView.h>
92 #include <WebCore/HTMLFormElement.h>
93 #include <WebCore/HistoryItem.h>
94 #include <WebCore/KeyboardEvent.h>
95 #include <WebCore/MouseEvent.h>
96 #include <WebCore/Page.h>
97 #include <WebCore/PlatformKeyboardEvent.h>
98 #include <WebCore/PluginDocument.h>
99 #include <WebCore/PrintContext.h>
100 #include <WebCore/RenderArena.h>
101 #include <WebCore/RenderLayer.h>
102 #include <WebCore/RenderTreeAsText.h>
103 #include <WebCore/RenderView.h>
104 #include <WebCore/ReplaceSelectionCommand.h>
105 #include <WebCore/ResourceRequest.h>
106 #include <WebCore/SchemeRegistry.h>
107 #include <WebCore/ScriptValue.h>
108 #include <WebCore/SerializedScriptValue.h>
109 #include <WebCore/Settings.h>
110 #include <WebCore/SharedBuffer.h>
111 #include <WebCore/SubstituteData.h>
112 #include <WebCore/TextIterator.h>
113 #include <WebCore/markup.h>
114 #include <runtime/JSLock.h>
115 #include <runtime/JSValue.h>
116
117 #include <WebCore/Range.h>
118 #include <WebCore/VisiblePosition.h>
119
120 #if ENABLE(PLUGIN_PROCESS)
121 #if PLATFORM(MAC)
122 #include "MachPort.h"
123 #endif
124 #endif
125
126 #if PLATFORM(MAC)
127 #include "BuiltInPDFView.h"
128 #endif
129
130 #if PLATFORM(QT)
131 #include "HitTestResult.h"
132 #include <QMimeData>
133 #endif
134
135 #if PLATFORM(GTK)
136 #include "DataObjectGtk.h"
137 #endif
138
139 #ifndef NDEBUG
140 #include <wtf/RefCountedLeakCounter.h>
141 #endif
142
143 using namespace JSC;
144 using namespace WebCore;
145 using namespace std;
146
147 namespace WebKit {
148
149 class SendStopResponsivenessTimer {
150 public:
151     SendStopResponsivenessTimer(WebPage* page)
152         : m_page(page)
153     {
154     }
155     
156     ~SendStopResponsivenessTimer()
157     {
158         m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
159     }
160
161 private:
162     WebPage* m_page;
163 };
164
165 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
166
167 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
168 {
169     RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
170
171     if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
172         WebProcess::shared().injectedBundle()->didCreatePage(page.get());
173
174     return page.release();
175 }
176
177 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
178     : m_viewSize(parameters.viewSize)
179     , m_useFixedLayout(false)
180     , m_drawsBackground(true)
181     , m_drawsTransparentBackground(false)
182     , m_isInRedo(false)
183     , m_isClosed(false)
184     , m_tabToLinks(false)
185 #if PLATFORM(MAC)
186     , m_windowIsVisible(false)
187     , m_isSmartInsertDeleteEnabled(parameters.isSmartInsertDeleteEnabled)
188     , m_keyboardEventBeingInterpreted(0)
189 #elif PLATFORM(WIN)
190     , m_nativeWindow(parameters.nativeWindow)
191 #endif
192     , m_setCanStartMediaTimer(WebProcess::shared().runLoop(), this, &WebPage::setCanStartMediaTimerFired)
193     , m_findController(this)
194     , m_geolocationPermissionRequestManager(this)
195     , m_pageID(pageID)
196     , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
197     , m_canRunModal(parameters.canRunModal)
198     , m_isRunningModal(false)
199     , m_cachedMainFrameIsPinnedToLeftSide(false)
200     , m_cachedMainFrameIsPinnedToRightSide(false)
201     , m_cachedPageCount(0)
202     , m_isShowingContextMenu(false)
203 #if PLATFORM(WIN)
204     , m_gestureReachedScrollingLimit(false)
205 #endif
206 {
207     ASSERT(m_pageID);
208     // FIXME: This is a non-ideal location for this Setting and
209     // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
210     Settings::setDefaultMinDOMTimerInterval(0.004);
211
212     Page::PageClients pageClients;
213     pageClients.chromeClient = new WebChromeClient(this);
214     pageClients.contextMenuClient = new WebContextMenuClient(this);
215     pageClients.editorClient = new WebEditorClient(this);
216     pageClients.dragClient = new WebDragClient(this);
217     pageClients.backForwardClient = WebBackForwardListProxy::create(this);
218 #if ENABLE(CLIENT_BASED_GEOLOCATION)
219     pageClients.geolocationClient = new WebGeolocationClient(this);
220 #endif
221 #if ENABLE(INSPECTOR)
222     pageClients.inspectorClient = new WebInspectorClient(this);
223 #endif
224 #if ENABLE(NOTIFICATIONS)
225     pageClients.notificationClient = new WebNotificationClient(this);
226 #endif
227     
228     m_page = adoptPtr(new Page(pageClients));
229
230     // Qt does not yet call setIsInWindow. Until it does, just leave
231     // this line out so plug-ins and video will work. Eventually all platforms
232     // should call setIsInWindow and this comment and #if should be removed,
233     // leaving behind the setCanStartMedia call.
234 #if !PLATFORM(QT)
235     m_page->setCanStartMedia(false);
236 #endif
237
238     updatePreferences(parameters.store);
239
240     m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
241     m_page->setGroupName(m_pageGroup->identifier());
242
243     platformInitialize();
244
245     m_drawingArea = DrawingArea::create(this, parameters);
246     m_drawingArea->setPaintingEnabled(false);
247
248     m_mainFrame = WebFrame::createMainFrame(this);
249
250     setUseFixedLayout(parameters.useFixedLayout);
251
252     setDrawsBackground(parameters.drawsBackground);
253     setDrawsTransparentBackground(parameters.drawsTransparentBackground);
254
255     setPaginationMode(parameters.paginationMode);
256     setPageLength(parameters.pageLength);
257     setGapBetweenPages(parameters.gapBetweenPages);
258
259     setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
260
261     setActive(parameters.isActive);
262     setFocused(parameters.isFocused);
263     setIsInWindow(parameters.isInWindow);
264
265     m_userAgent = parameters.userAgent;
266
267     WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
268     
269     if (!parameters.sessionState.isEmpty())
270         restoreSession(parameters.sessionState);
271
272     m_drawingArea->setPaintingEnabled(true);
273
274 #ifndef NDEBUG
275     webPageCounter.increment();
276 #endif
277 }
278
279 WebPage::~WebPage()
280 {
281     if (m_backForwardList)
282         m_backForwardList->detach();
283
284     ASSERT(!m_page);
285
286     m_sandboxExtensionTracker.invalidate();
287
288 #if PLATFORM(MAC)
289     ASSERT(m_pluginViews.isEmpty());
290 #endif
291
292 #ifndef NDEBUG
293     webPageCounter.decrement();
294 #endif
295 }
296
297 void WebPage::dummy(bool&)
298 {
299 }
300
301 CoreIPC::Connection* WebPage::connection() const
302 {
303     return WebProcess::shared().connection();
304 }
305
306 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClient* client)
307 {
308     m_contextMenuClient.initialize(client);
309 }
310
311 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClient* client)
312 {
313     m_editorClient.initialize(client);
314 }
315
316 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClient* client)
317 {
318     m_formClient.initialize(client);
319 }
320
321 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClient* client)
322 {
323     m_loaderClient.initialize(client);
324 }
325
326 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClient* client)
327 {
328     m_policyClient.initialize(client);
329 }
330
331 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClient* client)
332 {
333     m_resourceLoadClient.initialize(client);
334 }
335
336 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClient* client)
337 {
338     m_uiClient.initialize(client);
339 }
340
341 #if ENABLE(FULLSCREEN_API)
342 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClient* client)
343 {
344     m_fullScreenClient.initialize(client);
345 }
346 #endif
347
348 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, const Plugin::Parameters& parameters)
349 {
350     String pluginPath;
351
352     if (!WebProcess::shared().connection()->sendSync(
353             Messages::WebContext::GetPluginPath(parameters.mimeType, parameters.url.string()), 
354             Messages::WebContext::GetPluginPath::Reply(pluginPath), 0)) {
355         return 0;
356     }
357
358     if (pluginPath.isNull()) {
359 #if PLATFORM(MAC)
360         if (parameters.mimeType == "application/pdf"
361             || (parameters.mimeType.isEmpty() && parameters.url.path().lower().endsWith(".pdf")))
362             return BuiltInPDFView::create(frame);
363 #else
364         UNUSED_PARAM(frame);
365 #endif
366         return 0;
367     }
368
369 #if ENABLE(PLUGIN_PROCESS)
370     return PluginProxy::create(pluginPath);
371 #else
372     NetscapePlugin::setSetExceptionFunction(NPRuntimeObjectMap::setGlobalException);
373     return NetscapePlugin::create(NetscapePluginModule::getOrCreate(pluginPath));
374 #endif
375 }
376
377 EditorState WebPage::editorState() const
378 {
379     Frame* frame = m_page->focusController()->focusedOrMainFrame();
380     ASSERT(frame);
381
382     EditorState result;
383     result.selectionIsNone = frame->selection()->isNone();
384     result.selectionIsRange = frame->selection()->isRange();
385     result.isContentEditable = frame->selection()->isContentEditable();
386     result.isContentRichlyEditable = frame->selection()->isContentRichlyEditable();
387     result.isInPasswordField = frame->selection()->isInPasswordField();
388     result.hasComposition = frame->editor()->hasComposition();
389
390 #if PLATFORM(QT)
391     size_t location = 0;
392     size_t length = 0;
393     Element* scope = frame->selection()->rootEditableElement();
394
395     RefPtr<Range> range;
396     if (result.hasComposition && (range = frame->editor()->compositionRange())) {
397         TextIterator::getLocationAndLengthFromRange(scope, range.get(), location, length);
398         result.compositionStart = location;
399         result.compositionLength = length;
400         result.compositionRect = range->boundingBox();
401     }
402
403     if (!result.selectionIsNone && (range = frame->selection()->selection().firstRange())) {
404         TextIterator::getLocationAndLengthFromRange(scope, range.get(), location, length);
405
406         ExceptionCode ec = 0;
407         RefPtr<Range> tempRange = range->cloneRange(ec);
408         tempRange->setStart(tempRange->startContainer(ec), tempRange->startOffset(ec) + location, ec);
409         IntRect rect = frame->editor()->firstRectForRange(tempRange.get());
410         bool baseIsFirst = frame->selection()->selection().isBaseFirst();
411
412         result.cursorPosition = (baseIsFirst) ? location + length : location;
413         result.anchorPosition = (baseIsFirst) ? location : location + length;
414         result.microFocus = frame->view()->contentsToWindow(rect);
415         result.selectedText = range->text();
416     }
417
418     if (scope && result.isContentEditable && !result.isInPasswordField) {
419         result.surroundingText = scope->innerText();
420         result.surroundingText.remove(result.compositionStart, result.compositionLength);
421     }
422 #endif
423
424     result.shouldIgnoreCompositionSelectionChange = frame->editor()->ignoreCompositionSelectionChange();
425
426     return result;
427 }
428
429 String WebPage::renderTreeExternalRepresentation() const
430 {
431     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
432 }
433
434 uint64_t WebPage::renderTreeSize() const
435 {
436     if (!m_page)
437         return 0;
438
439     Frame* mainFrame = m_page->mainFrame();
440     if (!mainFrame)
441         return 0;
442
443     uint64_t size = 0;
444     for (Frame* coreFrame = mainFrame; coreFrame; coreFrame = coreFrame->tree()->traverseNext())
445         size += coreFrame->document()->renderArena()->totalRenderArenaSize();
446
447     return size;
448 }
449
450 void WebPage::setTracksRepaints(bool trackRepaints)
451 {
452     if (FrameView* view = mainFrameView())
453         view->setTracksRepaints(trackRepaints);
454 }
455
456 bool WebPage::isTrackingRepaints() const
457 {
458     if (FrameView* view = mainFrameView())
459         return view->isTrackingRepaints();
460
461     return false;
462 }
463
464 void WebPage::resetTrackedRepaints()
465 {
466     if (FrameView* view = mainFrameView())
467         view->resetTrackedRepaints();
468 }
469
470 PassRefPtr<ImmutableArray> WebPage::trackedRepaintRects()
471 {
472     FrameView* view = mainFrameView();
473     if (!view)
474         return ImmutableArray::create();
475
476     const Vector<IntRect>& rects = view->trackedRepaintRects();
477     size_t size = rects.size();
478     if (!size)
479         return ImmutableArray::create();
480
481     Vector<RefPtr<APIObject> > vector;
482     vector.reserveInitialCapacity(size);
483
484     for (size_t i = 0; i < size; ++i)
485         vector.uncheckedAppend(WebRect::create(toAPI(rects[i])));
486
487     return ImmutableArray::adopt(vector);
488 }
489
490 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
491 {
492     Frame* frame = m_page->focusController()->focusedOrMainFrame();
493     if (!frame)
494         return;
495     frame->editor()->command(commandName).execute(argument);
496 }
497
498 bool WebPage::isEditingCommandEnabled(const String& commandName)
499 {
500     Frame* frame = m_page->focusController()->focusedOrMainFrame();
501     if (!frame)
502         return false;
503     
504     Editor::Command command = frame->editor()->command(commandName);
505     return command.isSupported() && command.isEnabled();
506 }
507     
508 void WebPage::clearMainFrameName()
509 {
510     if (Frame* frame = mainFrame())
511         frame->tree()->clearName();
512 }
513
514 #if USE(ACCELERATED_COMPOSITING)
515 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
516 {
517     m_drawingArea->setRootCompositingLayer(layer);
518 }
519
520 void WebPage::exitAcceleratedCompositingMode()
521 {
522     m_drawingArea->setRootCompositingLayer(0);
523 }
524 #endif
525
526 void WebPage::close()
527 {
528     if (m_isClosed)
529         return;
530
531     m_isClosed = true;
532
533     if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
534         WebProcess::shared().injectedBundle()->willDestroyPage(this);
535
536 #if ENABLE(INSPECTOR)
537     m_inspector = 0;
538 #endif
539 #if ENABLE(FULLSCREEN_API)
540     m_fullScreenManager = 0;
541 #endif
542
543     if (m_activePopupMenu) {
544         m_activePopupMenu->disconnectFromPage();
545         m_activePopupMenu = 0;
546     }
547
548     if (m_activeOpenPanelResultListener) {
549         m_activeOpenPanelResultListener->disconnectFromPage();
550         m_activeOpenPanelResultListener = 0;
551     }
552
553     m_sandboxExtensionTracker.invalidate();
554
555     m_underlayPage = nullptr;
556     m_printContext = nullptr;
557     m_mainFrame->coreFrame()->loader()->detachFromParent();
558     m_page = nullptr;
559     m_drawingArea = nullptr;
560
561     bool isRunningModal = m_isRunningModal;
562     m_isRunningModal = false;
563
564     // The WebPage can be destroyed by this call.
565     WebProcess::shared().removeWebPage(m_pageID);
566
567     if (isRunningModal)
568         WebProcess::shared().runLoop()->stop();
569 }
570
571 void WebPage::tryClose()
572 {
573     SendStopResponsivenessTimer stopper(this);
574
575     if (!m_mainFrame->coreFrame()->loader()->shouldClose()) {
576         send(Messages::WebPageProxy::StopResponsivenessTimer());
577         return;
578     }
579
580     send(Messages::WebPageProxy::ClosePage(true));
581 }
582
583 void WebPage::sendClose()
584 {
585     send(Messages::WebPageProxy::ClosePage(false));
586 }
587
588 void WebPage::loadURL(const String& url, const SandboxExtension::Handle& sandboxExtensionHandle)
589 {
590     loadURLRequest(ResourceRequest(KURL(KURL(), url)), sandboxExtensionHandle);
591 }
592
593 void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle)
594 {
595     SendStopResponsivenessTimer stopper(this);
596
597     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
598     m_mainFrame->coreFrame()->loader()->load(request, false);
599 }
600
601 void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL)
602 {
603     SendStopResponsivenessTimer stopper(this);
604
605     ResourceRequest request(baseURL);
606     SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
607     m_mainFrame->coreFrame()->loader()->load(request, substituteData, false);
608 }
609
610 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString)
611 {
612     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
613     KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
614     loadData(sharedBuffer, "text/html", "utf-16", baseURL, KURL());
615 }
616
617 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString)
618 {
619     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
620     KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
621     KURL unreachableURL = unreachableURLString.isEmpty() ? KURL() : KURL(KURL(), unreachableURLString);
622     loadData(sharedBuffer, "text/html", "utf-16", baseURL, unreachableURL);
623 }
624
625 void WebPage::loadPlainTextString(const String& string)
626 {
627     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(string.characters()), string.length() * sizeof(UChar));
628     loadData(sharedBuffer, "text/plain", "utf-16", blankURL(), KURL());
629 }
630
631 void WebPage::linkClicked(const String& url, const WebMouseEvent& event)
632 {
633     Frame* frame = m_page->mainFrame();
634     if (!frame)
635         return;
636
637     RefPtr<Event> coreEvent;
638     if (event.type() != WebEvent::NoType)
639         coreEvent = MouseEvent::create(eventNames().clickEvent, frame->document()->defaultView(), platform(event), 0, 0);
640
641     frame->loader()->loadFrameRequest(FrameLoadRequest(frame->document()->securityOrigin(), ResourceRequest(url)), 
642         false, false, coreEvent.get(), 0, MaybeSendReferrer);
643 }
644
645 void WebPage::stopLoadingFrame(uint64_t frameID)
646 {
647     WebFrame* frame = WebProcess::shared().webFrame(frameID);
648     if (!frame)
649         return;
650
651     frame->coreFrame()->loader()->stopForUserCancel();
652 }
653
654 void WebPage::stopLoading()
655 {
656     SendStopResponsivenessTimer stopper(this);
657
658     m_mainFrame->coreFrame()->loader()->stopForUserCancel();
659 }
660
661 void WebPage::setDefersLoading(bool defersLoading)
662 {
663     m_page->setDefersLoading(defersLoading);
664 }
665
666 void WebPage::reload(bool reloadFromOrigin)
667 {
668     SendStopResponsivenessTimer stopper(this);
669
670     m_mainFrame->coreFrame()->loader()->reload(reloadFromOrigin);
671 }
672
673 void WebPage::goForward(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
674 {
675     SendStopResponsivenessTimer stopper(this);
676
677     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
678     ASSERT(item);
679     if (!item)
680         return;
681
682     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
683     m_page->goToItem(item, FrameLoadTypeForward);
684 }
685
686 void WebPage::goBack(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
687 {
688     SendStopResponsivenessTimer stopper(this);
689
690     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
691     ASSERT(item);
692     if (!item)
693         return;
694
695     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
696     m_page->goToItem(item, FrameLoadTypeBack);
697 }
698
699 void WebPage::goToBackForwardItem(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
700 {
701     SendStopResponsivenessTimer stopper(this);
702
703     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
704     ASSERT(item);
705     if (!item)
706         return;
707
708     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
709     m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
710 }
711
712 void WebPage::tryRestoreScrollPosition()
713 {
714     m_page->mainFrame()->loader()->history()->restoreScrollPositionAndViewState();
715 }
716
717 void WebPage::layoutIfNeeded()
718 {
719     if (m_mainFrame->coreFrame()->view())
720         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
721
722     if (m_underlayPage) {
723         if (FrameView *frameView = m_underlayPage->mainFrameView())
724             frameView->updateLayoutAndStyleIfNeededRecursive();
725     }
726 }
727
728 void WebPage::setSize(const WebCore::IntSize& viewSize)
729 {
730     FrameView* view = m_page->mainFrame()->view();
731
732 #if USE(TILED_BACKING_STORE)
733     // If we are resizing to content ignore external attempts.
734     if (view->useFixedLayout())
735         return;
736 #endif
737
738     if (m_viewSize == viewSize)
739         return;
740
741     view->resize(viewSize);
742     view->setNeedsLayout();
743     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), viewSize));
744     
745     m_viewSize = viewSize;
746 }
747
748 #if USE(TILED_BACKING_STORE)
749 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
750 {
751     ASSERT(m_useFixedLayout);
752
753     Frame* frame = m_page->mainFrame();
754
755     frame->view()->setFixedVisibleContentRect(rect);
756 }
757
758 void WebPage::setResizesToContentsUsingLayoutSize(const IntSize& targetLayoutSize)
759 {
760     ASSERT(m_useFixedLayout);
761     ASSERT(!targetLayoutSize.isEmpty());
762
763     FrameView* view = m_page->mainFrame()->view();
764
765     view->setDelegatesScrolling(true);
766     view->setUseFixedLayout(true);
767     view->setPaintsEntireContents(true);
768
769     if (view->fixedLayoutSize() == targetLayoutSize)
770         return;
771
772     // Always reset even when empty.
773     view->setFixedLayoutSize(targetLayoutSize);
774
775     // Schedule a layout to use the new target size.
776     if (!view->layoutPending()) {
777         view->setNeedsLayout();
778         view->scheduleRelayout();
779     }
780 }
781
782 void WebPage::resizeToContentsIfNeeded()
783 {
784     ASSERT(m_useFixedLayout);
785
786     FrameView* view = m_page->mainFrame()->view();
787
788     if (!view->useFixedLayout())
789         return;
790
791     IntSize contentSize = view->contentsSize();
792     if (contentSize == m_viewSize)
793         return;
794
795     m_viewSize = contentSize;
796     view->resize(m_viewSize);
797     view->setNeedsLayout();
798 }
799
800 void WebPage::setViewportSize(const IntSize& size)
801 {
802     ASSERT(m_useFixedLayout);
803
804     if (m_viewportSize == size)
805         return;
806
807      m_viewportSize = size;
808
809     // Recalculate the recommended layout size, when the available size (device pixel) changes.
810     Settings* settings = m_page->settings();
811
812     int minimumLayoutFallbackWidth = std::max(settings->layoutFallbackWidth(), size.width());
813
814     IntSize targetLayoutSize = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, settings->deviceWidth(), settings->deviceHeight(), settings->deviceDPI(), size).layoutSize;
815     setResizesToContentsUsingLayoutSize(targetLayoutSize);
816 }
817
818 #endif
819
820 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
821 {
822     Frame* frame = m_page->mainFrame();
823
824     IntPoint scrollPosition = frame->view()->scrollPosition();
825     IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
826
827     // If the current scroll position in a direction is the max scroll position 
828     // we don't want to scroll at all.
829     IntSize newScrollOffset;
830     if (scrollPosition.x() < maximumScrollPosition.x())
831         newScrollOffset.setWidth(scrollOffset.width());
832     if (scrollPosition.y() < maximumScrollPosition.y())
833         newScrollOffset.setHeight(scrollOffset.height());
834
835     if (newScrollOffset.isZero())
836         return;
837
838     frame->view()->setScrollPosition(frame->view()->scrollPosition() + newScrollOffset);
839 }
840
841 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
842 {
843     GraphicsContextStateSaver stateSaver(graphicsContext);
844     graphicsContext.clip(rect);
845
846     if (m_underlayPage) {
847         m_underlayPage->drawRect(graphicsContext, rect);
848
849         graphicsContext.beginTransparencyLayer(1);
850         m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
851         graphicsContext.endTransparencyLayer();
852         return;
853     }
854
855     m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
856 }
857
858 void WebPage::drawPageOverlay(GraphicsContext& graphicsContext, const IntRect& rect)
859 {
860     ASSERT(m_pageOverlay);
861
862     GraphicsContextStateSaver stateSaver(graphicsContext);
863     graphicsContext.clip(rect);
864     m_pageOverlay->drawRect(graphicsContext, rect);
865 }
866
867 double WebPage::textZoomFactor() const
868 {
869     Frame* frame = m_mainFrame->coreFrame();
870     if (!frame)
871         return 1;
872     return frame->textZoomFactor();
873 }
874
875 void WebPage::setTextZoomFactor(double zoomFactor)
876 {
877     Frame* frame = m_mainFrame->coreFrame();
878     if (!frame)
879         return;
880     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
881 }
882
883 double WebPage::pageZoomFactor() const
884 {
885     Frame* frame = m_mainFrame->coreFrame();
886     if (!frame)
887         return 1;
888     return frame->pageZoomFactor();
889 }
890
891 void WebPage::setPageZoomFactor(double zoomFactor)
892 {
893     Frame* frame = m_mainFrame->coreFrame();
894     if (!frame)
895         return;
896     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
897 }
898
899 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
900 {
901     Frame* frame = m_mainFrame->coreFrame();
902     if (!frame)
903         return;
904     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
905 }
906
907 void WebPage::windowScreenDidChange(uint64_t displayID)
908 {
909     m_page->windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
910 }
911
912 void WebPage::scalePage(double scale, const IntPoint& origin)
913 {
914     m_page->setPageScaleFactor(scale, origin);
915
916     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
917 }
918
919 double WebPage::pageScaleFactor() const
920 {
921     return m_page->pageScaleFactor();
922 }
923
924 void WebPage::setDeviceScaleFactor(float scaleFactor)
925 {
926     if (scaleFactor == m_page->deviceScaleFactor())
927         return;
928
929     m_page->setDeviceScaleFactor(scaleFactor);
930
931     // Tell all our plug-in views that the device scale factor changed.
932 #if PLATFORM(MAC)
933     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
934         (*it)->setDeviceScaleFactor(scaleFactor);
935 #endif
936
937     if (m_findController.isShowingOverlay()) {
938         // We must have updated layout to get the selection rects right.
939         layoutIfNeeded();
940         m_findController.deviceScaleFactorDidChange();
941     }
942 }
943
944 float WebPage::deviceScaleFactor() const
945 {
946     return m_page->deviceScaleFactor();
947 }
948
949 void WebPage::setUseFixedLayout(bool fixed)
950 {
951     m_useFixedLayout = fixed;
952
953     FrameView* view = mainFrameView();
954     if (!view)
955         return;
956
957     view->setUseFixedLayout(fixed);
958     if (!fixed)
959         view->setFixedLayoutSize(IntSize());
960 }
961
962 void WebPage::setFixedLayoutSize(const IntSize& size)
963 {
964     FrameView* view = mainFrameView();
965     if (!view)
966         return;
967
968     view->setFixedLayoutSize(size);
969     view->forceLayout();
970 }
971
972 void WebPage::setPaginationMode(uint32_t mode)
973 {
974     Page::Pagination pagination = m_page->pagination();
975     pagination.mode = static_cast<Page::Pagination::Mode>(mode);
976     m_page->setPagination(pagination);
977 }
978
979 void WebPage::setPageLength(double pageLength)
980 {
981     Page::Pagination pagination = m_page->pagination();
982     pagination.pageLength = pageLength;
983     m_page->setPagination(pagination);
984 }
985
986 void WebPage::setGapBetweenPages(double gap)
987 {
988     Page::Pagination pagination = m_page->pagination();
989     pagination.gap = gap;
990     m_page->setPagination(pagination);
991 }
992
993 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay)
994 {
995     bool shouldFadeIn = true;
996     
997     if (m_pageOverlay) {
998         m_pageOverlay->setPage(0);
999
1000         if (pageOverlay) {
1001             // We're installing a page overlay when a page overlay is already active.
1002             // In this case we don't want to fade in the new overlay.
1003             shouldFadeIn = false;
1004         }
1005     }
1006
1007     m_pageOverlay = pageOverlay;
1008     m_pageOverlay->setPage(this);
1009
1010     if (shouldFadeIn)
1011         m_pageOverlay->startFadeInAnimation();
1012
1013     m_drawingArea->didInstallPageOverlay();
1014 #if PLATFORM(WIN)
1015     send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(true));
1016 #endif
1017
1018     m_pageOverlay->setNeedsDisplay();
1019 }
1020
1021 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool fadeOut)
1022 {
1023     if (pageOverlay != m_pageOverlay)
1024         return;
1025
1026     if (fadeOut) {
1027         m_pageOverlay->startFadeOutAnimation();
1028         return;
1029     }
1030
1031     m_pageOverlay->setPage(0);
1032     m_pageOverlay = nullptr;
1033
1034     m_drawingArea->didUninstallPageOverlay();
1035 #if PLATFORM(WIN)
1036     send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(false));
1037 #endif
1038 }
1039
1040 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
1041 {
1042     FrameView* frameView = m_mainFrame->coreFrame()->view();
1043     if (!frameView)
1044         return 0;
1045
1046     IntSize bitmapSize = rect.size();
1047     float deviceScaleFactor = corePage()->deviceScaleFactor();
1048     bitmapSize.scale(deviceScaleFactor);
1049
1050     RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, options);
1051     if (!snapshot->bitmap())
1052         return 0;
1053     
1054     OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1055     graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1056     graphicsContext->translate(-rect.x(), -rect.y());
1057
1058     frameView->updateLayoutAndStyleIfNeededRecursive();
1059
1060     PaintBehavior oldBehavior = frameView->paintBehavior();
1061     frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1062     frameView->paint(graphicsContext.get(), rect);
1063     frameView->setPaintBehavior(oldBehavior);
1064
1065     return snapshot.release();
1066 }
1067
1068 PassRefPtr<WebImage> WebPage::scaledSnapshotInDocumentCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
1069 {
1070     FrameView* frameView = m_mainFrame->coreFrame()->view();
1071     if (!frameView)
1072         return 0;
1073
1074     float combinedScaleFactor = scaleFactor * corePage()->deviceScaleFactor();
1075     IntSize size(ceil(rect.width() * combinedScaleFactor), ceil(rect.height() * combinedScaleFactor));
1076     RefPtr<WebImage> snapshot = WebImage::create(size, options);
1077     if (!snapshot->bitmap())
1078         return 0;
1079
1080     OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1081     graphicsContext->applyDeviceScaleFactor(combinedScaleFactor);
1082     graphicsContext->translate(-rect.x(), -rect.y());
1083
1084     frameView->updateLayoutAndStyleIfNeededRecursive();
1085
1086     PaintBehavior oldBehavior = frameView->paintBehavior();
1087     frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1088     frameView->paintContents(graphicsContext.get(), rect);
1089     frameView->setPaintBehavior(oldBehavior);
1090
1091     return snapshot.release();
1092 }
1093
1094 PassRefPtr<WebImage> WebPage::snapshotInDocumentCoordinates(const IntRect& rect, ImageOptions options)
1095 {
1096     return scaledSnapshotInDocumentCoordinates(rect, 1, options);
1097 }
1098
1099 void WebPage::pageDidScroll()
1100 {
1101     // Hide the find indicator.
1102     m_findController.hideFindIndicator();
1103
1104     m_uiClient.pageDidScroll(this);
1105
1106     send(Messages::WebPageProxy::PageDidScroll());
1107 }
1108
1109 #if USE(TILED_BACKING_STORE)
1110 void WebPage::pageDidRequestScroll(const IntPoint& point)
1111 {
1112     send(Messages::WebPageProxy::PageDidRequestScroll(point));
1113 }
1114 #endif
1115
1116 WebContextMenu* WebPage::contextMenu()
1117 {
1118     if (!m_contextMenu)
1119         m_contextMenu = WebContextMenu::create(this);
1120     return m_contextMenu.get();
1121 }
1122
1123 // Events 
1124
1125 static const WebEvent* g_currentEvent = 0;
1126
1127 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1128 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1129 // platform events passed to the event handler code.
1130 const WebEvent* WebPage::currentEvent()
1131 {
1132     return g_currentEvent;
1133 }
1134
1135 class CurrentEvent {
1136 public:
1137     explicit CurrentEvent(const WebEvent& event)
1138         : m_previousCurrentEvent(g_currentEvent)
1139     {
1140         g_currentEvent = &event;
1141     }
1142
1143     ~CurrentEvent()
1144     {
1145         g_currentEvent = m_previousCurrentEvent;
1146     }
1147
1148 private:
1149     const WebEvent* m_previousCurrentEvent;
1150 };
1151
1152 static bool isContextClick(const PlatformMouseEvent& event)
1153 {
1154     if (event.button() == WebCore::RightButton)
1155         return true;
1156
1157 #if PLATFORM(MAC)
1158     // FIXME: this really should be about OSX-style UI, not about the Mac port
1159     if (event.button() == WebCore::LeftButton && event.ctrlKey())
1160         return true;
1161 #endif
1162
1163     return false;
1164 }
1165
1166 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, Page* page)
1167 {
1168     IntPoint point = page->mainFrame()->view()->windowToContents(platformMouseEvent.position());
1169     HitTestResult result = page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false);
1170
1171     Frame* frame = page->mainFrame();
1172     if (result.innerNonSharedNode())
1173         frame = result.innerNonSharedNode()->document()->frame();
1174     
1175     bool handled = frame->eventHandler()->sendContextMenuEvent(platformMouseEvent);
1176     if (handled)
1177         page->chrome()->showContextMenu();
1178
1179     return handled;
1180 }
1181
1182 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, Page* page, bool onlyUpdateScrollbars)
1183 {
1184     Frame* frame = page->mainFrame();
1185     if (!frame->view())
1186         return false;
1187
1188     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1189
1190     switch (platformMouseEvent.type()) {
1191         case PlatformEvent::MousePressed: {
1192             if (isContextClick(platformMouseEvent))
1193                 page->contextMenuController()->clearContextMenu();
1194             
1195             bool handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1196             if (isContextClick(platformMouseEvent))
1197                 handled = handleContextMenuEvent(platformMouseEvent, page);
1198
1199             return handled;
1200         }
1201         case PlatformEvent::MouseReleased:
1202             return frame->eventHandler()->handleMouseReleaseEvent(platformMouseEvent);
1203         case PlatformEvent::MouseMoved:
1204             return frame->eventHandler()->mouseMoved(platformMouseEvent, onlyUpdateScrollbars);
1205         default:
1206             ASSERT_NOT_REACHED();
1207             return false;
1208     }
1209 }
1210
1211 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1212 {
1213     // Don't try to handle any pending mouse events if a context menu is showing.
1214     if (m_isShowingContextMenu) {
1215         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1216         return;
1217     }
1218     
1219     bool handled = false;
1220     
1221     if (m_pageOverlay) {
1222         // Let the page overlay handle the event.
1223         handled = m_pageOverlay->mouseEvent(mouseEvent);
1224     }
1225
1226     if (!handled) {
1227         CurrentEvent currentEvent(mouseEvent);
1228
1229         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1230         // button is currently pressed. It is possible that neither of those things will be true since on 
1231         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one 
1232         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1233         // efficient scrollbars-only version of the event.
1234         bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1235         handled = handleMouseEvent(mouseEvent, m_page.get(), onlyUpdateScrollbars);
1236     }
1237
1238     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1239 }
1240
1241 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1242 {
1243     // Don't try to handle any pending mouse events if a context menu is showing.
1244     if (m_isShowingContextMenu) {
1245         handled = true;
1246         return;
1247     }
1248
1249     handled = m_pageOverlay && m_pageOverlay->mouseEvent(mouseEvent);
1250
1251     if (!handled) {
1252         CurrentEvent currentEvent(mouseEvent);
1253
1254         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1255         // button is currently pressed. It is possible that neither of those things will be true since on 
1256         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one 
1257         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1258         // efficient scrollbars-only version of the event.
1259         bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1260         handled = handleMouseEvent(mouseEvent, m_page.get(), onlyUpdateScrollbars);
1261     }
1262 }
1263
1264 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1265 {
1266     Frame* frame = page->mainFrame();
1267     if (!frame->view())
1268         return false;
1269
1270     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1271     return frame->eventHandler()->handleWheelEvent(platformWheelEvent);
1272 }
1273
1274 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1275 {
1276     CurrentEvent currentEvent(wheelEvent);
1277
1278     bool handled = handleWheelEvent(wheelEvent, m_page.get());
1279     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1280 }
1281
1282 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1283 {
1284     CurrentEvent currentEvent(wheelEvent);
1285
1286     handled = handleWheelEvent(wheelEvent, m_page.get());
1287 }
1288
1289 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1290 {
1291     if (!page->mainFrame()->view())
1292         return false;
1293
1294     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1295         return page->focusController()->focusedOrMainFrame()->eventHandler()->handleAccessKey(platform(keyboardEvent));
1296     return page->focusController()->focusedOrMainFrame()->eventHandler()->keyEvent(platform(keyboardEvent));
1297 }
1298
1299 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1300 {
1301     CurrentEvent currentEvent(keyboardEvent);
1302
1303     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
1304     // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1305     if (!handled)
1306         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1307
1308     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1309 }
1310
1311 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
1312 {
1313     CurrentEvent currentEvent(keyboardEvent);
1314
1315     handled = handleKeyEvent(keyboardEvent, m_page.get());
1316     if (!handled)
1317         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1318 }
1319
1320 #if ENABLE(GESTURE_EVENTS)
1321 static bool handleGestureEvent(const WebGestureEvent& gestureEvent, Page* page)
1322 {
1323     Frame* frame = page->mainFrame();
1324     if (!frame->view())
1325         return false;
1326
1327     PlatformGestureEvent platformGestureEvent = platform(gestureEvent);
1328     return frame->eventHandler()->handleGestureEvent(platformGestureEvent);
1329 }
1330
1331 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
1332 {
1333     CurrentEvent currentEvent(gestureEvent);
1334
1335     bool handled = handleGestureEvent(gestureEvent, m_page.get());
1336     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
1337 }
1338 #endif
1339
1340 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1341 {
1342     bool isEnabled = false;
1343     int32_t state = 0;
1344     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1345     if (frame) {
1346         Editor::Command command = frame->editor()->command(commandName);
1347         state = command.state();
1348         isEnabled = command.isSupported() && command.isEnabled();
1349     }
1350
1351     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1352 }
1353
1354 void WebPage::executeEditCommand(const String& commandName)
1355 {
1356     executeEditingCommand(commandName, String());
1357 }
1358
1359 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1360 {
1361     const BackForwardListItemVector& list = sessionState.list();
1362     size_t size = list.size();
1363     uint64_t currentItemID = 0;
1364     for (size_t i = 0; i < size; ++i) {
1365         WebBackForwardListItem* webItem = list[i].get();
1366         DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1367         
1368         RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1369         if (!item) {
1370             LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1371             return 0;
1372         }
1373         
1374         if (i == sessionState.currentIndex())
1375             currentItemID = webItem->itemID();
1376         
1377         WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1378     }    
1379     ASSERT(currentItemID);
1380     return currentItemID;
1381 }
1382
1383 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState, const SandboxExtension::Handle& sandboxExtensionHandle)
1384 {
1385     if (uint64_t currentItemID = restoreSession(sessionState))
1386         goToBackForwardItem(currentItemID, sandboxExtensionHandle);
1387 }
1388
1389 #if ENABLE(TOUCH_EVENTS)
1390 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1391 {
1392     Frame* frame = page->mainFrame();
1393     if (!frame->view())
1394         return false;
1395
1396     return frame->eventHandler()->handleTouchEvent(platform(touchEvent));
1397 }
1398
1399 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1400 {
1401     CurrentEvent currentEvent(touchEvent);
1402
1403     bool handled = handleTouchEvent(touchEvent, m_page.get());
1404
1405     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1406 }
1407
1408 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
1409 {
1410     CurrentEvent currentEvent(touchEvent);
1411     handled = handleTouchEvent(touchEvent, m_page.get());
1412 }
1413 #endif
1414
1415 void WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1416 {
1417     page->focusController()->focusedOrMainFrame()->eventHandler()->scrollRecursively(direction, granularity);
1418 }
1419
1420 void WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1421 {
1422     page->focusController()->focusedOrMainFrame()->eventHandler()->logicalScrollRecursively(direction, granularity);
1423 }
1424
1425 void WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1426 {
1427     scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1428 }
1429
1430 void WebPage::centerSelectionInVisibleArea()
1431 {
1432     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1433     if (!frame)
1434         return;
1435     
1436     frame->selection()->revealSelection(ScrollAlignment::alignCenterAlways);
1437     m_findController.showFindIndicatorInSelection();
1438 }
1439
1440 void WebPage::setActive(bool isActive)
1441 {
1442     m_page->focusController()->setActive(isActive);
1443
1444 #if PLATFORM(MAC)    
1445     // Tell all our plug-in views that the window focus changed.
1446     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1447         (*it)->setWindowIsFocused(isActive);
1448 #endif
1449 }
1450
1451 void WebPage::setDrawsBackground(bool drawsBackground)
1452 {
1453     if (m_drawsBackground == drawsBackground)
1454         return;
1455
1456     m_drawsBackground = drawsBackground;
1457
1458     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1459         if (FrameView* view = coreFrame->view())
1460             view->setTransparent(!drawsBackground);
1461     }
1462
1463     m_drawingArea->pageBackgroundTransparencyChanged();
1464     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1465 }
1466
1467 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
1468 {
1469     if (m_drawsTransparentBackground == drawsTransparentBackground)
1470         return;
1471
1472     m_drawsTransparentBackground = drawsTransparentBackground;
1473
1474     Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
1475     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1476         if (FrameView* view = coreFrame->view())
1477             view->setBaseBackgroundColor(backgroundColor);
1478     }
1479
1480     m_drawingArea->pageBackgroundTransparencyChanged();
1481     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1482 }
1483
1484 void WebPage::viewWillStartLiveResize()
1485 {
1486     if (!m_page)
1487         return;
1488
1489     // FIXME: This should propagate to all ScrollableAreas.
1490     if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1491         if (FrameView* view = frame->view())
1492             view->willStartLiveResize();
1493     }
1494 }
1495
1496 void WebPage::viewWillEndLiveResize()
1497 {
1498     if (!m_page)
1499         return;
1500
1501     // FIXME: This should propagate to all ScrollableAreas.
1502     if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1503         if (FrameView* view = frame->view())
1504             view->willEndLiveResize();
1505     }
1506 }
1507
1508 void WebPage::setFocused(bool isFocused)
1509 {
1510     m_page->focusController()->setFocused(isFocused);
1511 }
1512
1513 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
1514 {
1515     if (!m_page || !m_page->focusController())
1516         return;
1517
1518     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1519     frame->document()->setFocusedNode(0);
1520
1521     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
1522         PlatformKeyboardEvent platformEvent(platform(event));
1523         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
1524         m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame->document()->defaultView()).get());
1525         return;
1526     }
1527
1528     m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
1529 }
1530
1531 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
1532 {
1533     if (m_windowResizerSize == windowResizerSize)
1534         return;
1535
1536     m_windowResizerSize = windowResizerSize;
1537
1538     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1539         FrameView* view = coreFrame->view();
1540         if (view)
1541             view->windowResizerRectChanged();
1542     }
1543 }
1544
1545 void WebPage::setCanStartMediaTimerFired()
1546 {
1547     if (m_page)
1548         m_page->setCanStartMedia(true);
1549 }
1550
1551 void WebPage::setIsInWindow(bool isInWindow)
1552 {
1553     if (!isInWindow) {
1554         m_setCanStartMediaTimer.stop();
1555         m_page->setCanStartMedia(false);
1556         m_page->willMoveOffscreen();
1557     } else {
1558         // Defer the call to Page::setCanStartMedia() since it ends up sending a syncrhonous messages to the UI process
1559         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
1560         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
1561         m_setCanStartMediaTimer.startOneShot(0);
1562         m_page->didMoveOnscreen();
1563     }
1564 }
1565
1566 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
1567 {
1568     WebFrame* frame = WebProcess::shared().webFrame(frameID);
1569     if (!frame)
1570         return;
1571     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
1572 }
1573
1574 void WebPage::show()
1575 {
1576     send(Messages::WebPageProxy::ShowPage());
1577 }
1578
1579 void WebPage::setUserAgent(const String& userAgent)
1580 {
1581     m_userAgent = userAgent;
1582 }
1583   
1584 IntPoint WebPage::screenToWindow(const IntPoint& point)
1585 {
1586     IntPoint windowPoint;
1587     sendSync(Messages::WebPageProxy::ScreenToWindow(point), Messages::WebPageProxy::ScreenToWindow::Reply(windowPoint));
1588     return windowPoint;
1589 }
1590     
1591 IntRect WebPage::windowToScreen(const IntRect& rect)
1592 {
1593     IntRect screenRect;
1594     sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
1595     return screenRect;
1596 }
1597
1598 IntRect WebPage::windowResizerRect() const
1599 {
1600     if (m_windowResizerSize.isEmpty())
1601         return IntRect();
1602
1603     IntSize frameViewSize;
1604     if (Frame* coreFrame = m_mainFrame->coreFrame()) {
1605         if (FrameView* view = coreFrame->view())
1606             frameViewSize = view->size();
1607     }
1608
1609     return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(), 
1610                    m_windowResizerSize.width(), m_windowResizerSize.height());
1611 }
1612
1613 KeyboardUIMode WebPage::keyboardUIMode()
1614 {
1615     bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
1616     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
1617 }
1618
1619 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
1620 {
1621     // NOTE: We need to be careful when running scripts that the objects we depend on don't
1622     // disappear during script execution.
1623
1624     // Retain the SerializedScriptValue at this level so it (and the internal data) lives
1625     // long enough for the DataReference to be encoded by the sent message.
1626     RefPtr<SerializedScriptValue> serializedResultValue;
1627     CoreIPC::DataReference dataReference;
1628
1629     JSLock lock(SilenceAssertionsOnly);
1630     if (JSValue resultValue = m_mainFrame->coreFrame()->script()->executeScript(script, true).jsValue()) {
1631         if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script()->globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
1632             dataReference = serializedResultValue->data();
1633     }
1634
1635     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
1636 }
1637
1638 void WebPage::getContentsAsString(uint64_t callbackID)
1639 {
1640     String resultString = m_mainFrame->contentsAsString();
1641     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1642 }
1643
1644 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
1645 {
1646     String resultString = renderTreeExternalRepresentation();
1647     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1648 }
1649
1650 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
1651 {
1652     String resultString = m_mainFrame->selectionAsString();
1653     if (resultString.isEmpty())
1654         resultString = m_mainFrame->contentsAsString();
1655     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1656 }
1657
1658 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
1659 {
1660     String resultString;
1661     if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
1662        resultString = frame->source();
1663
1664     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1665 }
1666
1667 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
1668 {
1669     CoreIPC::DataReference dataReference;
1670
1671     RefPtr<SharedBuffer> buffer;
1672     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1673         if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
1674             if ((buffer = loader->mainResourceData()))
1675                 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1676         }
1677     }
1678
1679     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1680 }
1681
1682 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const KURL& resourceURL)
1683 {
1684     DocumentLoader* loader = frame->loader()->documentLoader();
1685     if (!loader)
1686         return 0;
1687
1688     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
1689     if (!subresource)
1690         return 0;
1691
1692     return subresource->data();
1693 }
1694
1695 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
1696 {
1697     CoreIPC::DataReference dataReference;
1698     KURL resourceURL(KURL(), resourceURLString);
1699
1700     RefPtr<SharedBuffer> buffer;
1701     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1702         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
1703         if (!buffer) {
1704             // Try to get the resource data from the cache.
1705             buffer = cachedResponseDataForURL(resourceURL);
1706         }
1707
1708         if (buffer)
1709             dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1710     }
1711
1712     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1713 }
1714
1715 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
1716 {
1717     CoreIPC::DataReference dataReference;
1718
1719 #if PLATFORM(MAC) || PLATFORM(WIN)
1720     RetainPtr<CFDataRef> data;
1721     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1722         if ((data = frame->webArchiveData()))
1723             dataReference = CoreIPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
1724     }
1725 #endif
1726
1727     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1728 }
1729
1730 void WebPage::forceRepaintWithoutCallback()
1731 {
1732     m_drawingArea->forceRepaint();
1733 }
1734
1735 void WebPage::forceRepaint(uint64_t callbackID)
1736 {
1737     forceRepaintWithoutCallback();
1738     send(Messages::WebPageProxy::VoidCallback(callbackID));
1739 }
1740
1741 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
1742 {
1743     WebPreferencesStore::removeTestRunnerOverrides();
1744     updatePreferences(store);
1745 }
1746
1747 void WebPage::updatePreferences(const WebPreferencesStore& store)
1748 {
1749     Settings* settings = m_page->settings();
1750
1751     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
1752
1753     // FIXME: This should be generated from macro expansion for all preferences,
1754     // but we currently don't match the naming of WebCore exactly so we are
1755     // handrolling the boolean and integer preferences until that is fixed.
1756
1757 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
1758
1759     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
1760
1761 #undef INITIALIZE_SETTINGS
1762
1763     settings->setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
1764     settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
1765     settings->setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
1766     settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
1767     settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
1768     settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
1769     settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
1770     settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
1771     settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
1772     settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
1773     settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
1774     settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
1775     settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
1776     settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
1777     settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
1778     settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
1779 #if ENABLE(WEB_ARCHIVE)
1780     settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
1781 #endif
1782     settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
1783     settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
1784     settings->setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
1785     settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
1786     settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
1787     settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
1788     settings->setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
1789     settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
1790     settings->setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
1791     settings->setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
1792     settings->setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
1793
1794     settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
1795     settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
1796     settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
1797     settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
1798     settings->setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
1799     settings->setDeviceDPI(store.getUInt32ValueForKey(WebPreferencesKey::deviceDPIKey()));
1800     settings->setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
1801     settings->setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
1802     settings->setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
1803     settings->setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
1804
1805     settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1806     settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1807     settings->setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1808     settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
1809     settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
1810     settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
1811     settings->setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
1812     settings->setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
1813     settings->setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
1814
1815 #if ENABLE(SQL_DATABASE)
1816     AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
1817 #endif
1818
1819 #if ENABLE(FULLSCREEN_API)
1820     settings->setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
1821 #endif
1822
1823     settings->setLocalStorageDatabasePath(WebProcess::shared().localStorageDirectory());
1824
1825 #if USE(AVFOUNDATION)
1826     settings->setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
1827 #endif
1828
1829 #if ENABLE(WEB_SOCKETS)
1830     settings->setUseHixie76WebSocketProtocol(store.getBoolValueForKey(WebPreferencesKey::hixie76WebSocketProtocolEnabledKey()));
1831 #endif
1832
1833 #if ENABLE(WEB_AUDIO)
1834     settings->setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
1835 #endif
1836
1837     settings->setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));    
1838     settings->setSuppressIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressIncrementalRenderingKey()));
1839     settings->setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
1840     settings->setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
1841
1842 #if ENABLE(VIDEO_TRACK)
1843     settings->setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
1844     settings->setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
1845     settings->setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
1846 #endif
1847
1848     platformPreferencesDidChange(store);
1849 }
1850
1851 #if ENABLE(INSPECTOR)
1852 WebInspector* WebPage::inspector()
1853 {
1854     if (m_isClosed)
1855         return 0;
1856     if (!m_inspector)
1857         m_inspector = WebInspector::create(this);
1858     return m_inspector.get();
1859 }
1860 #endif
1861
1862 #if ENABLE(FULLSCREEN_API)
1863 WebFullScreenManager* WebPage::fullScreenManager()
1864 {
1865     if (!m_fullScreenManager)
1866         m_fullScreenManager = WebFullScreenManager::create(this);
1867     return m_fullScreenManager.get();
1868 }
1869 #endif
1870
1871 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
1872 {
1873     if (m_notificationPermissionRequestManager)
1874         return m_notificationPermissionRequestManager.get();
1875
1876     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
1877     return m_notificationPermissionRequestManager.get();
1878 }
1879
1880 #if !PLATFORM(GTK) && !PLATFORM(MAC)
1881 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
1882 {
1883     Node* node = evt->target()->toNode();
1884     ASSERT(node);
1885     Frame* frame = node->document()->frame();
1886     ASSERT(frame);
1887
1888     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1889     if (!keyEvent)
1890         return false;
1891
1892     Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1893
1894     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
1895         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1896         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1897         // (e.g. Tab that inserts a Tab character, or Enter).
1898         return !command.isTextInsertion() && command.execute(evt);
1899     }
1900
1901     if (command.execute(evt))
1902         return true;
1903
1904     // Don't insert null or control characters as they can result in unexpected behaviour
1905     if (evt->charCode() < ' ')
1906         return false;
1907
1908     return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1909 }
1910 #endif
1911
1912 #if PLATFORM(WIN)
1913 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const WebCore::DragDataMap& dataMap, uint32_t flags)
1914 {
1915     if (!m_page) {
1916         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
1917         return;
1918     }
1919
1920     DragData dragData(dataMap, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
1921     switch (action) {
1922     case DragControllerActionEntered:
1923         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1924         break;
1925
1926     case DragControllerActionUpdated:
1927         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
1928         break;
1929         
1930     case DragControllerActionExited:
1931         m_page->dragController()->dragExited(&dragData);
1932         break;
1933         
1934     case DragControllerActionPerformDrag:
1935         m_page->dragController()->performDrag(&dragData);
1936         break;
1937         
1938     default:
1939         ASSERT_NOT_REACHED();
1940     }
1941 }
1942
1943 #elif PLATFORM(QT) || PLATFORM(GTK)
1944 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
1945 {
1946     if (!m_page) {
1947         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
1948 #if PLATFORM(QT)
1949         QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
1950 #elif PLATFORM(GTK)
1951         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
1952 #endif
1953         delete data;
1954         return;
1955     }
1956
1957     switch (action) {
1958     case DragControllerActionEntered:
1959         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1960         break;
1961
1962     case DragControllerActionUpdated:
1963         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
1964         break;
1965
1966     case DragControllerActionExited:
1967         m_page->dragController()->dragExited(&dragData);
1968         break;
1969
1970     case DragControllerActionPerformDrag: {
1971         m_page->dragController()->performDrag(&dragData);
1972         break;
1973     }
1974
1975     default:
1976         ASSERT_NOT_REACHED();
1977     }
1978     // DragData does not delete its platformData so we need to do that here.
1979 #if PLATFORM(QT)
1980     QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
1981 #elif PLATFORM(GTK)
1982     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
1983 #endif
1984     delete data;
1985 }
1986
1987 #else
1988 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const String& dragStorageName, uint32_t flags, const SandboxExtension::Handle& sandboxExtensionHandle)
1989 {
1990     if (!m_page) {
1991         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
1992         return;
1993     }
1994
1995     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
1996     switch (action) {
1997     case DragControllerActionEntered:
1998         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1999         break;
2000
2001     case DragControllerActionUpdated:
2002         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2003         break;
2004         
2005     case DragControllerActionExited:
2006         m_page->dragController()->dragExited(&dragData);
2007         break;
2008         
2009     case DragControllerActionPerformDrag: {
2010         ASSERT(!m_pendingDropSandboxExtension);
2011
2012         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2013
2014         m_page->dragController()->performDrag(&dragData);
2015
2016         // If we started loading a local file, the sandbox extension tracker would have adopted this
2017         // pending drop sandbox extension. If not, we'll play it safe and invalidate it.
2018         if (m_pendingDropSandboxExtension) {
2019             m_pendingDropSandboxExtension->invalidate();
2020             m_pendingDropSandboxExtension = nullptr;
2021         }
2022
2023         break;
2024     }
2025
2026     default:
2027         ASSERT_NOT_REACHED();
2028     }
2029 }
2030 #endif
2031
2032 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2033 {
2034     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
2035     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
2036
2037     m_page->dragController()->dragEnded();
2038     FrameView* view = m_page->mainFrame()->view();
2039     if (!view)
2040         return;
2041     // FIXME: These are fake modifier keys here, but they should be real ones instead.
2042     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2043     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
2044 }
2045
2046 void WebPage::willPerformLoadDragDestinationAction()
2047 {
2048     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2049 }
2050
2051 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2052 {
2053     return m_undoStepMap.get(stepID).get();
2054 }
2055
2056 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2057 {
2058     m_undoStepMap.set(stepID, entry);
2059 }
2060
2061 void WebPage::removeWebEditCommand(uint64_t stepID)
2062 {
2063     m_undoStepMap.remove(stepID);
2064 }
2065
2066 void WebPage::unapplyEditCommand(uint64_t stepID)
2067 {
2068     WebUndoStep* step = webUndoStep(stepID);
2069     if (!step)
2070         return;
2071
2072     step->step()->unapply();
2073 }
2074
2075 void WebPage::reapplyEditCommand(uint64_t stepID)
2076 {
2077     WebUndoStep* step = webUndoStep(stepID);
2078     if (!step)
2079         return;
2080
2081     m_isInRedo = true;
2082     step->step()->reapply();
2083     m_isInRedo = false;
2084 }
2085
2086 void WebPage::didRemoveEditCommand(uint64_t commandID)
2087 {
2088     removeWebEditCommand(commandID);
2089 }
2090
2091 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2092 {
2093     m_activePopupMenu = menu;
2094 }
2095
2096 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2097 {
2098     m_activeOpenPanelResultListener = openPanelResultListener;
2099 }
2100
2101 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2102 {
2103     return m_page->findString(target, options);
2104 }
2105
2106 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2107 {
2108     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2109 }
2110
2111 void WebPage::hideFindUI()
2112 {
2113     m_findController.hideFindUI();
2114 }
2115
2116 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2117 {
2118     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2119 }
2120
2121 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2122 {
2123     if (!m_activePopupMenu)
2124         return;
2125
2126     m_activePopupMenu->didChangeSelectedIndex(newIndex);
2127     m_activePopupMenu = 0;
2128 }
2129
2130 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
2131 {
2132     if (!m_activeOpenPanelResultListener)
2133         return;
2134
2135     m_activeOpenPanelResultListener->didChooseFiles(files);
2136     m_activeOpenPanelResultListener = 0;
2137 }
2138
2139 void WebPage::didCancelForOpenPanel()
2140 {
2141     m_activeOpenPanelResultListener = 0;
2142 }
2143
2144 #if ENABLE(WEB_PROCESS_SANDBOX)
2145 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
2146 {
2147     SandboxExtension::create(handle)->consumePermanently();
2148 }
2149 #endif
2150
2151 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
2152 {
2153     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
2154 }
2155
2156 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
2157 {
2158     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
2159 }
2160
2161 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
2162 {
2163     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2164     frame->editor()->advanceToNextMisspelling(startBeforeSelection);
2165 }
2166
2167 void WebPage::changeSpellingToWord(const String& word)
2168 {
2169     replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
2170 }
2171
2172 void WebPage::unmarkAllMisspellings()
2173 {
2174     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2175         if (Document* document = frame->document())
2176             document->markers()->removeMarkers(DocumentMarker::Spelling);
2177     }
2178 }
2179
2180 void WebPage::unmarkAllBadGrammar()
2181 {
2182     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2183         if (Document* document = frame->document())
2184             document->markers()->removeMarkers(DocumentMarker::Grammar);
2185     }
2186 }
2187
2188 #if PLATFORM(MAC)
2189 void WebPage::uppercaseWord()
2190 {
2191     m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
2192 }
2193
2194 void WebPage::lowercaseWord()
2195 {
2196     m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
2197 }
2198
2199 void WebPage::capitalizeWord()
2200 {
2201     m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
2202 }
2203 #endif
2204     
2205 void WebPage::setTextForActivePopupMenu(int32_t index)
2206 {
2207     if (!m_activePopupMenu)
2208         return;
2209
2210     m_activePopupMenu->setTextForIndex(index);
2211 }
2212
2213 #if PLATFORM(GTK)
2214 void WebPage::failedToShowPopupMenu()
2215 {
2216     if (!m_activePopupMenu)
2217         return;
2218
2219     m_activePopupMenu->client()->popupDidHide();
2220 }
2221 #endif
2222
2223 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
2224 {
2225     if (!m_contextMenu)
2226         return;
2227
2228     m_contextMenu->itemSelected(item);
2229     m_contextMenu = 0;
2230 }
2231
2232 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
2233 {
2234     bool selectReplacement = true;
2235     bool smartReplace = false;
2236     return frame->editor()->replaceSelectionWithText(text, selectReplacement, smartReplace);
2237 }
2238
2239 void WebPage::clearSelection()
2240 {
2241     m_page->focusController()->focusedOrMainFrame()->selection()->clear();
2242 }
2243
2244 bool WebPage::mainFrameHasCustomRepresentation() const
2245 {
2246     if (Frame* frame = mainFrame())
2247         return static_cast<WebFrameLoaderClient*>(frame->loader()->client())->frameHasCustomRepresentation();
2248
2249     return false;
2250 }
2251
2252 void WebPage::didChangeScrollOffsetForMainFrame()
2253 {
2254     Frame* frame = m_page->mainFrame();
2255     IntPoint scrollPosition = frame->view()->scrollPosition();
2256     IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
2257     IntPoint minimumScrollPosition = frame->view()->minimumScrollPosition();
2258
2259     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
2260     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
2261
2262     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide) {
2263         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide));
2264         
2265         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
2266         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
2267     }
2268 }
2269
2270 void WebPage::mainFrameDidLayout()
2271 {
2272     unsigned pageCount = m_page->pageCount();
2273     if (pageCount != m_cachedPageCount) {
2274         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
2275         m_cachedPageCount = pageCount;
2276     }
2277 }
2278
2279 #if PLATFORM(MAC)
2280
2281 void WebPage::addPluginView(PluginView* pluginView)
2282 {
2283     ASSERT(!m_pluginViews.contains(pluginView));
2284
2285     m_pluginViews.add(pluginView);
2286 }
2287
2288 void WebPage::removePluginView(PluginView* pluginView)
2289 {
2290     ASSERT(m_pluginViews.contains(pluginView));
2291
2292     m_pluginViews.remove(pluginView);
2293 }
2294
2295 void WebPage::setWindowIsVisible(bool windowIsVisible)
2296 {
2297     m_windowIsVisible = windowIsVisible;
2298
2299     // Tell all our plug-in views that the window visibility changed.
2300     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
2301         (*it)->setWindowIsVisible(windowIsVisible);
2302 }
2303
2304 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
2305 {
2306     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
2307     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
2308     m_accessibilityPosition = accessibilityViewCoordinates;
2309     
2310     // Tell all our plug-in views that the window and view frames have changed.
2311     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
2312         (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
2313 }
2314
2315 #endif
2316
2317 bool WebPage::windowIsFocused() const
2318 {
2319 #if PLATFORM(MAC)
2320     if (!m_windowIsVisible)
2321         return false;
2322 #endif
2323     return m_page->focusController()->isFocused() && m_page->focusController()->isActive();
2324 }    
2325
2326 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
2327 {
2328     if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
2329         if (m_drawingArea)
2330             m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
2331         return;
2332     }
2333
2334 #if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING)
2335     if (messageID.is<CoreIPC::MessageClassLayerTreeHost>()) {
2336         if (m_drawingArea)
2337             m_drawingArea->didReceiveLayerTreeHostMessage(connection, messageID, arguments);
2338         return;
2339     }
2340 #endif
2341     
2342 #if ENABLE(INSPECTOR)
2343     if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
2344         if (WebInspector* inspector = this->inspector())
2345             inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
2346         return;
2347     }
2348 #endif
2349
2350 #if ENABLE(FULLSCREEN_API)
2351     if (messageID.is<CoreIPC::MessageClassWebFullScreenManager>()) {
2352         fullScreenManager()->didReceiveMessage(connection, messageID, arguments);
2353         return;
2354     }
2355 #endif
2356
2357     didReceiveWebPageMessage(connection, messageID, arguments);
2358 }
2359
2360 void WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, OwnPtr<CoreIPC::ArgumentEncoder>& reply)
2361 {   
2362     didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
2363 }
2364     
2365 InjectedBundleBackForwardList* WebPage::backForwardList()
2366 {
2367     if (!m_backForwardList)
2368         m_backForwardList = InjectedBundleBackForwardList::create(this);
2369     return m_backForwardList.get();
2370 }
2371
2372 #if PLATFORM(QT)
2373 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point)
2374 {
2375     Frame* mainframe = m_mainFrame->coreFrame();
2376     HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
2377
2378     Node* node = result.innerNode();
2379
2380     if (!node)
2381         return;
2382
2383     IntRect zoomableArea = node->getRect();
2384
2385     while (true) {
2386         bool found = !node->isTextNode() && !node->isShadowRoot();
2387
2388         // No candidate found, bail out.
2389         if (!found && !node->parentNode())
2390             return;
2391
2392         // Candidate found, and it is a better candidate than its parent.
2393         // NB: A parent is considered a better candidate iff the node is
2394         // contained by it and it is the only child.
2395         if (found && (!node->parentNode() || node->parentNode()->childNodeCount() != 1))
2396             break;
2397
2398         node = node->parentNode();
2399         zoomableArea.unite(node->getRect());
2400     }
2401
2402     if (node->document() && node->document()->frame() && node->document()->frame()->view()) {
2403         const ScrollView* view = node->document()->frame()->view();
2404         zoomableArea = view->contentsToWindow(zoomableArea);
2405     }
2406
2407     send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
2408 }
2409 #endif
2410
2411 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
2412 {
2413     invalidate();
2414 }
2415
2416 void WebPage::SandboxExtensionTracker::invalidate()
2417 {
2418     if (m_pendingProvisionalSandboxExtension) {
2419         m_pendingProvisionalSandboxExtension->invalidate();
2420         m_pendingProvisionalSandboxExtension = 0;
2421     }
2422
2423     if (m_provisionalSandboxExtension) {
2424         m_provisionalSandboxExtension->invalidate();
2425         m_provisionalSandboxExtension = 0;
2426     }
2427
2428     if (m_committedSandboxExtension) {
2429         m_committedSandboxExtension->invalidate();
2430         m_committedSandboxExtension = 0;
2431     }
2432 }
2433
2434 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
2435 {
2436     setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
2437 }
2438
2439 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
2440 {
2441     ASSERT(frame->isMainFrame());
2442
2443     setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
2444 }
2445
2446 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
2447 {
2448     // If we get two beginLoad calls in succession, without a provisional load starting, then
2449     // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
2450     if (m_pendingProvisionalSandboxExtension) {
2451         m_pendingProvisionalSandboxExtension->invalidate();
2452         m_pendingProvisionalSandboxExtension = nullptr;
2453     }
2454     
2455     m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;    
2456 }
2457
2458 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
2459 {
2460     ASSERT(frame->isMainFrame());
2461
2462     FrameLoader* frameLoader = frame->coreFrame()->loader();
2463     FrameLoadType frameLoadType = frameLoader->loadType();
2464
2465     // If the page is being reloaded, it should reuse whatever extension is committed.
2466     if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
2467         return true;
2468
2469     DocumentLoader* documentLoader = frameLoader->documentLoader();
2470     DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
2471     if (!documentLoader || !provisionalDocumentLoader)
2472         return false;
2473
2474     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
2475         return true;
2476
2477     return false;
2478 }
2479
2480 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
2481 {
2482     if (!frame->isMainFrame())
2483         return;
2484
2485     // We should only reuse the commited sandbox extension if it is not null. It can be
2486     // null if the last load was for an error page.
2487     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame)) {
2488         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
2489         ASSERT(!m_committedSandboxExtension);
2490     }
2491
2492     ASSERT(!m_provisionalSandboxExtension);
2493
2494     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
2495     if (!m_provisionalSandboxExtension)
2496         return;
2497
2498     m_provisionalSandboxExtension->consume();
2499 }
2500
2501 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
2502 {
2503     if (!frame->isMainFrame())
2504         return;
2505     
2506     ASSERT(!m_pendingProvisionalSandboxExtension);
2507
2508     // The provisional load has been committed. Invalidate the currently committed sandbox
2509     // extension and make the provisional sandbox extension the committed sandbox extension.
2510     if (m_committedSandboxExtension)
2511         m_committedSandboxExtension->invalidate();
2512
2513     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
2514 }
2515
2516 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
2517 {
2518     if (!frame->isMainFrame())
2519         return;
2520
2521     if (!m_provisionalSandboxExtension)
2522         return;
2523
2524     m_provisionalSandboxExtension->invalidate();
2525     m_provisionalSandboxExtension = nullptr;
2526 }
2527
2528 bool WebPage::hasLocalDataForURL(const KURL& url)
2529 {
2530     if (url.isLocalFile())
2531         return true;
2532
2533     FrameLoader* frameLoader = m_page->mainFrame()->loader();
2534     DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
2535     if (documentLoader && documentLoader->subresource(url))
2536         return true;
2537
2538     return platformHasLocalDataForURL(url);
2539 }
2540
2541 void WebPage::setCustomTextEncodingName(const String& encoding)
2542 {
2543     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
2544 }
2545
2546 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
2547 {
2548     WebBackForwardListProxy::removeItem(itemID);
2549 }
2550
2551 #if PLATFORM(MAC)
2552
2553 bool WebPage::isSpeaking()
2554 {
2555     bool result;
2556     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
2557 }
2558
2559 void WebPage::speak(const String& string)
2560 {
2561     send(Messages::WebPageProxy::Speak(string));
2562 }
2563
2564 void WebPage::stopSpeaking()
2565 {
2566     send(Messages::WebPageProxy::StopSpeaking());
2567 }
2568
2569 #endif
2570
2571 #if USE(CG)
2572 static RetainPtr<CGPDFDocumentRef> pdfDocumentForPrintingFrame(Frame* coreFrame)
2573 {
2574     Document* document = coreFrame->document();
2575     if (!document)
2576         return 0;
2577
2578     if (!document->isPluginDocument())
2579         return 0;
2580
2581     PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
2582     if (!pluginView)
2583         return 0;
2584
2585     return pluginView->pdfDocumentForPrinting();
2586 }
2587 #endif // USE(CG)
2588
2589 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
2590 {
2591     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2592     if (!frame)
2593         return;
2594
2595     Frame* coreFrame = frame->coreFrame();
2596     if (!coreFrame)
2597         return;
2598
2599 #if USE(CG)
2600     if (pdfDocumentForPrintingFrame(coreFrame))
2601         return;
2602 #endif // USE(CG)
2603
2604     if (!m_printContext)
2605         m_printContext = adoptPtr(new PrintContext(coreFrame));
2606
2607     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
2608
2609     float fullPageHeight;
2610     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
2611 }
2612
2613 void WebPage::endPrinting()
2614 {
2615     m_printContext = nullptr;
2616 }
2617
2618 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
2619 {
2620     Vector<IntRect> resultPageRects;
2621     double resultTotalScaleFactorForPrinting = 1;
2622
2623     beginPrinting(frameID, printInfo);
2624
2625     if (m_printContext) {
2626         resultPageRects = m_printContext->pageRects();
2627         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
2628     }
2629 #if USE(CG)
2630     else {
2631         WebFrame* frame = WebProcess::shared().webFrame(frameID);
2632         Frame* coreFrame = frame ? frame->coreFrame() : 0;
2633         RetainPtr<CGPDFDocumentRef> pdfDocument = coreFrame ? pdfDocumentForPrintingFrame(coreFrame) : 0;
2634         if (pdfDocument && CGPDFDocumentAllowsPrinting(pdfDocument.get())) {
2635             CFIndex pageCount = CGPDFDocumentGetNumberOfPages(pdfDocument.get());
2636             IntRect pageRect(0, 0, ceilf(printInfo.availablePaperWidth), ceilf(printInfo.availablePaperHeight));
2637             for (CFIndex i = 1; i <= pageCount; ++i) {
2638                 resultPageRects.append(pageRect);
2639                 pageRect.move(0, pageRect.height());
2640             }
2641         }
2642     }
2643 #endif // USE(CG)
2644
2645     // If we're asked to print, we should actually print at least a blank page.
2646     if (resultPageRects.isEmpty())
2647         resultPageRects.append(IntRect(0, 0, 1, 1));
2648
2649     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
2650 }
2651
2652 #if USE(CG)
2653 static inline CGFloat roundCGFloat(CGFloat f)
2654 {
2655     if (sizeof(CGFloat) == sizeof(float))
2656         return roundf(static_cast<float>(f));
2657     return static_cast<CGFloat>(round(f));
2658 }
2659
2660 static void drawPDFPage(CGPDFDocumentRef pdfDocument, CFIndex pageIndex, CGContextRef context, CGFloat pageSetupScaleFactor, CGSize paperSize)
2661 {
2662     CGContextSaveGState(context);
2663
2664     CGContextScaleCTM(context, pageSetupScaleFactor, pageSetupScaleFactor);
2665
2666     CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocument, pageIndex + 1);
2667     CGRect cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
2668     if (CGRectIsEmpty(cropBox))
2669         cropBox = CGRectIntersection(cropBox, CGPDFPageGetBoxRect(page, kCGPDFMediaBox));
2670     else
2671         cropBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
2672
2673     bool shouldRotate = (paperSize.width < paperSize.height) != (cropBox.size.width < cropBox.size.height);
2674     if (shouldRotate)
2675         swap(cropBox.size.width, cropBox.size.height);
2676
2677     // Center.
2678     CGFloat widthDifference = paperSize.width / pageSetupScaleFactor - cropBox.size.width;
2679     CGFloat heightDifference = paperSize.height / pageSetupScaleFactor - cropBox.size.height;
2680     if (widthDifference || heightDifference)
2681         CGContextTranslateCTM(context, roundCGFloat(widthDifference / 2), roundCGFloat(heightDifference / 2));
2682
2683     if (shouldRotate) {
2684         CGContextRotateCTM(context, static_cast<CGFloat>(piOverTwoDouble));
2685         CGContextTranslateCTM(context, 0, -cropBox.size.width);
2686     }
2687
2688     CGContextDrawPDFPage(context, page);
2689
2690     CGContextRestoreGState(context);
2691 }
2692 #endif // USE(CG)
2693
2694 #if PLATFORM(MAC) || PLATFORM(WIN)
2695 void WebPage::drawRectToPDF(uint64_t frameID, const PrintInfo& printInfo, const WebCore::IntRect& rect, uint64_t callbackID)
2696 {
2697     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2698     Frame* coreFrame = frame ? frame->coreFrame() : 0;
2699
2700     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2701
2702     if (coreFrame) {
2703 #if !USE(CG)
2704         UNUSED_PARAM(printInfo);
2705
2706         ASSERT(coreFrame->document()->printing());
2707 #else
2708         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
2709
2710         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2711         RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2712
2713         CGRect mediaBox = CGRectMake(0, 0, rect.width(), rect.height());
2714         RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2715         RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2716         CGPDFContextBeginPage(context.get(), pageInfo.get());
2717
2718         if (RetainPtr<CGPDFDocumentRef> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
2719             CFIndex pageCount = CGPDFDocumentGetNumberOfPages(pdfDocument.get());
2720             IntSize paperSize(ceilf(printInfo.availablePaperWidth), ceilf(printInfo.availablePaperHeight));
2721             IntRect pageRect(IntPoint(), paperSize);
2722             for (CFIndex i = 0; i < pageCount; ++i) {
2723                 if (pageRect.intersects(rect)) {
2724                     CGContextSaveGState(context.get());
2725
2726                     CGContextTranslateCTM(context.get(), pageRect.x() - rect.x(), pageRect.y() - rect.y());
2727                     drawPDFPage(pdfDocument.get(), i, context.get(), printInfo.pageSetupScaleFactor, paperSize);
2728
2729                     CGContextRestoreGState(context.get());
2730                 }
2731                 pageRect.move(0, pageRect.height());
2732             }
2733         } else {
2734             GraphicsContext ctx(context.get());
2735             ctx.scale(FloatSize(1, -1));
2736             ctx.translate(0, -rect.height());
2737             m_printContext->spoolRect(ctx, rect);
2738         }
2739
2740         CGPDFContextEndPage(context.get());
2741         CGPDFContextClose(context.get());
2742 #endif
2743     }
2744
2745     send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2746 }
2747
2748 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
2749 {
2750     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2751     Frame* coreFrame = frame ? frame->coreFrame() : 0;
2752
2753     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2754
2755     if (coreFrame) {
2756
2757 #if !USE(CG)
2758         ASSERT(coreFrame->document()->printing());
2759 #else
2760         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
2761
2762         RetainPtr<CGPDFDocumentRef> pdfDocument = pdfDocumentForPrintingFrame(coreFrame);
2763
2764         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2765         RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2766
2767         CGRect mediaBox = m_printContext && m_printContext->pageCount() ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
2768         RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2769         size_t pageCount = m_printContext ? m_printContext->pageCount() : CGPDFDocumentGetNumberOfPages(pdfDocument.get());
2770         for (uint32_t page = first; page < first + count; ++page) {
2771             if (page >= pageCount)
2772                 break;
2773
2774             RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2775             CGPDFContextBeginPage(context.get(), pageInfo.get());
2776
2777             if (pdfDocument)
2778                 drawPDFPage(pdfDocument.get(), page, context.get(), printInfo.pageSetupScaleFactor, CGSizeMake(printInfo.availablePaperWidth, printInfo.availablePaperHeight));
2779             else {
2780                 GraphicsContext ctx(context.get());
2781                 ctx.scale(FloatSize(1, -1));
2782                 ctx.translate(0, -m_printContext->pageRect(page).height());
2783                 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
2784             }
2785
2786             CGPDFContextEndPage(context.get());
2787         }
2788         CGPDFContextClose(context.get());
2789 #endif
2790     }
2791
2792     send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2793 }
2794 #endif
2795
2796 void WebPage::runModal()
2797 {
2798     if (m_isClosed)
2799         return;
2800     if (m_isRunningModal)
2801         return;
2802
2803     m_isRunningModal = true;
2804     send(Messages::WebPageProxy::RunModal());
2805     RunLoop::run();
2806     ASSERT(!m_isRunningModal);
2807 }
2808
2809 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
2810 {
2811     m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
2812 }
2813
2814 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
2815 {
2816     if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
2817         return true;
2818     return platformCanHandleRequest(request);
2819 }
2820
2821 #if PLATFORM(MAC) && !defined(BUILDING_ON_SNOW_LEOPARD)
2822 void WebPage::handleCorrectionPanelResult(const String& result)
2823 {
2824     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2825     if (!frame)
2826         return;
2827     frame->editor()->handleCorrectionPanelResult(result);
2828 }
2829 #endif
2830
2831 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
2832 {
2833     mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
2834 }
2835
2836 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
2837 {
2838     mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
2839 }
2840
2841 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
2842 {
2843     mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
2844 }
2845
2846 String WebPage::viewportConfigurationAsText(int deviceDPI, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight)
2847 {
2848     ViewportArguments arguments = mainFrame()->document()->viewportArguments();
2849     ViewportAttributes attrs = WebCore::computeViewportAttributes(arguments, /* default layout width for non-mobile pages */ 980, deviceWidth, deviceHeight, deviceDPI, IntSize(availableWidth, availableHeight));
2850     WebCore::restrictMinimumScaleFactorToViewportSize(attrs, IntSize(availableWidth, availableHeight));
2851     WebCore::restrictScaleFactorToInitialScaleIfNotUserScalable(attrs);
2852     return String::format("viewport size %dx%d scale %f with limits [%f, %f] and userScalable %f\n", attrs.layoutSize.width(), attrs.layoutSize.height(), attrs.initialScale, attrs.minimumScale, attrs.maximumScale, attrs.userScalable);
2853 }
2854
2855 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
2856 {
2857     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2858     if (!frame || !frame->editor()->canEdit())
2859         return;
2860
2861     Vector<CompositionUnderline> underlines;
2862     underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
2863     frame->editor()->setComposition(compositionString, underlines, from, from + length);
2864 }
2865
2866 bool WebPage::hasCompositionForTesting()
2867 {
2868     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2869     return frame && frame->editor()->hasComposition();
2870 }
2871
2872 void WebPage::confirmCompositionForTesting(const String& compositionString)
2873 {
2874     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2875     if (!frame || !frame->editor()->canEdit())
2876         return;
2877
2878     if (compositionString.isNull())
2879         frame->editor()->confirmComposition();
2880     frame->editor()->confirmComposition(compositionString);
2881 }
2882
2883 Frame* WebPage::mainFrame() const
2884 {
2885     return m_page ? m_page->mainFrame() : 0;
2886 }
2887
2888 FrameView* WebPage::mainFrameView() const
2889 {
2890     if (Frame* frame = mainFrame())
2891         return frame->view();
2892     
2893     return 0;
2894 }
2895
2896 } // namespace WebKit