Implement contentInset for Mac WebKit2
[WebKit-https.git] / Source / WebKit2 / WebProcess / WebPage / WebPage.cpp
1 /*
2  * Copyright (C) 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
3  * Copyright (C) 2012 Intel Corporation. All rights reserved.
4  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
16  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
19  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
25  * THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "config.h"
29 #include "WebPage.h"
30
31 #include "Arguments.h"
32 #include "DataReference.h"
33 #include "DecoderAdapter.h"
34 #include "DragControllerAction.h"
35 #include "DrawingArea.h"
36 #include "DrawingAreaMessages.h"
37 #include "EditingRange.h"
38 #include "EditorState.h"
39 #include "EventDispatcher.h"
40 #include "InjectedBundle.h"
41 #include "InjectedBundleBackForwardList.h"
42 #include "InjectedBundleUserMessageCoders.h"
43 #include "LayerTreeHost.h"
44 #include "Logging.h"
45 #include "NetscapePlugin.h"
46 #include "NotificationPermissionRequestManager.h"
47 #include "PageBanner.h"
48 #include "PageOverlay.h"
49 #include "PluginProcessAttributes.h"
50 #include "PluginProxy.h"
51 #include "PluginView.h"
52 #include "PrintInfo.h"
53 #include "SessionState.h"
54 #include "ShareableBitmap.h"
55 #include "VisitedLinkTableController.h"
56 #include "WKSharedAPICast.h"
57 #include "WebAlternativeTextClient.h"
58 #include "WebBackForwardListItem.h"
59 #include "WebBackForwardListProxy.h"
60 #include "WebChromeClient.h"
61 #include "WebColorChooser.h"
62 #include "WebContextMenu.h"
63 #include "WebContextMenuClient.h"
64 #include "WebContextMessages.h"
65 #include "WebCoreArgumentCoders.h"
66 #include "WebDocumentLoader.h"
67 #include "WebDragClient.h"
68 #include "WebEditorClient.h"
69 #include "WebEvent.h"
70 #include "WebEventConversion.h"
71 #include "WebFrame.h"
72 #include "WebFrameLoaderClient.h"
73 #include "WebFullScreenManager.h"
74 #include "WebFullScreenManagerMessages.h"
75 #include "WebGeolocationClient.h"
76 #include "WebImage.h"
77 #include "WebInspector.h"
78 #include "WebInspectorClient.h"
79 #include "WebInspectorMessages.h"
80 #include "WebNotificationClient.h"
81 #include "WebOpenPanelResultListener.h"
82 #include "WebPageCreationParameters.h"
83 #include "WebPageGroupProxy.h"
84 #include "WebPageMessages.h"
85 #include "WebPageProxyMessages.h"
86 #include "WebPlugInClient.h"
87 #include "WebPopupMenu.h"
88 #include "WebPreferencesStore.h"
89 #include "WebProcess.h"
90 #include "WebProcessProxyMessages.h"
91 #include "WebProgressTrackerClient.h"
92 #include <JavaScriptCore/APICast.h>
93 #include <WebCore/ArchiveResource.h>
94 #include <WebCore/Chrome.h>
95 #include <WebCore/ContextMenuController.h>
96 #include <WebCore/DatabaseManager.h>
97 #include <WebCore/DocumentFragment.h>
98 #include <WebCore/DocumentLoader.h>
99 #include <WebCore/DocumentMarkerController.h>
100 #include <WebCore/DragController.h>
101 #include <WebCore/DragData.h>
102 #include <WebCore/DragSession.h>
103 #include <WebCore/ElementIterator.h>
104 #include <WebCore/EventHandler.h>
105 #include <WebCore/FocusController.h>
106 #include <WebCore/FormState.h>
107 #include <WebCore/FrameLoadRequest.h>
108 #include <WebCore/FrameLoaderTypes.h>
109 #include <WebCore/FrameView.h>
110 #include <WebCore/HTMLFormElement.h>
111 #include <WebCore/HTMLInputElement.h>
112 #include <WebCore/HTMLPlugInElement.h>
113 #include <WebCore/HTMLPlugInImageElement.h>
114 #include <WebCore/HistoryController.h>
115 #include <WebCore/HistoryItem.h>
116 #include <WebCore/HitTestResult.h>
117 #include <WebCore/JSDOMWindow.h>
118 #include <WebCore/KeyboardEvent.h>
119 #include <WebCore/MIMETypeRegistry.h>
120 #include <WebCore/MainFrame.h>
121 #include <WebCore/MouseEvent.h>
122 #include <WebCore/Page.h>
123 #include <WebCore/PageThrottler.h>
124 #include <WebCore/PlatformKeyboardEvent.h>
125 #include <WebCore/PluginDocument.h>
126 #include <WebCore/PrintContext.h>
127 #include <WebCore/Range.h>
128 #include <WebCore/RenderLayer.h>
129 #include <WebCore/RenderTreeAsText.h>
130 #include <WebCore/RenderView.h>
131 #include <WebCore/ResourceBuffer.h>
132 #include <WebCore/ResourceRequest.h>
133 #include <WebCore/ResourceResponse.h>
134 #include <WebCore/RuntimeEnabledFeatures.h>
135 #include <WebCore/SchemeRegistry.h>
136 #include <WebCore/ScriptController.h>
137 #include <WebCore/SerializedScriptValue.h>
138 #include <WebCore/SessionID.h>
139 #include <WebCore/Settings.h>
140 #include <WebCore/ShadowRoot.h>
141 #include <WebCore/SharedBuffer.h>
142 #include <WebCore/SubframeLoader.h>
143 #include <WebCore/SubstituteData.h>
144 #include <WebCore/TextIterator.h>
145 #include <WebCore/UserInputBridge.h>
146 #include <WebCore/VisiblePosition.h>
147 #include <WebCore/VisibleUnits.h>
148 #include <WebCore/markup.h>
149 #include <bindings/ScriptValue.h>
150 #include <runtime/JSCInlines.h>
151 #include <runtime/JSCJSValue.h>
152 #include <runtime/JSLock.h>
153 #include <wtf/RunLoop.h>
154
155 #if ENABLE(MHTML)
156 #include <WebCore/MHTMLArchive.h>
157 #endif
158
159 #if ENABLE(BATTERY_STATUS)
160 #include "WebBatteryClient.h"
161 #endif
162
163 #if ENABLE(NETWORK_INFO)
164 #include "WebNetworkInfoClient.h"
165 #endif
166
167 #if ENABLE(VIBRATION)
168 #include "WebVibrationClient.h"
169 #endif
170
171 #if ENABLE(PROXIMITY_EVENTS)
172 #include "WebDeviceProximityClient.h"
173 #endif
174
175 #if PLATFORM(COCOA)
176 #include "PDFPlugin.h"
177 #include "RemoteLayerTreeTransaction.h"
178 #include <WebCore/LegacyWebArchive.h>
179 #endif
180
181 #if PLATFORM(GTK)
182 #include <gtk/gtk.h>
183 #include "DataObjectGtk.h"
184 #include "WebPrintOperationGtk.h"
185 #endif
186
187 #if PLATFORM(IOS)
188 #include "WebVideoFullscreenManager.h"
189 #endif
190
191 #ifndef NDEBUG
192 #include <wtf/RefCountedLeakCounter.h>
193 #endif
194
195 #if USE(COORDINATED_GRAPHICS)
196 #include "CoordinatedLayerTreeHostMessages.h"
197 #endif
198
199 using namespace JSC;
200 using namespace WebCore;
201
202 namespace WebKit {
203
204 class SendStopResponsivenessTimer {
205 public:
206     SendStopResponsivenessTimer(WebPage* page)
207         : m_page(page)
208     {
209     }
210     
211     ~SendStopResponsivenessTimer()
212     {
213         m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
214     }
215
216 private:
217     WebPage* m_page;
218 };
219
220 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
221
222 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
223 {
224     RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
225
226     if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
227         WebProcess::shared().injectedBundle()->didCreatePage(page.get());
228
229     return page.release();
230 }
231
232 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
233     : m_pageID(pageID)
234     , m_viewSize(parameters.viewSize)
235     , m_hasSeenPlugin(false)
236     , m_useFixedLayout(false)
237     , m_drawsBackground(true)
238     , m_drawsTransparentBackground(false)
239     , m_isInRedo(false)
240     , m_isClosed(false)
241     , m_tabToLinks(false)
242     , m_asynchronousPluginInitializationEnabled(false)
243     , m_asynchronousPluginInitializationEnabledForAllPlugins(false)
244     , m_artificialPluginInitializationDelayEnabled(false)
245     , m_scrollingPerformanceLoggingEnabled(false)
246     , m_mainFrameIsScrollable(true)
247 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
248     , m_readyToFindPrimarySnapshottedPlugin(false)
249     , m_didFindPrimarySnapshottedPlugin(false)
250     , m_numberOfPrimarySnapshotDetectionAttempts(0)
251     , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
252 #endif
253     , m_layerHostingMode(parameters.layerHostingMode)
254 #if PLATFORM(COCOA)
255     , m_pdfPluginEnabled(false)
256     , m_hasCachedWindowFrame(false)
257     , m_viewGestureGeometryCollector(*this)
258 #elif PLATFORM(GTK) && HAVE(ACCESSIBILITY)
259     , m_accessibilityObject(0)
260 #endif
261     , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
262     , m_sendDidUpdateViewStateTimer(RunLoop::main(), this, &WebPage::didUpdateViewStateTimerFired)
263     , m_findController(this)
264 #if ENABLE(INPUT_TYPE_COLOR)
265     , m_activeColorChooser(0)
266 #endif
267 #if ENABLE(GEOLOCATION)
268     , m_geolocationPermissionRequestManager(this)
269 #endif
270     , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
271     , m_canRunModal(parameters.canRunModal)
272     , m_isRunningModal(false)
273     , m_cachedMainFrameIsPinnedToLeftSide(false)
274     , m_cachedMainFrameIsPinnedToRightSide(false)
275     , m_cachedMainFrameIsPinnedToTopSide(false)
276     , m_cachedMainFrameIsPinnedToBottomSide(false)
277     , m_canShortCircuitHorizontalWheelEvents(false)
278     , m_numWheelEventHandlers(0)
279     , m_cachedPageCount(0)
280     , m_autoSizingShouldExpandToViewHeight(false)
281 #if ENABLE(CONTEXT_MENUS)
282     , m_isShowingContextMenu(false)
283 #endif
284 #if PLATFORM(IOS)
285     , m_shouldReturnWordAtSelection(false)
286     , m_lastVisibleContentRectUpdateID(0)
287     , m_scaleWasSetByUIProcess(false)
288     , m_userHasChangedPageScaleFactor(false)
289     , m_viewportScreenSize(parameters.viewportScreenSize)
290 #endif
291     , m_inspectorClient(0)
292     , m_backgroundColor(Color::white)
293     , m_maximumRenderingSuppressionToken(0)
294     , m_scrollPinningBehavior(DoNotPin)
295     , m_useAsyncScrolling(false)
296     , m_viewState(parameters.viewState)
297     , m_processSuppressionDisabledByWebPreference("Process suppression is disabled.")
298     , m_pendingNavigationID(0)
299     , m_pageScaleWithoutThumbnailScale(1)
300     , m_thumbnailScale(1)
301 #if ENABLE(WEBGL)
302     , m_systemWebGLPolicy(WebGLAllowCreation)
303 #endif
304 {
305     ASSERT(m_pageID);
306     // FIXME: This is a non-ideal location for this Setting and
307     // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
308     Settings::setDefaultMinDOMTimerInterval(0.004);
309
310     Page::PageClients pageClients;
311     pageClients.chromeClient = new WebChromeClient(this);
312 #if ENABLE(CONTEXT_MENUS)
313     pageClients.contextMenuClient = new WebContextMenuClient(this);
314 #endif
315     pageClients.editorClient = new WebEditorClient(this);
316 #if ENABLE(DRAG_SUPPORT)
317     pageClients.dragClient = new WebDragClient(this);
318 #endif
319     pageClients.backForwardClient = WebBackForwardListProxy::create(this);
320 #if ENABLE(INSPECTOR)
321     m_inspectorClient = new WebInspectorClient(this);
322     pageClients.inspectorClient = m_inspectorClient;
323 #endif
324 #if USE(AUTOCORRECTION_PANEL)
325     pageClients.alternativeTextClient = new WebAlternativeTextClient(this);
326 #endif
327     pageClients.plugInClient = new WebPlugInClient(this);
328     pageClients.loaderClientForMainFrame = new WebFrameLoaderClient;
329     pageClients.progressTrackerClient = new WebProgressTrackerClient(*this);
330
331     pageClients.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
332
333     m_page = adoptPtr(new Page(pageClients));
334
335     m_drawingArea = DrawingArea::create(this, parameters);
336     m_drawingArea->setPaintingEnabled(false);
337
338 #if ENABLE(ASYNC_SCROLLING)
339     m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
340     if (!m_drawingArea->supportsAsyncScrolling())
341         m_useAsyncScrolling = false;
342     m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
343 #endif
344
345     m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
346
347 #if ENABLE(BATTERY_STATUS)
348     WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
349 #endif
350 #if ENABLE(GEOLOCATION)
351     WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
352 #endif
353 #if ENABLE(NETWORK_INFO)
354     WebCore::provideNetworkInfoTo(m_page.get(), new WebNetworkInfoClient(this));
355 #endif
356 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
357     WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
358 #endif
359 #if ENABLE(VIBRATION)
360     WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
361 #endif
362 #if ENABLE(PROXIMITY_EVENTS)
363     WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this));
364 #endif
365
366 #if ENABLE(REMOTE_INSPECTOR)
367     m_page->setRemoteInspectionAllowed(true);
368 #endif
369
370     m_page->setCanStartMedia(false);
371     m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
372
373     m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
374     m_page->setGroupName(m_pageGroup->identifier());
375     m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
376
377     updatePreferences(parameters.store);
378     platformInitialize();
379
380     setUseFixedLayout(parameters.useFixedLayout);
381
382     setDrawsBackground(parameters.drawsBackground);
383     setDrawsTransparentBackground(parameters.drawsTransparentBackground);
384
385     setUnderlayColor(parameters.underlayColor);
386
387     setPaginationMode(parameters.paginationMode);
388     setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
389     setPageLength(parameters.pageLength);
390     setGapBetweenPages(parameters.gapBetweenPages);
391
392     setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
393
394     // If the page is created off-screen, its visibilityState should be prerender.
395     m_page->setViewState(m_viewState);
396     if (!isVisible())
397         m_page->setIsPrerender();
398
399     updateIsInWindow(true);
400
401     setMinimumLayoutSize(parameters.minimumLayoutSize);
402     setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
403     
404     setScrollPinningBehavior(parameters.scrollPinningBehavior);
405     setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
406
407     setTopContentInset(parameters.topContentInset);
408
409     m_userAgent = parameters.userAgent;
410
411     WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
412     
413     if (!parameters.sessionState.isEmpty())
414         restoreSession(parameters.sessionState);
415
416     m_drawingArea->setPaintingEnabled(true);
417     
418     setMediaVolume(parameters.mediaVolume);
419
420     // We use the DidFirstLayout milestone to determine when to unfreeze the layer tree.
421     m_page->addLayoutMilestones(DidFirstLayout);
422
423     WebProcess::shared().addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
424
425     // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
426     WebProcess::shared().addMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID, *this);
427 #if USE(COORDINATED_GRAPHICS)
428     WebProcess::shared().addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this);
429 #endif
430 #if ENABLE(INSPECTOR)
431     WebProcess::shared().addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
432 #endif
433 #if ENABLE(FULLSCREEN_API)
434     WebProcess::shared().addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
435 #endif
436
437 #ifndef NDEBUG
438     webPageCounter.increment();
439 #endif
440
441 #if ENABLE(ASYNC_SCROLLING)
442     if (m_useAsyncScrolling)
443         WebProcess::shared().eventDispatcher().addScrollingTreeForPage(this);
444 #endif
445 }
446
447 void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters)
448 {
449     if (m_viewState != parameters.viewState)
450         setViewState(parameters.viewState);
451     if (m_layerHostingMode != parameters.layerHostingMode)
452         setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode));
453 }
454
455 WebPage::~WebPage()
456 {
457     if (m_backForwardList)
458         m_backForwardList->detach();
459
460     ASSERT(!m_page);
461
462 #if ENABLE(ASYNC_SCROLLING)
463     if (m_useAsyncScrolling)
464         WebProcess::shared().eventDispatcher().removeScrollingTreeForPage(this);
465 #endif
466
467     m_sandboxExtensionTracker.invalidate();
468
469     for (auto* pluginView : m_pluginViews)
470         pluginView->webPageDestroyed();
471
472 #if !PLATFORM(IOS)
473     if (m_headerBanner)
474         m_headerBanner->detachFromPage();
475     if (m_footerBanner)
476         m_footerBanner->detachFromPage();
477 #endif // !PLATFORM(IOS)
478
479     WebProcess::shared().removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
480
481     // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
482     WebProcess::shared().removeMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID);
483 #if USE(COORDINATED_GRAPHICS)
484     WebProcess::shared().removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID);
485 #endif
486 #if ENABLE(INSPECTOR)
487     WebProcess::shared().removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
488 #endif
489 #if ENABLE(FULLSCREEN_API)
490     WebProcess::shared().removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
491 #endif
492
493 #ifndef NDEBUG
494     webPageCounter.decrement();
495 #endif
496 }
497
498 void WebPage::dummy(bool&)
499 {
500 }
501
502 IPC::Connection* WebPage::messageSenderConnection()
503 {
504     return WebProcess::shared().parentProcessConnection();
505 }
506
507 uint64_t WebPage::messageSenderDestinationID()
508 {
509     return pageID();
510 }
511
512 #if ENABLE(CONTEXT_MENUS)
513 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClientBase* client)
514 {
515     m_contextMenuClient.initialize(client);
516 }
517 #endif
518
519 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* client)
520 {
521     m_editorClient.initialize(client);
522 }
523
524 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClientBase* client)
525 {
526     m_formClient.initialize(client);
527 }
528
529 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client)
530 {
531     m_loaderClient.initialize(client);
532
533     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
534     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
535     // for backwards compatibility.
536     LayoutMilestones milestones = 0;
537     if (client) {
538         if (m_loaderClient.client().didFirstLayoutForFrame)
539             milestones |= WebCore::DidFirstLayout;
540         if (m_loaderClient.client().didFirstVisuallyNonEmptyLayoutForFrame)
541             milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
542     }
543
544     if (milestones)
545         listenForLayoutMilestones(milestones);
546 }
547
548 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
549 {
550     m_policyClient.initialize(client);
551 }
552
553 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase* client)
554 {
555     m_resourceLoadClient.initialize(client);
556 }
557
558 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClientBase* client)
559 {
560     m_uiClient.initialize(client);
561 }
562
563 #if ENABLE(FULLSCREEN_API)
564 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
565 {
566     m_fullScreenClient.initialize(client);
567 }
568 #endif
569
570 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase* client)
571 {
572     m_logDiagnosticMessageClient.initialize(client);
573 }
574
575 #if ENABLE(NETSCAPE_PLUGIN_API)
576 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
577 {
578     String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
579     String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
580     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
581
582     bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin);
583
584     uint64_t pluginProcessToken;
585     uint32_t pluginLoadPolicy;
586     String unavailabilityDescription;
587     if (!sendSync(Messages::WebPageProxy::FindPlugin(parameters.mimeType, static_cast<uint32_t>(processType), parameters.url.string(), frameURLString, pageURLString, allowOnlyApplicationPlugins), Messages::WebPageProxy::FindPlugin::Reply(pluginProcessToken, newMIMEType, pluginLoadPolicy, unavailabilityDescription)))
588         return nullptr;
589
590     bool isBlockedPlugin = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy) == PluginModuleBlocked;
591
592     if (isBlockedPlugin || !pluginProcessToken) {
593 #if ENABLE(PDFKIT_PLUGIN)
594         String path = parameters.url.path();
595         if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
596             RefPtr<PDFPlugin> pdfPlugin = PDFPlugin::create(frame);
597             return pdfPlugin.release();
598         }
599 #else
600         UNUSED_PARAM(frame);
601 #endif
602     }
603
604     if (isBlockedPlugin) {
605         bool replacementObscured = false;
606         if (pluginElement->renderer()->isEmbeddedObject()) {
607             RenderEmbeddedObject* renderObject = toRenderEmbeddedObject(pluginElement->renderer());
608             renderObject->setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
609             replacementObscured = renderObject->isReplacementObscured();
610             renderObject->setUnavailablePluginIndicatorIsHidden(replacementObscured);
611         }
612
613         send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
614         return nullptr;
615     }
616
617     if (!pluginProcessToken)
618         return nullptr;
619
620     bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
621     return PluginProxy::create(pluginProcessToken, isRestartedProcess);
622 }
623
624 #endif // ENABLE(NETSCAPE_PLUGIN_API)
625
626 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
627 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
628 {
629     return WebGLAllowCreation;
630 }
631
632 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
633 {
634     return WebGLAllowCreation;
635 }
636 #endif
637
638 EditorState WebPage::editorState() const
639 {
640     Frame& frame = m_page->focusController().focusedOrMainFrame();
641
642     EditorState result;
643
644     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
645         if (!pluginView->getSelectionString().isNull()) {
646             result.selectionIsNone = false;
647             result.selectionIsRange = true;
648             result.isInPlugin = true;
649             return result;
650         }
651     }
652
653     const VisibleSelection& selection = frame.selection().selection();
654
655     result.selectionIsNone = selection.isNone();
656     result.selectionIsRange = selection.isRange();
657     result.isContentEditable = selection.isContentEditable();
658     result.isContentRichlyEditable = selection.isContentRichlyEditable();
659     result.isInPasswordField = selection.isInPasswordField();
660     result.hasComposition = frame.editor().hasComposition();
661     result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange();
662
663 #if PLATFORM(IOS)
664     if (frame.editor().hasComposition()) {
665         RefPtr<Range> compositionRange = frame.editor().compositionRange();
666         Vector<WebCore::SelectionRect> compositionRects;
667         compositionRange->collectSelectionRects(compositionRects);
668         if (compositionRects.size())
669             result.firstMarkedRect = compositionRects[0].rect();
670         if (compositionRects.size() > 1)
671             result.lastMarkedRect = compositionRects.last().rect();
672         else
673             result.lastMarkedRect = result.firstMarkedRect;
674         result.markedText = plainText(compositionRange.get());
675     }
676     FrameView* view = frame.view();
677     if (selection.isCaret()) {
678         result.caretRectAtStart = view->contentsToRootView(frame.selection().absoluteCaretBounds());
679         result.caretRectAtEnd = result.caretRectAtStart;
680         if (m_shouldReturnWordAtSelection)
681             result.wordAtSelection = plainText(wordRangeFromPosition(selection.start()).get());
682     } else if (selection.isRange()) {
683         result.caretRectAtStart = view->contentsToRootView(VisiblePosition(selection.start()).absoluteCaretBounds());
684         result.caretRectAtEnd = view->contentsToRootView(VisiblePosition(selection.end()).absoluteCaretBounds());
685         RefPtr<Range> selectedRange = selection.toNormalizedRange();
686         selectedRange->collectSelectionRects(result.selectionRects);
687         convertSelectionRectsToRootView(view, result.selectionRects);
688         result.selectedTextLength = plainText(selectedRange.get(), TextIteratorDefaultBehavior, true).length();
689     }
690 #endif
691
692 #if PLATFORM(GTK)
693     result.cursorRect = frame.selection().absoluteCaretBounds();
694 #endif
695
696     return result;
697 }
698
699 String WebPage::renderTreeExternalRepresentation() const
700 {
701     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
702 }
703
704 String WebPage::renderTreeExternalRepresentationForPrinting() const
705 {
706     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
707 }
708
709 uint64_t WebPage::renderTreeSize() const
710 {
711     if (!m_page)
712         return 0;
713     return m_page->renderTreeSize();
714 }
715
716 void WebPage::setTracksRepaints(bool trackRepaints)
717 {
718     if (FrameView* view = mainFrameView())
719         view->setTracksRepaints(trackRepaints);
720 }
721
722 bool WebPage::isTrackingRepaints() const
723 {
724     if (FrameView* view = mainFrameView())
725         return view->isTrackingRepaints();
726
727     return false;
728 }
729
730 void WebPage::resetTrackedRepaints()
731 {
732     if (FrameView* view = mainFrameView())
733         view->resetTrackedRepaints();
734 }
735
736 PassRefPtr<API::Array> WebPage::trackedRepaintRects()
737 {
738     FrameView* view = mainFrameView();
739     if (!view)
740         return API::Array::create();
741
742     Vector<RefPtr<API::Object>> repaintRects;
743     repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
744
745     for (const auto& repaintRect : view->trackedRepaintRects())
746         repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
747
748     return API::Array::create(std::move(repaintRects));
749 }
750
751 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
752 {
753     if (!frame.document()->isPluginDocument())
754         return 0;
755
756     PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
757
758     if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
759         return 0;
760
761     PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
762     return pluginView;
763 }
764
765 PluginView* WebPage::pluginViewForFrame(Frame* frame)
766 {
767     if (!frame->document()->isPluginDocument())
768         return 0;
769
770     PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
771     PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
772     return pluginView;
773 }
774
775 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
776 {
777     Frame& frame = m_page->focusController().focusedOrMainFrame();
778
779     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
780         pluginView->handleEditingCommand(commandName, argument);
781         return;
782     }
783     
784     frame.editor().command(commandName).execute(argument);
785 }
786
787 bool WebPage::isEditingCommandEnabled(const String& commandName)
788 {
789     Frame& frame = m_page->focusController().focusedOrMainFrame();
790
791     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
792         return pluginView->isEditingCommandEnabled(commandName);
793     
794     Editor::Command command = frame.editor().command(commandName);
795     return command.isSupported() && command.isEnabled();
796 }
797     
798 void WebPage::clearMainFrameName()
799 {
800     if (Frame* frame = mainFrame())
801         frame->tree().clearName();
802 }
803
804 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
805 {
806     m_drawingArea->setRootCompositingLayer(layer);
807 }
808
809 void WebPage::exitAcceleratedCompositingMode()
810 {
811     m_drawingArea->setRootCompositingLayer(0);
812 }
813
814 void WebPage::close()
815 {
816     if (m_isClosed)
817         return;
818
819     m_isClosed = true;
820
821     // If there is still no URL, then we never loaded anything in this page, so nothing to report.
822     if (!mainWebFrame()->url().isEmpty())
823         reportUsedFeatures();
824
825     if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
826         WebProcess::shared().injectedBundle()->willDestroyPage(this);
827
828 #if ENABLE(INSPECTOR)
829     m_inspector = 0;
830 #endif
831 #if ENABLE(FULLSCREEN_API)
832     m_fullScreenManager = 0;
833 #endif
834
835     if (m_activePopupMenu) {
836         m_activePopupMenu->disconnectFromPage();
837         m_activePopupMenu = 0;
838     }
839
840     if (m_activeOpenPanelResultListener) {
841         m_activeOpenPanelResultListener->disconnectFromPage();
842         m_activeOpenPanelResultListener = 0;
843     }
844
845 #if ENABLE(INPUT_TYPE_COLOR)
846     if (m_activeColorChooser) {
847         m_activeColorChooser->disconnectFromPage();
848         m_activeColorChooser = 0;
849     }
850 #endif
851
852 #if PLATFORM(GTK)
853     if (m_printOperation) {
854         m_printOperation->disconnectFromPage();
855         m_printOperation = nullptr;
856     }
857 #endif
858
859     m_sandboxExtensionTracker.invalidate();
860
861 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
862     m_determinePrimarySnapshottedPlugInTimer.stop();
863 #endif
864
865 #if ENABLE(CONTEXT_MENUS)
866     m_contextMenuClient.initialize(0);
867 #endif
868     m_editorClient.initialize(0);
869     m_formClient.initialize(0);
870     m_loaderClient.initialize(0);
871     m_policyClient.initialize(0);
872     m_resourceLoadClient.initialize(0);
873     m_uiClient.initialize(0);
874 #if ENABLE(FULLSCREEN_API)
875     m_fullScreenClient.initialize(0);
876 #endif
877     m_logDiagnosticMessageClient.initialize(0);
878
879     m_printContext = nullptr;
880     m_mainFrame->coreFrame()->loader().detachFromParent();
881     m_page = nullptr;
882     m_drawingArea = nullptr;
883
884     bool isRunningModal = m_isRunningModal;
885     m_isRunningModal = false;
886
887     // The WebPage can be destroyed by this call.
888     WebProcess::shared().removeWebPage(m_pageID);
889
890     if (isRunningModal)
891         RunLoop::main().stop();
892 }
893
894 void WebPage::tryClose()
895 {
896     SendStopResponsivenessTimer stopper(this);
897
898     if (!corePage()->userInputBridge().tryClosePage()) {
899         send(Messages::WebPageProxy::StopResponsivenessTimer());
900         return;
901     }
902
903     send(Messages::WebPageProxy::ClosePage(true));
904 }
905
906 void WebPage::sendClose()
907 {
908     send(Messages::WebPageProxy::ClosePage(false));
909 }
910
911 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
912 {
913     WebFrame* frame = WebProcess::shared().webFrame(frameID);
914     if (!frame)
915         return;
916
917     frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url))));
918 }
919
920 void WebPage::loadRequest(uint64_t navigationID, const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, IPC::MessageDecoder& decoder)
921 {
922     SendStopResponsivenessTimer stopper(this);
923
924     RefPtr<API::Object> userData;
925     InjectedBundleUserMessageDecoder userMessageDecoder(userData);
926     if (!decoder.decode(userMessageDecoder))
927         return;
928
929     ASSERT(!m_pendingNavigationID);
930     m_pendingNavigationID = navigationID;
931
932     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
933
934     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
935     // to all the client to set up any needed state.
936     m_loaderClient.willLoadURLRequest(this, request, userData.get());
937
938     // Initate the load in WebCore.
939     corePage()->userInputBridge().loadRequest(FrameLoadRequest(m_mainFrame->coreFrame(), request));
940
941     ASSERT(!m_pendingNavigationID);
942 }
943
944 void WebPage::loadDataImpl(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder)
945 {
946     SendStopResponsivenessTimer stopper(this);
947
948     RefPtr<API::Object> userData;
949     InjectedBundleUserMessageDecoder userMessageDecoder(userData);
950     if (!decoder.decode(userMessageDecoder))
951         return;
952
953     ResourceRequest request(baseURL);
954     SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
955
956     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
957     // to all the client to set up any needed state.
958     m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), userData.get());
959
960     // Initate the load in WebCore.
961     m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, substituteData));
962 }
963
964 void WebPage::loadString(const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder)
965 {
966     if (!htmlString.isNull() && htmlString.is8Bit()) {
967         RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
968         loadDataImpl(sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, decoder);
969     } else {
970         RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
971         loadDataImpl(sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, decoder);
972     }
973 }
974
975 void WebPage::loadData(const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, IPC::MessageDecoder& decoder)
976 {
977     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
978     URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
979     loadDataImpl(sharedBuffer, MIMEType, encodingName, baseURL, URL(), decoder);
980 }
981
982 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString, IPC::MessageDecoder& decoder)
983 {
984     URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
985     loadString(htmlString, ASCIILiteral("text/html"), baseURL, URL(), decoder);
986 }
987
988 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, IPC::MessageDecoder& decoder)
989 {
990     URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
991     URL unreachableURL = unreachableURLString.isEmpty() ? URL() : URL(URL(), unreachableURLString);
992     loadString(htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, decoder);
993 }
994
995 void WebPage::loadPlainTextString(const String& string, IPC::MessageDecoder& decoder)
996 {
997     loadString(string, ASCIILiteral("text/plain"), blankURL(), URL(), decoder);
998 }
999
1000 void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, IPC::MessageDecoder& decoder)
1001 {
1002     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
1003     loadDataImpl(sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), decoder);
1004 }
1005
1006 void WebPage::stopLoadingFrame(uint64_t frameID)
1007 {
1008     WebFrame* frame = WebProcess::shared().webFrame(frameID);
1009     if (!frame)
1010         return;
1011
1012     corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1013 }
1014
1015 void WebPage::stopLoading()
1016 {
1017     SendStopResponsivenessTimer stopper(this);
1018
1019     corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1020 }
1021
1022 void WebPage::setDefersLoading(bool defersLoading)
1023 {
1024     m_page->setDefersLoading(defersLoading);
1025 }
1026
1027 void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
1028 {
1029     SendStopResponsivenessTimer stopper(this);
1030
1031     ASSERT(!m_pendingNavigationID);
1032     m_pendingNavigationID = navigationID;
1033
1034     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1035     corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin);
1036 }
1037
1038 void WebPage::goForward(uint64_t backForwardItemID)
1039 {
1040     SendStopResponsivenessTimer stopper(this);
1041
1042     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1043     ASSERT(item);
1044     if (!item)
1045         return;
1046
1047     m_page->goToItem(item, FrameLoadTypeForward);
1048 }
1049
1050 void WebPage::goBack(uint64_t backForwardItemID)
1051 {
1052     SendStopResponsivenessTimer stopper(this);
1053
1054     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1055     ASSERT(item);
1056     if (!item)
1057         return;
1058
1059     m_page->goToItem(item, FrameLoadTypeBack);
1060 }
1061
1062 void WebPage::goToBackForwardItem(uint64_t backForwardItemID)
1063 {
1064     SendStopResponsivenessTimer stopper(this);
1065
1066     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1067     ASSERT(item);
1068     if (!item)
1069         return;
1070
1071     m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
1072 }
1073
1074 void WebPage::tryRestoreScrollPosition()
1075 {
1076     m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1077 }
1078
1079 void WebPage::layoutIfNeeded()
1080 {
1081     if (m_mainFrame->coreFrame()->view())
1082         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1083 }
1084
1085 WebPage* WebPage::fromCorePage(Page* page)
1086 {
1087     return static_cast<WebChromeClient&>(page->chrome().client()).page();
1088 }
1089
1090 void WebPage::setSize(const WebCore::IntSize& viewSize)
1091 {
1092     if (m_viewSize == viewSize)
1093         return;
1094
1095     FrameView* view = m_page->mainFrame().view();
1096     view->resize(viewSize);
1097     m_drawingArea->setNeedsDisplay();
1098     
1099     m_viewSize = viewSize;
1100
1101 #if USE(TILED_BACKING_STORE)
1102     if (view->useFixedLayout())
1103         sendViewportAttributesChanged();
1104 #endif
1105 }
1106
1107 #if USE(TILED_BACKING_STORE)
1108 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1109 {
1110     ASSERT(m_useFixedLayout);
1111
1112     m_page->mainFrame().view()->setFixedVisibleContentRect(rect);
1113 }
1114
1115 void WebPage::sendViewportAttributesChanged()
1116 {
1117     ASSERT(m_useFixedLayout);
1118
1119     // Viewport properties have no impact on zero sized fixed viewports.
1120     if (m_viewSize.isEmpty())
1121         return;
1122
1123     // Recalculate the recommended layout size, when the available size (device pixel) changes.
1124     Settings& settings = m_page->settings();
1125
1126     int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1127
1128     // If unset  we use the viewport dimensions. This fits with the behavior of desktop browsers.
1129     int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1130     int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1131
1132     ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1133
1134     FrameView* view = m_page->mainFrame().view();
1135
1136     // If no layout was done yet set contentFixedOrigin to (0,0).
1137     IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1138
1139     // Put the width and height to the viewport width and height. In css units however.
1140     // Use FloatSize to avoid truncated values during scale.
1141     FloatSize contentFixedSize = m_viewSize;
1142
1143 #if ENABLE(CSS_DEVICE_ADAPTATION)
1144     // CSS viewport descriptors might be applied to already affected viewport size
1145     // if the page enables/disables stylesheets, so need to keep initial viewport size.
1146     view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1147 #endif
1148
1149     contentFixedSize.scale(1 / attr.initialScale);
1150     setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1151
1152     attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1153
1154     // This also takes care of the relayout.
1155     setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1156
1157     send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1158 }
1159 #endif
1160
1161 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1162 {
1163     FrameView* frameView = m_page->mainFrame().view();
1164
1165     IntPoint scrollPosition = frameView->scrollPosition();
1166     IntPoint maximumScrollPosition = frameView->maximumScrollPosition();
1167
1168     // If the current scroll position in a direction is the max scroll position 
1169     // we don't want to scroll at all.
1170     IntSize newScrollOffset;
1171     if (scrollPosition.x() < maximumScrollPosition.x())
1172         newScrollOffset.setWidth(scrollOffset.width());
1173     if (scrollPosition.y() < maximumScrollPosition.y())
1174         newScrollOffset.setHeight(scrollOffset.height());
1175
1176     if (newScrollOffset.isZero())
1177         return;
1178
1179     frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1180 }
1181
1182 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1183 {
1184     GraphicsContextStateSaver stateSaver(graphicsContext);
1185     graphicsContext.clip(rect);
1186
1187     m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1188 }
1189
1190 void WebPage::drawPageOverlay(PageOverlay* pageOverlay, GraphicsContext& graphicsContext, const IntRect& rect)
1191 {
1192     ASSERT(pageOverlay);
1193
1194     GraphicsContextStateSaver stateSaver(graphicsContext);
1195     graphicsContext.clip(rect);
1196     pageOverlay->drawRect(graphicsContext, rect);
1197 }
1198
1199 double WebPage::textZoomFactor() const
1200 {
1201     Frame* frame = m_mainFrame->coreFrame();
1202     if (!frame)
1203         return 1;
1204     return frame->textZoomFactor();
1205 }
1206
1207 void WebPage::setTextZoomFactor(double zoomFactor)
1208 {
1209     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1210     if (pluginView && pluginView->handlesPageScaleFactor())
1211         return;
1212
1213     Frame* frame = m_mainFrame->coreFrame();
1214     if (!frame)
1215         return;
1216     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1217 }
1218
1219 double WebPage::pageZoomFactor() const
1220 {
1221     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1222     if (pluginView && pluginView->handlesPageScaleFactor())
1223         return pluginView->pageScaleFactor();
1224
1225     Frame* frame = m_mainFrame->coreFrame();
1226     if (!frame)
1227         return 1;
1228     return frame->pageZoomFactor();
1229 }
1230
1231 void WebPage::setPageZoomFactor(double zoomFactor)
1232 {
1233     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1234     if (pluginView && pluginView->handlesPageScaleFactor()) {
1235         pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1236         return;
1237     }
1238
1239     Frame* frame = m_mainFrame->coreFrame();
1240     if (!frame)
1241         return;
1242     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1243 }
1244
1245 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1246 {
1247     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1248     if (pluginView && pluginView->handlesPageScaleFactor()) {
1249         pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1250         return;
1251     }
1252
1253     Frame* frame = m_mainFrame->coreFrame();
1254     if (!frame)
1255         return;
1256     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1257 }
1258
1259 void WebPage::windowScreenDidChange(uint64_t displayID)
1260 {
1261     m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1262 }
1263
1264 void WebPage::scalePage(double scale, const IntPoint& origin)
1265 {
1266     if (scale == pageScaleFactor())
1267         return;
1268
1269 #if PLATFORM(IOS)
1270     m_scaleWasSetByUIProcess = false;
1271 #endif
1272     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1273     if (pluginView && pluginView->handlesPageScaleFactor()) {
1274         pluginView->setPageScaleFactor(scale, origin);
1275         return;
1276     }
1277
1278     m_page->setPageScaleFactor(scale, origin);
1279
1280     for (auto* pluginView : m_pluginViews)
1281         pluginView->pageScaleFactorDidChange();
1282
1283     if (m_drawingArea->layerTreeHost())
1284         m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1285
1286     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1287 }
1288
1289 double WebPage::pageScaleFactor() const
1290 {
1291     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1292     if (pluginView && pluginView->handlesPageScaleFactor())
1293         return pluginView->pageScaleFactor();
1294     
1295     return m_page->pageScaleFactor();
1296 }
1297
1298 void WebPage::setDeviceScaleFactor(float scaleFactor)
1299 {
1300     if (scaleFactor == m_page->deviceScaleFactor())
1301         return;
1302
1303     m_page->setDeviceScaleFactor(scaleFactor);
1304
1305     // Tell all our plug-in views that the device scale factor changed.
1306 #if PLATFORM(MAC)
1307     for (auto* pluginView : m_pluginViews)
1308         pluginView->setDeviceScaleFactor(scaleFactor);
1309
1310     updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1311 #endif
1312
1313     if (m_findController.isShowingOverlay()) {
1314         // We must have updated layout to get the selection rects right.
1315         layoutIfNeeded();
1316         m_findController.deviceScaleFactorDidChange();
1317     }
1318
1319     if (m_drawingArea->layerTreeHost())
1320         m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1321 }
1322
1323 float WebPage::deviceScaleFactor() const
1324 {
1325     return m_page->deviceScaleFactor();
1326 }
1327
1328 void WebPage::setUseFixedLayout(bool fixed)
1329 {
1330     // Do not overwrite current settings if initially setting it to false.
1331     if (m_useFixedLayout == fixed)
1332         return;
1333     m_useFixedLayout = fixed;
1334
1335 #if !PLATFORM(IOS)
1336     m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1337 #endif
1338 #if USE(COORDINATED_GRAPHICS)
1339     m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1340     m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1341     m_page->settings().setDelegatesPageScaling(fixed);
1342     m_page->settings().setScrollingCoordinatorEnabled(fixed);
1343 #endif
1344
1345 #if USE(TILED_BACKING_STORE) && ENABLE(SMOOTH_SCROLLING)
1346     // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1347     // Ensure we don't do animated scrolling in the WebProcess in that case.
1348     m_page->settings().setScrollAnimatorEnabled(!fixed);
1349 #endif
1350
1351     FrameView* view = mainFrameView();
1352     if (!view)
1353         return;
1354
1355 #if USE(TILED_BACKING_STORE)
1356     view->setDelegatesScrolling(fixed);
1357     view->setPaintsEntireContents(fixed);
1358 #endif
1359     view->setUseFixedLayout(fixed);
1360     if (!fixed)
1361         setFixedLayoutSize(IntSize());
1362 }
1363
1364 void WebPage::setFixedLayoutSize(const IntSize& size)
1365 {
1366     FrameView* view = mainFrameView();
1367     if (!view || view->fixedLayoutSize() == size)
1368         return;
1369
1370     view->setFixedLayoutSize(size);
1371     // Do not force it until the first layout, this would then become our first layout prematurely.
1372     if (view->didFirstLayout())
1373         view->forceLayout();
1374 }
1375
1376 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1377 {
1378     if (!m_page)
1379         return;
1380     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1381 }
1382
1383 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1384 {
1385     m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1386 }
1387
1388 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1389 {
1390     if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1391         m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1392 }
1393
1394 void WebPage::setPaginationMode(uint32_t mode)
1395 {
1396     Pagination pagination = m_page->pagination();
1397     pagination.mode = static_cast<Pagination::Mode>(mode);
1398     m_page->setPagination(pagination);
1399 }
1400
1401 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1402 {
1403     Pagination pagination = m_page->pagination();
1404     pagination.behavesLikeColumns = behavesLikeColumns;
1405     m_page->setPagination(pagination);
1406 }
1407
1408 void WebPage::setPageLength(double pageLength)
1409 {
1410     Pagination pagination = m_page->pagination();
1411     pagination.pageLength = pageLength;
1412     m_page->setPagination(pagination);
1413 }
1414
1415 void WebPage::setGapBetweenPages(double gap)
1416 {
1417     Pagination pagination = m_page->pagination();
1418     pagination.gap = gap;
1419     m_page->setPagination(pagination);
1420 }
1421
1422 void WebPage::postInjectedBundleMessage(const String& messageName, IPC::MessageDecoder& decoder)
1423 {
1424     InjectedBundle* injectedBundle = WebProcess::shared().injectedBundle();
1425     if (!injectedBundle)
1426         return;
1427
1428     RefPtr<API::Object> messageBody;
1429     InjectedBundleUserMessageDecoder messageBodyDecoder(messageBody);
1430     if (!decoder.decode(messageBodyDecoder))
1431         return;
1432
1433     injectedBundle->didReceiveMessageToPage(this, messageName, messageBody.get());
1434 }
1435
1436 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay, bool shouldFadeIn)
1437 {
1438     RefPtr<PageOverlay> overlay = pageOverlay;
1439     
1440     if (m_pageOverlays.contains(overlay.get()))
1441         return;
1442
1443     m_pageOverlays.append(overlay);
1444     overlay->setPage(this);
1445
1446     if (shouldFadeIn)
1447         overlay->startFadeInAnimation();
1448
1449     m_drawingArea->didInstallPageOverlay(overlay.get());
1450 }
1451
1452 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool shouldFadeOut)
1453 {
1454     size_t existingOverlayIndex = m_pageOverlays.find(pageOverlay);
1455     if (existingOverlayIndex == notFound)
1456         return;
1457
1458     if (shouldFadeOut) {
1459         pageOverlay->startFadeOutAnimation();
1460         return;
1461     }
1462
1463     pageOverlay->setPage(0);
1464     m_pageOverlays.remove(existingOverlayIndex);
1465
1466     m_drawingArea->didUninstallPageOverlay(pageOverlay);
1467 }
1468
1469 #if !PLATFORM(IOS)
1470 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1471 {
1472     if (m_headerBanner)
1473         m_headerBanner->detachFromPage();
1474
1475     m_headerBanner = pageBanner;
1476
1477     if (m_headerBanner)
1478         m_headerBanner->addToPage(PageBanner::Header, this);
1479 }
1480
1481 PageBanner* WebPage::headerPageBanner()
1482 {
1483     return m_headerBanner.get();
1484 }
1485
1486 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1487 {
1488     if (m_footerBanner)
1489         m_footerBanner->detachFromPage();
1490
1491     m_footerBanner = pageBanner;
1492
1493     if (m_footerBanner)
1494         m_footerBanner->addToPage(PageBanner::Footer, this);
1495 }
1496
1497 PageBanner* WebPage::footerPageBanner()
1498 {
1499     return m_footerBanner.get();
1500 }
1501
1502 void WebPage::hidePageBanners()
1503 {
1504     if (m_headerBanner)
1505         m_headerBanner->hide();
1506     if (m_footerBanner)
1507         m_footerBanner->hide();
1508 }
1509
1510 void WebPage::showPageBanners()
1511 {
1512     if (m_headerBanner)
1513         m_headerBanner->showIfHidden();
1514     if (m_footerBanner)
1515         m_footerBanner->showIfHidden();
1516 }
1517 #endif // !PLATFORM(IOS)
1518
1519 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1520 {
1521     SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1522     snapshotOptions |= SnapshotOptionsShareable;
1523
1524     RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1525
1526     ShareableBitmap::Handle handle;
1527     if (image)
1528         image->bitmap()->createHandle(handle, SharedMemory::ReadOnly);
1529
1530     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1531 }
1532
1533 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double scaleFactor, SnapshotOptions options)
1534 {
1535     IntRect snapshotRect = rect;
1536     if (options & SnapshotOptionsRespectDrawingAreaTransform)
1537         snapshotRect = m_drawingArea->rootLayerTransform().inverse().mapRect(snapshotRect);
1538
1539     IntSize bitmapSize = snapshotRect.size();
1540     bitmapSize.scale(scaleFactor * corePage()->deviceScaleFactor());
1541
1542     return snapshotAtSize(rect, bitmapSize, options);
1543 }
1544
1545 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1546 {
1547     Frame* coreFrame = m_mainFrame->coreFrame();
1548     if (!coreFrame)
1549         return nullptr;
1550
1551     FrameView* frameView = coreFrame->view();
1552     if (!frameView)
1553         return nullptr;
1554
1555     IntRect snapshotRect = rect;
1556     if (options & SnapshotOptionsRespectDrawingAreaTransform)
1557         snapshotRect = m_drawingArea->rootLayerTransform().inverse().mapRect(snapshotRect);
1558
1559     float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1560     float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1561     float scaleFactor = std::min(horizontalScaleFactor, verticalScaleFactor);
1562
1563     RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1564     if (!snapshot->bitmap())
1565         return nullptr;
1566
1567     auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1568
1569     graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), frameView->baseBackgroundColor(), ColorSpaceDeviceRGB);
1570
1571     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1572         graphicsContext->applyDeviceScaleFactor(corePage()->deviceScaleFactor());
1573
1574     graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1575     graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1576
1577     FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1578     if (options & SnapshotOptionsExcludeSelectionHighlighting)
1579         shouldPaintSelection = FrameView::ExcludeSelection;
1580
1581     FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1582     if (options & SnapshotOptionsInViewCoordinates)
1583         coordinateSpace = FrameView::ViewCoordinates;
1584
1585     frameView->paintContentsForSnapshot(graphicsContext.get(), snapshotRect, shouldPaintSelection, coordinateSpace);
1586
1587     if (options & SnapshotOptionsPaintSelectionRectangle) {
1588         FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1589         graphicsContext->setStrokeColor(Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
1590         graphicsContext->strokeRect(selectionRectangle, 1);
1591     }
1592     
1593     return snapshot.release();
1594 }
1595
1596 void WebPage::pageDidScroll()
1597 {
1598     m_uiClient.pageDidScroll(this);
1599
1600     send(Messages::WebPageProxy::PageDidScroll());
1601 }
1602
1603 #if USE(TILED_BACKING_STORE)
1604 void WebPage::pageDidRequestScroll(const IntPoint& point)
1605 {
1606     send(Messages::WebPageProxy::PageDidRequestScroll(point));
1607 }
1608 #endif
1609
1610 #if ENABLE(CONTEXT_MENUS)
1611 WebContextMenu* WebPage::contextMenu()
1612 {
1613     if (!m_contextMenu)
1614         m_contextMenu = WebContextMenu::create(this);
1615     return m_contextMenu.get();
1616 }
1617
1618 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1619 {
1620     corePage()->contextMenuController().clearContextMenu();
1621     
1622     // Simulate a mouse click to generate the correct menu.
1623     PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime());
1624     bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
1625     if (!handled)
1626         return 0;
1627
1628     return contextMenu();
1629 }
1630 #endif
1631
1632 // Events 
1633
1634 static const WebEvent* g_currentEvent = 0;
1635
1636 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1637 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1638 // platform events passed to the event handler code.
1639 const WebEvent* WebPage::currentEvent()
1640 {
1641     return g_currentEvent;
1642 }
1643
1644 class CurrentEvent {
1645 public:
1646     explicit CurrentEvent(const WebEvent& event)
1647         : m_previousCurrentEvent(g_currentEvent)
1648     {
1649         g_currentEvent = &event;
1650     }
1651
1652     ~CurrentEvent()
1653     {
1654         g_currentEvent = m_previousCurrentEvent;
1655     }
1656
1657 private:
1658     const WebEvent* m_previousCurrentEvent;
1659 };
1660
1661 #if ENABLE(CONTEXT_MENUS)
1662 static bool isContextClick(const PlatformMouseEvent& event)
1663 {
1664     if (event.button() == WebCore::RightButton)
1665         return true;
1666
1667 #if PLATFORM(COCOA)
1668     // FIXME: this really should be about OSX-style UI, not about the Mac port
1669     if (event.button() == WebCore::LeftButton && event.ctrlKey())
1670         return true;
1671 #endif
1672
1673     return false;
1674 }
1675
1676 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1677 {
1678     IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
1679     HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
1680
1681     Frame* frame = &page->corePage()->mainFrame();
1682     if (result.innerNonSharedNode())
1683         frame = result.innerNonSharedNode()->document().frame();
1684
1685     bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
1686     if (handled)
1687         page->contextMenu()->show();
1688
1689     return handled;
1690 }
1691 #endif
1692
1693 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1694 {
1695     Frame& frame = page->corePage()->mainFrame();
1696     if (!frame.view())
1697         return false;
1698
1699     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1700
1701     switch (platformMouseEvent.type()) {
1702         case PlatformEvent::MousePressed: {
1703 #if ENABLE(CONTEXT_MENUS)
1704             if (isContextClick(platformMouseEvent))
1705                 page->corePage()->contextMenuController().clearContextMenu();
1706 #endif
1707
1708             bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
1709 #if ENABLE(CONTEXT_MENUS)
1710             if (isContextClick(platformMouseEvent))
1711                 handled = handleContextMenuEvent(platformMouseEvent, page);
1712 #endif
1713             return handled;
1714         }
1715         case PlatformEvent::MouseReleased:
1716             return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
1717
1718         case PlatformEvent::MouseMoved:
1719             if (onlyUpdateScrollbars)
1720                 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
1721             return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
1722         default:
1723             ASSERT_NOT_REACHED();
1724             return false;
1725     }
1726 }
1727
1728 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1729 {
1730     m_page->pageThrottler().didReceiveUserInput();
1731
1732 #if ENABLE(CONTEXT_MENUS)
1733     // Don't try to handle any pending mouse events if a context menu is showing.
1734     if (m_isShowingContextMenu) {
1735         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1736         return;
1737     }
1738 #endif
1739     bool handled = false;
1740     if (m_pageOverlays.size()) {
1741         // Let the page overlay handle the event.
1742         PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1743         for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it)
1744             if ((handled = (*it)->mouseEvent(mouseEvent)))
1745                 break;
1746     }
1747
1748 #if !PLATFORM(IOS)
1749     if (!handled && m_headerBanner)
1750         handled = m_headerBanner->mouseEvent(mouseEvent);
1751     if (!handled && m_footerBanner)
1752         handled = m_footerBanner->mouseEvent(mouseEvent);
1753 #endif // !PLATFORM(IOS)
1754
1755     if (!handled && canHandleUserEvents()) {
1756         CurrentEvent currentEvent(mouseEvent);
1757
1758         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1759         // button is currently pressed. It is possible that neither of those things will be true since on
1760         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1761         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1762         // efficient scrollbars-only version of the event.
1763         bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1764         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1765     }
1766
1767     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1768 }
1769
1770 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1771 {
1772     handled = false;
1773
1774     if (m_pageOverlays.size()) {
1775         PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1776         for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it)
1777             if ((handled = (*it)->mouseEvent(mouseEvent)))
1778                 break;
1779     }
1780 #if !PLATFORM(IOS)
1781     if (!handled && m_headerBanner)
1782         handled = m_headerBanner->mouseEvent(mouseEvent);
1783     if (!handled && m_footerBanner)
1784         handled = m_footerBanner->mouseEvent(mouseEvent);
1785 #endif // !PLATFORM(IOS)
1786
1787     if (!handled) {
1788         CurrentEvent currentEvent(mouseEvent);
1789
1790         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1791         // button is currently pressed. It is possible that neither of those things will be true since on 
1792         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one 
1793         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1794         // efficient scrollbars-only version of the event.
1795         bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1796         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1797     }
1798 }
1799
1800 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1801 {
1802     Frame& frame = page->mainFrame();
1803     if (!frame.view())
1804         return false;
1805
1806     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1807     return page->userInputBridge().handleWheelEvent(platformWheelEvent);
1808 }
1809
1810 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1811 {
1812     m_page->pageThrottler().didReceiveUserInput();
1813
1814     bool handled = false;
1815
1816     if (canHandleUserEvents()) {
1817         CurrentEvent currentEvent(wheelEvent);
1818
1819         handled = handleWheelEvent(wheelEvent, m_page.get());
1820     }
1821     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1822 }
1823
1824 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1825 {
1826     CurrentEvent currentEvent(wheelEvent);
1827
1828     handled = handleWheelEvent(wheelEvent, m_page.get());
1829 }
1830
1831 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1832 {
1833     if (!page->mainFrame().view())
1834         return false;
1835
1836     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1837         return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
1838     return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
1839 }
1840
1841 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1842 {
1843     m_page->pageThrottler().didReceiveUserInput();
1844
1845     bool handled = false;
1846
1847     if (canHandleUserEvents()) {
1848         CurrentEvent currentEvent(keyboardEvent);
1849
1850         handled = handleKeyEvent(keyboardEvent, m_page.get());
1851         // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1852         if (!handled)
1853             handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1854     }
1855     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1856 }
1857
1858 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
1859 {
1860     CurrentEvent currentEvent(keyboardEvent);
1861
1862     Frame& frame = m_page->focusController().focusedOrMainFrame();
1863     frame.document()->updateStyleIfNeeded();
1864
1865     handled = handleKeyEvent(keyboardEvent, m_page.get());
1866     if (!handled)
1867         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1868 }
1869
1870 WKTypeRef WebPage::pageOverlayCopyAccessibilityAttributeValue(WKStringRef attribute, WKTypeRef parameter)
1871 {
1872     if (!m_pageOverlays.size())
1873         return 0;
1874     PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1875     for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) {
1876         WKTypeRef value = (*it)->copyAccessibilityAttributeValue(attribute, parameter);
1877         if (value)
1878             return value;
1879     }
1880     return 0;
1881 }
1882
1883 WKArrayRef WebPage::pageOverlayCopyAccessibilityAttributesNames(bool parameterizedNames)
1884 {
1885     if (!m_pageOverlays.size())
1886         return 0;
1887     PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1888     for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) {
1889         WKArrayRef value = (*it)->copyAccessibilityAttributeNames(parameterizedNames);
1890         if (value)
1891             return value;
1892     }
1893     return 0;
1894 }
1895
1896 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1897 {
1898     bool isEnabled = false;
1899     int32_t state = 0;
1900     Frame& frame = m_page->focusController().focusedOrMainFrame();
1901     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1902         isEnabled = pluginView->isEditingCommandEnabled(commandName);
1903     else {
1904         Editor::Command command = frame.editor().command(commandName);
1905         state = command.state();
1906         isEnabled = command.isSupported() && command.isEnabled();
1907     }
1908
1909     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1910 }
1911
1912 void WebPage::executeEditCommand(const String& commandName)
1913 {
1914     executeEditingCommand(commandName, String());
1915 }
1916
1917 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1918 {
1919     const BackForwardListItemVector& list = sessionState.list();
1920     size_t size = list.size();
1921     uint64_t currentItemID = 0;
1922     for (size_t i = 0; i < size; ++i) {
1923         WebBackForwardListItem* webItem = list[i].get();
1924         DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1925         
1926         RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1927         if (!item) {
1928             LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1929             return 0;
1930         }
1931         
1932         if (i == sessionState.currentIndex())
1933             currentItemID = webItem->itemID();
1934         
1935         WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1936     }    
1937     ASSERT(currentItemID);
1938     return currentItemID;
1939 }
1940
1941 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState)
1942 {
1943     if (uint64_t currentItemID = restoreSession(sessionState))
1944         goToBackForwardItem(currentItemID);
1945 }
1946
1947 #if ENABLE(TOUCH_EVENTS)
1948 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1949 {
1950     if (!page->mainFrame().view())
1951         return false;
1952
1953     return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
1954 }
1955
1956 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1957 {
1958     bool handled = false;
1959
1960     if (canHandleUserEvents()) {
1961         CurrentEvent currentEvent(touchEvent);
1962
1963         handled = handleTouchEvent(touchEvent, m_page.get());
1964     }
1965     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1966 }
1967
1968 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
1969 {
1970     CurrentEvent currentEvent(touchEvent);
1971     handled = handleTouchEvent(touchEvent, m_page.get());
1972 }
1973 #endif
1974
1975 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1976 {
1977     return page->userInputBridge().scrollRecursively(direction, granularity);
1978 }
1979
1980 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1981 {
1982     return page->userInputBridge().logicalScrollRecursively(direction, granularity);
1983 }
1984
1985 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1986 {
1987     return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1988 }
1989
1990 void WebPage::centerSelectionInVisibleArea()
1991 {
1992     Frame& frame = m_page->focusController().focusedOrMainFrame();
1993     frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
1994     m_findController.showFindIndicatorInSelection();
1995 }
1996
1997 #if ENABLE(REMOTE_INSPECTOR)
1998 void WebPage::setAllowsRemoteInspection(bool allow)
1999 {
2000     m_page->setRemoteInspectionAllowed(allow);
2001 }
2002 #endif
2003
2004 void WebPage::setDrawsBackground(bool drawsBackground)
2005 {
2006     if (m_drawsBackground == drawsBackground)
2007         return;
2008
2009     m_drawsBackground = drawsBackground;
2010
2011     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2012         if (FrameView* view = coreFrame->view())
2013             view->setTransparent(!drawsBackground);
2014     }
2015
2016     m_drawingArea->pageBackgroundTransparencyChanged();
2017     m_drawingArea->setNeedsDisplay();
2018 }
2019
2020 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
2021 {
2022     if (m_drawsTransparentBackground == drawsTransparentBackground)
2023         return;
2024
2025     m_drawsTransparentBackground = drawsTransparentBackground;
2026
2027     Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2028     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2029         if (FrameView* view = coreFrame->view())
2030             view->setBaseBackgroundColor(backgroundColor);
2031     }
2032
2033     m_drawingArea->pageBackgroundTransparencyChanged();
2034     m_drawingArea->setNeedsDisplay();
2035 }
2036
2037 void WebPage::setTopContentInset(float contentInset)
2038 {
2039     m_page->setTopContentInset(contentInset);
2040 }
2041
2042 void WebPage::viewWillStartLiveResize()
2043 {
2044     if (!m_page)
2045         return;
2046
2047     // FIXME: This should propagate to all ScrollableAreas.
2048     Frame& frame = m_page->focusController().focusedOrMainFrame();
2049     if (FrameView* view = frame.view())
2050         view->willStartLiveResize();
2051 }
2052
2053 void WebPage::viewWillEndLiveResize()
2054 {
2055     if (!m_page)
2056         return;
2057
2058     // FIXME: This should propagate to all ScrollableAreas.
2059     Frame& frame = m_page->focusController().focusedOrMainFrame();
2060     if (FrameView* view = frame.view())
2061         view->willEndLiveResize();
2062 }
2063
2064 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
2065 {
2066     if (!m_page)
2067         return;
2068
2069     Frame& frame = m_page->focusController().focusedOrMainFrame();
2070     frame.document()->setFocusedElement(0);
2071
2072     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2073         PlatformKeyboardEvent platformEvent(platform(event));
2074         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2075         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2076         return;
2077     }
2078
2079     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2080 }
2081
2082 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
2083 {
2084     if (m_windowResizerSize == windowResizerSize)
2085         return;
2086
2087     m_windowResizerSize = windowResizerSize;
2088
2089     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2090         FrameView* view = coreFrame->view();
2091         if (view)
2092             view->windowResizerRectChanged();
2093     }
2094 }
2095
2096 void WebPage::setCanStartMediaTimerFired()
2097 {
2098     if (m_page)
2099         m_page->setCanStartMedia(true);
2100 }
2101
2102 #if !PLATFORM(MAC)
2103 void WebPage::didUpdateViewStateTimerFired()
2104 {
2105     send(Messages::WebPageProxy::DidUpdateViewState());
2106 }
2107 #endif
2108
2109 inline bool WebPage::canHandleUserEvents() const
2110 {
2111 #if USE(TILED_BACKING_STORE)
2112     // Should apply only if the area was frozen by didStartPageTransition().
2113     return !m_drawingArea->layerTreeStateIsFrozen();
2114 #endif
2115     return true;
2116 }
2117
2118 void WebPage::updateIsInWindow(bool isInitialState)
2119 {
2120     bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2121
2122     if (!isInWindow) {
2123         m_setCanStartMediaTimer.stop();
2124         m_page->setCanStartMedia(false);
2125         
2126         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2127         if (!isInitialState)
2128             WebProcess::shared().pageWillLeaveWindow(m_pageID);
2129     } else {
2130         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2131         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2132         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2133         if (m_mayStartMediaWhenInWindow)
2134             m_setCanStartMediaTimer.startOneShot(0);
2135
2136         WebProcess::shared().pageDidEnterWindow(m_pageID);
2137     }
2138
2139     if (isInWindow)
2140         layoutIfNeeded();
2141 }
2142
2143 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState)
2144 {
2145     ViewState::Flags changed = m_viewState ^ viewState;
2146     m_viewState = viewState;
2147
2148     m_drawingArea->viewStateDidChange(changed);
2149     m_page->setViewState(viewState);
2150     for (auto* pluginView : m_pluginViews)
2151         pluginView->viewStateDidChange(changed);
2152
2153     if (changed & ViewState::IsInWindow)
2154         updateIsInWindow();
2155
2156     if (wantsDidUpdateViewState)
2157         m_sendDidUpdateViewStateTimer.startOneShot(0);
2158 }
2159
2160 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2161 {
2162     m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2163
2164     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2165
2166     for (auto* pluginView : m_pluginViews)
2167         pluginView->setLayerHostingMode(m_layerHostingMode);
2168 }
2169
2170 SessionID WebPage::sessionID() const
2171 {
2172     if (m_page->isSessionIDSet())
2173         return m_page->sessionID();
2174
2175     return m_page->settings().privateBrowsingEnabled() ? SessionID::legacyPrivateSessionID() : SessionID::defaultSessionID();
2176 }
2177
2178 bool WebPage::isUsingEphemeralSession() const
2179 {
2180     return sessionID().isEphemeral();
2181 }
2182
2183 void WebPage::setSessionID(SessionID sessionID)
2184 {
2185     m_page->setSessionID(sessionID);
2186     if (sessionID.isEphemeral())
2187         WebProcess::shared().ensurePrivateBrowsingSession(sessionID);
2188 }
2189
2190 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
2191 {
2192     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2193     if (!frame)
2194         return;
2195     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
2196 }
2197
2198 void WebPage::didStartPageTransition()
2199 {
2200     m_drawingArea->setLayerTreeStateIsFrozen(true);
2201 }
2202
2203 void WebPage::didCompletePageTransition()
2204 {
2205 #if USE(TILED_BACKING_STORE)
2206     if (m_mainFrame->coreFrame()->view()->delegatesScrolling())
2207         // Wait until the UI process sent us the visible rect it wants rendered.
2208         send(Messages::WebPageProxy::PageTransitionViewportReady());
2209     else
2210 #endif
2211         
2212     m_drawingArea->setLayerTreeStateIsFrozen(false);
2213 }
2214
2215 void WebPage::show()
2216 {
2217     send(Messages::WebPageProxy::ShowPage());
2218 }
2219
2220 void WebPage::setUserAgent(const String& userAgent)
2221 {
2222     m_userAgent = userAgent;
2223 }
2224
2225 void WebPage::suspendActiveDOMObjectsAndAnimations()
2226 {
2227     m_page->suspendActiveDOMObjectsAndAnimations();
2228 }
2229
2230 void WebPage::resumeActiveDOMObjectsAndAnimations()
2231 {
2232     m_page->resumeActiveDOMObjectsAndAnimations();
2233 }
2234
2235 IntPoint WebPage::screenToRootView(const IntPoint& point)
2236 {
2237     IntPoint windowPoint;
2238     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2239     return windowPoint;
2240 }
2241     
2242 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2243 {
2244     IntRect screenRect;
2245     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2246     return screenRect;
2247 }
2248
2249 IntRect WebPage::windowResizerRect() const
2250 {
2251     if (m_windowResizerSize.isEmpty())
2252         return IntRect();
2253
2254     IntSize frameViewSize;
2255     if (Frame* coreFrame = m_mainFrame->coreFrame()) {
2256         if (FrameView* view = coreFrame->view())
2257             frameViewSize = view->size();
2258     }
2259
2260     return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(), 
2261                    m_windowResizerSize.width(), m_windowResizerSize.height());
2262 }
2263
2264 KeyboardUIMode WebPage::keyboardUIMode()
2265 {
2266     bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
2267     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2268 }
2269
2270 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2271 {
2272     // NOTE: We need to be careful when running scripts that the objects we depend on don't
2273     // disappear during script execution.
2274
2275     // Retain the SerializedScriptValue at this level so it (and the internal data) lives
2276     // long enough for the DataReference to be encoded by the sent message.
2277     RefPtr<SerializedScriptValue> serializedResultValue;
2278     IPC::DataReference dataReference;
2279
2280     JSLockHolder lock(JSDOMWindow::commonVM());
2281     if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) {
2282         if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
2283             dataReference = serializedResultValue->data();
2284     }
2285
2286     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2287 }
2288
2289 void WebPage::getContentsAsString(uint64_t callbackID)
2290 {
2291     String resultString = m_mainFrame->contentsAsString();
2292     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2293 }
2294
2295 #if ENABLE(MHTML)
2296 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2297 {
2298     IPC::DataReference dataReference;
2299
2300     RefPtr<SharedBuffer> buffer = useBinaryEncoding
2301         ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2302         : MHTMLArchive::generateMHTMLData(m_page.get());
2303
2304     if (buffer)
2305         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2306
2307     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2308 }
2309 #endif
2310
2311 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2312 {
2313     String resultString = renderTreeExternalRepresentation();
2314     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2315 }
2316
2317 static Frame* frameWithSelection(Page* page)
2318 {
2319     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2320         if (frame->selection().isRange())
2321             return frame;
2322     }
2323
2324     return 0;
2325 }
2326
2327 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2328 {
2329     IPC::DataReference dataReference;
2330
2331 #if PLATFORM(COCOA)
2332     RefPtr<LegacyWebArchive> archive;
2333     RetainPtr<CFDataRef> data;
2334
2335     Frame* frame = frameWithSelection(m_page.get());
2336     if (frame) {
2337         archive = LegacyWebArchive::createFromSelection(frame);
2338         data = archive->rawDataRepresentation();
2339         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2340     }
2341 #endif
2342
2343     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2344 }
2345
2346 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2347 {
2348     String resultString = m_mainFrame->selectionAsString();
2349     if (resultString.isEmpty())
2350         resultString = m_mainFrame->contentsAsString();
2351     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2352 }
2353
2354 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2355 {
2356     String resultString;
2357     if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
2358        resultString = frame->source();
2359
2360     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2361 }
2362
2363 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2364 {
2365     IPC::DataReference dataReference;
2366
2367     RefPtr<ResourceBuffer> buffer;
2368     RefPtr<SharedBuffer> pdfResource;
2369     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2370         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame())) {
2371             if ((pdfResource = pluginView->liveResourceData()))
2372                 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(pdfResource->data()), pdfResource->size());
2373         }
2374
2375         if (dataReference.isEmpty()) {
2376             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader()) {
2377                 if ((buffer = loader->mainResourceData()))
2378                     dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2379             }
2380         }
2381     }
2382
2383     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2384 }
2385
2386 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2387 {
2388     DocumentLoader* loader = frame->loader().documentLoader();
2389     if (!loader)
2390         return 0;
2391
2392     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2393     if (!subresource)
2394         return 0;
2395
2396     return subresource->data();
2397 }
2398
2399 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2400 {
2401     IPC::DataReference dataReference;
2402     URL resourceURL(URL(), resourceURLString);
2403
2404     RefPtr<SharedBuffer> buffer;
2405     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2406         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2407         if (!buffer) {
2408             // Try to get the resource data from the cache.
2409             buffer = cachedResponseDataForURL(resourceURL);
2410         }
2411
2412         if (buffer)
2413             dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2414     }
2415
2416     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2417 }
2418
2419 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2420 {
2421     IPC::DataReference dataReference;
2422
2423 #if PLATFORM(COCOA)
2424     RetainPtr<CFDataRef> data;
2425     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2426         if ((data = frame->webArchiveData(0, 0)))
2427             dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2428     }
2429 #else
2430     UNUSED_PARAM(frameID);
2431 #endif
2432
2433     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2434 }
2435
2436 void WebPage::forceRepaintWithoutCallback()
2437 {
2438     m_drawingArea->forceRepaint();
2439 }
2440
2441 void WebPage::forceRepaint(uint64_t callbackID)
2442 {
2443     if (m_drawingArea->forceRepaintAsync(callbackID))
2444         return;
2445
2446     forceRepaintWithoutCallback();
2447     send(Messages::WebPageProxy::VoidCallback(callbackID));
2448 }
2449
2450 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2451 {
2452     WebPreferencesStore::removeTestRunnerOverrides();
2453     updatePreferences(store);
2454 }
2455
2456 void WebPage::updatePreferences(const WebPreferencesStore& store)
2457 {
2458     Settings& settings = m_page->settings();
2459
2460     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2461     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2462     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2463     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2464
2465     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2466
2467 #if PLATFORM(COCOA)
2468     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2469 #endif
2470
2471     // FIXME: This should be generated from macro expansion for all preferences,
2472     // but we currently don't match the naming of WebCore exactly so we are
2473     // handrolling the boolean and integer preferences until that is fixed.
2474
2475 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2476
2477     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2478
2479 #undef INITIALIZE_SETTINGS
2480
2481     settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2482     settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2483     settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2484     settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2485     settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2486     settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2487     settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));    
2488     settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2489     settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2490     settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2491     settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2492     if (m_page->isSessionIDSet())
2493         settings.setPrivateBrowsingEnabled(m_page->sessionID().isEphemeral());
2494     else
2495         settings.setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
2496     settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2497     settings.setJavaScriptExperimentsEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptExperimentsEnabledKey()));
2498     settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2499     settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2500     settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2501     settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2502     settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2503 #if ENABLE(WEB_ARCHIVE)
2504     settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2505 #endif
2506     settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2507     settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2508     settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2509     settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2510     settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2511     settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2512     settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2513     settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2514     settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2515     settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2516     settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2517
2518     settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2519     settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2520     settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2521     settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2522     settings.setScreenFontSubstitutionEnabled(store.getBoolValueForKey(WebPreferencesKey::screenFontSubstitutionEnabledKey())
2523 #if PLATFORM(COCOA)
2524         || WebProcess::shared().shouldForceScreenFontSubstitution()
2525 #endif
2526     );
2527     settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2528     settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2529     settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2530     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2531     settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2532
2533     settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2534     settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2535     settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2536     settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2537     settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2538     settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2539     settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2540     settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2541     RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2542     RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2543 #if ENABLE(CSS_GRID_LAYOUT)
2544     settings.setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
2545 #endif
2546     settings.setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
2547     settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2548     settings.setMultithreadedWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::multithreadedWebGLEnabledKey()));
2549     settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2550     settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2551     settings.setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
2552     settings.setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
2553     settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2554     settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2555     settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2556 #if ENABLE(SMOOTH_SCROLLING)
2557     settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2558 #endif
2559     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2560     settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2561
2562 #if ENABLE(SQL_DATABASE)
2563     DatabaseManager::manager().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2564 #endif
2565
2566 #if ENABLE(FULLSCREEN_API)
2567     settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2568 #endif
2569
2570 #if USE(AVFOUNDATION)
2571     settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2572 #endif
2573
2574 #if PLATFORM(COCOA)
2575     settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2576 #endif
2577
2578 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2579     settings.setVideoPluginProxyEnabled(false);
2580 #endif
2581
2582 #if PLATFORM(IOS)
2583     settings.setAVKitEnabled(true);
2584 #endif
2585
2586 #if ENABLE(IOS_TEXT_AUTOSIZING)
2587     settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2588 #endif
2589
2590 #if ENABLE(WEB_AUDIO)
2591     settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2592 #endif
2593
2594 #if ENABLE(MEDIA_STREAM)
2595     settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2596 #endif
2597
2598 #if ENABLE(IMAGE_CONTROLS)
2599     settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2600 #endif
2601
2602     settings.setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2603     settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2604     settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2605     settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2606     settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2607     settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2608
2609 #if ENABLE(VIDEO_TRACK)
2610     settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2611     settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2612     settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2613 #endif
2614
2615 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2616     settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2617 #endif
2618
2619     settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2620     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2621     settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2622
2623     settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2624
2625     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2626
2627     settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2628     settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2629     settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2630     settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2631     settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2632
2633 #if ENABLE(TEXT_AUTOSIZING)
2634     settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2635 #endif
2636
2637     settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2638     settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2639
2640     settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2641     settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2642     settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2643
2644 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2645     settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2646 #endif
2647 #if ENABLE(PAGE_VISIBILITY_API)
2648     settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2649 #endif
2650
2651     settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2652     settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2653     settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2654
2655     settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2656
2657 #if ENABLE(MEDIA_SOURCE)
2658     settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2659 #endif
2660
2661     settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2662
2663     settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2664     settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2665     settings.setAlwaysUseBaselineOfPrimaryFont(store.getBoolValueForKey(WebPreferencesKey::alwaysUseBaselineOfPrimaryFontKey()));
2666     settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2667     settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2668
2669     settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2670     settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2671     
2672     settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2673     settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2674
2675     settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2676
2677     if (store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey()))
2678         m_processSuppressionDisabledByWebPreference.stop();
2679     else
2680         m_processSuppressionDisabledByWebPreference.start();
2681
2682     platformPreferencesDidChange(store);
2683
2684     if (m_drawingArea)
2685         m_drawingArea->updatePreferences(store);
2686 }
2687
2688 #if PLATFORM(COCOA)
2689 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2690 {
2691     layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2692     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2693     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2694     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2695 #if PLATFORM(IOS)
2696     layerTransaction.setLastVisibleContentRectUpdateID(m_lastVisibleContentRectUpdateID);
2697     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2698     layerTransaction.setMinimumScaleFactor(minimumPageScaleFactor());
2699     layerTransaction.setMaximumScaleFactor(maximumPageScaleFactor());
2700     layerTransaction.setAllowsUserScaling(allowsUserScaling());
2701 #endif
2702 }
2703 #endif
2704
2705     
2706 #if ENABLE(INSPECTOR)
2707 WebInspector* WebPage::inspector()
2708 {
2709     if (m_isClosed)
2710         return 0;
2711     if (!m_inspector)
2712         m_inspector = WebInspector::create(this, m_inspectorClient);
2713     return m_inspector.get();
2714 }
2715 #endif
2716     
2717 #if PLATFORM(IOS)
2718 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
2719 {
2720     if (!m_videoFullscreenManager)
2721         m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
2722     return m_videoFullscreenManager.get();
2723 }
2724 #endif
2725
2726 #if ENABLE(FULLSCREEN_API)
2727 WebFullScreenManager* WebPage::fullScreenManager()
2728 {
2729     if (!m_fullScreenManager)
2730         m_fullScreenManager = WebFullScreenManager::create(this);
2731     return m_fullScreenManager.get();
2732 }
2733 #endif
2734
2735 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2736 {
2737     if (m_notificationPermissionRequestManager)
2738         return m_notificationPermissionRequestManager.get();
2739
2740     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2741     return m_notificationPermissionRequestManager.get();
2742 }
2743
2744 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
2745 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2746 {
2747     Node* node = evt->target()->toNode();
2748     ASSERT(node);
2749     Frame* frame = node->document().frame();
2750     ASSERT(frame);
2751
2752     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2753     if (!keyEvent)
2754         return false;
2755
2756     Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
2757
2758     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2759         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2760         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2761         // (e.g. Tab that inserts a Tab character, or Enter).
2762         return !command.isTextInsertion() && command.execute(evt);
2763     }
2764
2765     if (command.execute(evt))
2766         return true;
2767
2768     // Don't allow text insertion for nodes that cannot edit.
2769     if (!frame->editor().canEdit())
2770         return false;
2771
2772     // Don't insert null or control characters as they can result in unexpected behaviour
2773     if (evt->charCode() < ' ')
2774         return false;
2775
2776     return frame->editor().insertText(evt->keyEvent()->text(), evt);
2777 }
2778 #endif
2779
2780 #if ENABLE(DRAG_SUPPORT)
2781
2782 #if PLATFORM(GTK)
2783 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2784 {
2785     if (!m_page) {
2786         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2787         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2788         data->deref();
2789         return;
2790     }
2791
2792     switch (action) {
2793     case DragControllerActionEntered:
2794         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData)));
2795         break;
2796
2797     case DragControllerActionUpdated:
2798         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData)));
2799         break;
2800
2801     case DragControllerActionExited:
2802         m_page->dragController().dragExited(dragData);
2803         break;
2804
2805     case DragControllerActionPerformDrag: {
2806         m_page->dragController().performDrag(dragData);
2807         break;
2808     }
2809
2810     default:
2811         ASSERT_NOT_REACHED();
2812     }
2813     // DragData does not delete its platformData so we need to do that here.
2814     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2815     data->deref();
2816 }
2817
2818 #else
2819 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, const SandboxExtension::HandleArray& sandboxExtensionsHandleArray)
2820 {
2821     if (!m_page) {
2822         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2823         return;
2824     }
2825
2826     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2827     switch (action) {
2828     case DragControllerActionEntered:
2829         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData)));
2830         break;
2831
2832     case DragControllerActionUpdated:
2833         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData)));
2834         break;
2835         
2836     case DragControllerActionExited:
2837         m_page->dragController().dragExited(dragData);
2838         break;
2839         
2840     case DragControllerActionPerformDrag: {
2841         ASSERT(!m_pendingDropSandboxExtension);
2842
2843         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2844         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
2845             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
2846                 m_pendingDropExtensionsForFileUpload.append(extension);
2847         }
2848
2849         m_page->dragController().performDrag(dragData);
2850
2851         // If we started loading a local file, the sandbox extension tracker would have adopted this
2852         // pending drop sandbox extension. If not, we'll play it safe and clear it.
2853         m_pendingDropSandboxExtension = nullptr;
2854
2855         m_pendingDropExtensionsForFileUpload.clear();
2856         break;
2857     }
2858
2859     default:
2860         ASSERT_NOT_REACHED();
2861     }
2862 }
2863 #endif
2864
2865 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2866 {
2867     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
2868     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
2869
2870     m_page->dragController().dragEnded();
2871     FrameView* view = m_page->mainFrame().view();
2872     if (!view)
2873         return;
2874     // FIXME: These are fake modifier keys here, but they should be real ones instead.
2875     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2876     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
2877 }
2878
2879 void WebPage::willPerformLoadDragDestinationAction()
2880 {
2881     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2882 }
2883
2884 void WebPage::mayPerformUploadDragDestinationAction()
2885 {
2886     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2887         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
2888     m_pendingDropExtensionsForFileUpload.clear();
2889 }
2890     
2891 #endif // ENABLE(DRAG_SUPPORT)
2892
2893 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2894 {
2895     return m_undoStepMap.get(stepID);
2896 }
2897
2898 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2899 {
2900     m_undoStepMap.set(stepID, entry);
2901 }
2902
2903 void WebPage::removeWebEditCommand(uint64_t stepID)
2904 {
2905     m_undoStepMap.remove(stepID);
2906 }
2907
2908 void WebPage::unapplyEditCommand(uint64_t stepID)
2909 {
2910     WebUndoStep* step = webUndoStep(stepID);
2911     if (!step)
2912         return;
2913
2914     step->step()->unapply();
2915 }
2916
2917 void WebPage::reapplyEditCommand(uint64_t stepID)
2918 {
2919     WebUndoStep* step = webUndoStep(stepID);
2920     if (!step)
2921         return;
2922
2923     m_isInRedo = true;
2924     step->step()->reapply();
2925     m_isInRedo = false;
2926 }
2927
2928 void WebPage::didRemoveEditCommand(uint64_t commandID)
2929 {
2930     removeWebEditCommand(commandID);
2931 }
2932
2933 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2934 {
2935     m_activePopupMenu = menu;
2936 }
2937
2938 #if ENABLE(INPUT_TYPE_COLOR)
2939 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
2940 {
2941     m_activeColorChooser = colorChooser;
2942 }
2943
2944 void WebPage::didEndColorPicker()
2945 {
2946     m_activeColorChooser->didEndChooser();
2947 }
2948
2949 void WebPage::didChooseColor(const WebCore::Color& color)
2950 {
2951     m_activeColorChooser->didChooseColor(color);
2952 }
2953 #endif
2954
2955 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2956 {
2957     m_activeOpenPanelResultListener = openPanelResultListener;
2958 }
2959
2960 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2961 {
2962     return m_page->findString(target, options);
2963 }
2964
2965 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2966 {
2967     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2968 }
2969
2970 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2971 {
2972     m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2973 }
2974
2975 void WebPage::getImageForFindMatch(uint32_t matchIndex)
2976 {
2977     m_findController.getImageForFindMatch(matchIndex);
2978 }
2979
2980 void WebPage::selectFindMatch(uint32_t matchIndex)
2981 {
2982     m_findController.selectFindMatch(matchIndex);
2983 }
2984
2985 void WebPage::hideFindUI()
2986 {
2987     m_findController.hideFindUI();
2988 }
2989
2990 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2991 {
2992     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2993 }
2994
2995 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2996 {
2997     changeSelectedIndex(newIndex);
2998     m_activePopupMenu = 0;
2999 }
3000
3001 void WebPage::changeSelectedIndex(int32_t index)
3002 {
3003     if (!m_activePopupMenu)
3004         return;
3005
3006     m_activePopupMenu->didChangeSelectedIndex(index);
3007 }
3008
3009 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3010 {
3011     if (!m_activeOpenPanelResultListener)
3012         return;
3013
3014     m_activeOpenPanelResultListener->didChooseFiles(files);
3015     m_activeOpenPanelResultListener = 0;
3016 }
3017
3018 void WebPage::didCancelForOpenPanel()
3019 {
3020     m_activeOpenPanelResultListener = 0;
3021 }
3022
3023 #if ENABLE(WEB_PROCESS_SANDBOX)
3024 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3025 {
3026     SandboxExtension::create(handle)->consumePermanently();
3027 }
3028 #endif
3029
3030 #if ENABLE(GEOLOCATION)
3031 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3032 {
3033     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3034 }
3035 #endif
3036
3037 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3038 {
3039     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3040 }
3041
3042 #if !PLATFORM(IOS)
3043 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3044 {
3045     Frame& frame = m_page->focusController().focusedOrMainFrame();
3046     frame.editor().advanceToNextMisspelling(startBeforeSelection);
3047 }
3048 #endif
3049
3050 void WebPage::changeSpellingToWord(const String& word)
3051 {
3052     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3053 }
3054
3055 void WebPage::unmarkAllMisspellings()
3056 {
3057     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3058         if (Document* document = frame->document())
3059             document->markers().removeMarkers(DocumentMarker::Spelling);
3060     }
3061 }
3062
3063 void WebPage::unmarkAllBadGrammar()
3064 {
3065     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3066         if (Document* document = frame->document())
3067             document->markers().removeMarkers(DocumentMarker::Grammar);
3068     }
3069 }
3070
3071 #if USE(APPKIT)
3072 void WebPage::uppercaseWord()
3073 {
3074     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3075 }
3076
3077 void WebPage::lowercaseWord()
3078 {
3079     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3080 }
3081
3082 void WebPage::capitalizeWord()
3083 {
3084     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3085 }
3086 #endif
3087     
3088 void WebPage::setTextForActivePopupMenu(int32_t index)
3089 {
3090     if (!m_activePopupMenu)
3091         return;
3092
3093     m_activePopupMenu->setTextForIndex(index);
3094 }
3095
3096 #if PLATFORM(GTK)
3097 void WebPage::failedToShowPopupMenu()
3098 {
3099     if (!m_activePopupMenu)
3100         return;
3101
3102     m_activePopupMenu->client()->popupDidHide();
3103 }
3104 #endif
3105
3106 #if ENABLE(CONTEXT_MENUS)
3107 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3108 {
3109     if (!m_contextMenu)
3110         return;
3111
3112     m_contextMenu->itemSelected(item);
3113     m_contextMenu = 0;
3114 }
3115 #endif
3116
3117 #if ENABLE(IMAGE_CONTROLS)
3118 void WebPage::replaceControlledImage(const ShareableBitmap::Handle& bitmapHandle)
3119 {
3120     RefPtr<ShareableBitmap> bitmap = ShareableBitmap::create(bitmapHandle);
3121     if (bitmap)
3122         m_contextMenu->replaceControlledImage(bitmap->createImage());
3123 }
3124 #endif
3125
3126 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3127 {
3128     bool selectReplacement = true;
3129     bool smartReplace = false;
3130     return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3131 }
3132
3133 #if !PLATFORM(IOS)
3134 void WebPage::clearSelection()
3135 {
3136     m_page->focusController().focusedOrMainFrame().selection().clear();
3137 }
3138 #endif
3139
3140 bool WebPage::mainFrameHasCustomContentProvider() const
3141 {
3142     if (Frame* frame = mainFrame()) {
3143         WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3144         ASSERT(webFrameLoaderClient);
3145         return webFrameLoaderClient->frameHasCustomContentProvider();
3146     }
3147
3148     return false;
3149 }
3150
3151 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3152 {
3153     m_mimeTypesWithCustomContentProviders.add(mimeType);
3154 }
3155
3156 void WebPage::updateMainFrameScrollOffsetPinning()
3157 {
3158     Frame& frame = m_page->mainFrame();
3159     IntPoint scrollPosition = frame.view()->scrollPosition();
3160     IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3161     IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3162
3163     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3164     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3165     bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3166     bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3167
3168     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3169         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3170         
3171         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3172         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3173         m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3174         m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3175     }
3176 }
3177
3178 void WebPage::mainFrameDidLayout()
3179 {
3180     unsigned pageCount = m_page->pageCount();
3181     if (pageCount != m_cachedPageCount) {
3182         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3183         m_cachedPageCount = pageCount;
3184     }
3185
3186 #if USE(TILED_BACKING_STORE)
3187     if (m_drawingArea && m_drawingArea->layerTreeHost()) {
3188         double red, green, blue, alpha;
3189         m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha);
3190         RGBA32 rgba = makeRGBA32FromFloats(red, green, blue, alpha);
3191         if (m_backgroundColor.rgb() != rgba) {
3192             m_backgroundColor.setRGB(rgba);
3193             m_drawingArea->layerTreeHost()->setBackgroundColor(m_backgroundColor);
3194         }
3195     }
3196 #endif
3197
3198 #if PLATFORM(MAC)
3199     m_viewGestureGeometryCollector.mainFrameDidLayout();
3200 #endif
3201 #if PLATFORM(IOS)
3202     if (FrameView* frameView = mainFrameView()) {
3203         m_viewportConfiguration.setContentsSize(frameView->contentsSize());
3204         viewportConfigurationChanged();
3205     }
3206 #endif
3207 }
3208
3209 void WebPage::addPluginView(PluginView* pluginView)
3210 {
3211     ASSERT(!m_pluginViews.contains(pluginView));
3212
3213     m_pluginViews.add(pluginView);
3214     m_hasSeenPlugin = true;
3215 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3216     LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3217     m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3218 #endif
3219 }
3220
3221 void WebPage::removePluginView(PluginView* pluginView)
3222 {
3223     ASSERT(m_pluginViews.contains(pluginView));
3224
3225     m_pluginViews.remove(pluginView);
3226 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3227     LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3228 #endif
3229 }
3230
3231 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3232 {
3233 #if PLATFORM(COCOA)
3234     m_hasCachedWindowFrame = false;
3235 #endif
3236     send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3237 }
3238
3239 #if PLATFORM(COCOA)
3240 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3241 {
3242     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3243     m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3244     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3245     m_accessibilityPosition = accessibilityViewCoordinates;
3246     
3247     // Tell all our plug-in views that the window and view frames have changed.
3248     for (auto* pluginView : m_pluginViews)
3249         pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3250
3251     m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3252 }
3253 #endif
3254
3255 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3256 {
3257     m_mainFrameIsScrollable = isScrollable;
3258     m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3259
3260     if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3261         frameView->setCanHaveScrollbars(isScrollable);
3262         frameView->setProhibitsScrolling(!isScrollable);
3263     }
3264 }
3265
3266 bool WebPage::windowIsFocused() const
3267 {
3268     return m_page->focusController().isActive();
3269 }
3270
3271 bool WebPage::windowAndWebPageAreFocused() const
3272 {
3273     if (!isVisible())
3274         return false;
3275
3276     return m_page->focusController().isFocused() && m_page->focusController().isActive();
3277 }
3278
3279 void WebPage::didReceiveMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder)
3280 {
3281     if (decoder.messageReceiverName() == Messages::DrawingArea::messageReceiverName()) {
3282         if (m_drawingArea)
3283             m_drawingArea->didReceiveDrawingAreaMessage(connection, decoder);
3284         return;
3285     }
3286
3287 #if USE(TILED_BACKING_STORE)
3288     if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
3289         if (m_drawingArea)
3290             m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
3291         return;
3292     }
3293 #endif
3294     
3295 #if ENABLE(INSPECTOR)
3296     if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
3297         if (WebInspector* inspector = this->inspector())
3298             inspector->didReceiveWebInspectorMessage(connection, decoder);
3299         return;
3300     }
3301 #endif
3302
3303 #if ENABLE(FULLSCREEN_API)
3304     if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
3305         fullScreenManager()->didReceiveMessage(connection, decoder);
3306         return;
3307     }
3308 #endif
3309
3310     didReceiveWebPageMessage(connection, decoder);
3311 }
3312
3313 void WebPage::didReceiveSyncMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder)
3314 {   
3315     didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
3316 }
3317     
3318 InjectedBundleBackForwardList* WebPage::backForwardList()
3319 {
3320     if (!m_backForwardList)
3321         m_backForwardList = InjectedBundleBackForwardList::create(this);
3322     return m_backForwardList.get();
3323 }
3324
3325 #if ENABLE(ASYNC_SCROLLING)
3326 ScrollingCoordinator* WebPage::scrollingCoordinator() const
3327 {
3328     return m_page->scrollingCoordinator();
3329 }
3330 #endif
3331
3332 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3333 {
3334     invalidate();
3335 }
3336
3337 void WebPage::SandboxExtensionTracker::invalidate()
3338 {
3339     m_pendingProvisionalSandboxExtension = nullptr;
3340
3341     if (m_provisionalSandboxExtension) {
3342         m_provisionalSandboxExtension->revoke();
3343         m_provisionalSandboxExtension = nullptr;
3344     }
3345
3346     if (m_committedSandboxExtension) {
3347         m_committedSandboxExtension->revoke();
3348         m_committedSandboxExtension = nullptr;
3349     }
3350 }
3351
3352 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3353 {
3354     setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3355 }
3356
3357 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3358 {
3359     ASSERT_UNUSED(frame, frame->isMainFrame());
3360
3361     setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3362 }
3363
3364 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3365 {
3366     m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;    
3367 }
3368
3369 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3370 {
3371     ASSERT(frame->isMainFrame());
3372
3373     FrameLoader& frameLoader = frame->coreFrame()->loader();
3374     FrameLoadType frameLoadType = frameLoader.loadType();
3375
3376     // If the page is being reloaded, it should reuse whatever extension is committed.
3377     if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
3378         return true;
3379
3380     DocumentLoader* documentLoader = frameLoader.documentLoader();
3381     DocumentLoader* provisionalDocumentLoader = frameLoader.provisionalDocumentLoader();
3382     if (!documentLoader || !provisionalDocumentLoader)
3383         return false;
3384
3385     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3386         return true;
3387
3388     return false;
3389 }
3390
3391 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3392 {
3393     if (!frame->isMainFrame())
3394         return;
3395
3396     // We should only reuse the commited sandbox extension if it is not null. It can be
3397     // null if the last load was for an error page.
3398     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame))
3399         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension;
3400
3401     ASSERT(!m_provisionalSandboxExtension);
3402
3403     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3404     if (!m_provisionalSandboxExtension)
3405         return;
3406
3407     ASSERT(!m_provisionalSandboxExtension || frame->coreFrame()->loader().provisionalDocumentLoader()->url().isLocalFile());
3408
3409     m_provisionalSandboxExtension->consume();
3410 }
3411
3412 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3413 {
3414     if (!frame->isMainFrame())
3415         return;
3416
3417     if (m_committedSandboxExtension)
3418         m_committedSandboxExtension->revoke();
3419
3420     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3421
3422     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started.
3423     // This extension is not cleared, because it does not pertain to the failed load, and will be needed.
3424 }
3425
3426 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3427 {
3428     if (!frame->isMainFrame())
3429         return;
3430
3431     if (!m_provisionalSandboxExtension)
3432         return;
3433
3434     m_provisionalSandboxExtension->revoke();
3435     m_provisionalSandboxExtension = nullptr;
3436
3437     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started
3438     // (notably, if the current one fails because the new one cancels it). This extension is not cleared,
3439     // because it does not pertain to the failed load, and will be needed.
3440 }
3441
3442 bool WebPage::hasLocalDataForURL(const URL& url)
3443 {
3444     if (url.isLocalFile())
3445         return true;
3446
3447     DocumentLoader* documentLoader = m_page->mainFrame().loader().documentLoader();
3448     if (documentLoader && documentLoader->subresource(url))
3449         return true;
3450
3451     return platformHasLocalDataForURL(url);
3452 }
3453
3454 void WebPage::setCustomTextEncodingName(const String& encoding)
3455 {
3456     m_page->mainFrame().loader().reloadWithOverrideEncoding(encoding);
3457 }
3458
3459 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3460 {
3461     WebBackForwardListProxy::removeItem(itemID);
3462 }
3463
3464 #if PLATFORM(COCOA)
3465
3466 bool WebPage::isSpeaking()
3467 {
3468     bool result;
3469     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3470 }
3471
3472 void WebPage::speak(const String& string)
3473 {
3474     send(Messages::WebPageProxy::Speak(string));
3475 }
3476
3477 void WebPage::stopSpeaking()
3478 {
3479     send(Messages::WebPageProxy::StopSpeaking());
3480 }
3481
3482 #endif
3483
3484 #if PLATFORM(MAC)
3485 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3486 {
3487     Document* document = coreFrame->document();
3488     if (!document)
3489         return 0;
3490
3491     if (!document->isPluginDocument())
3492         return 0;
3493
3494     PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
3495     if (!pluginView)
3496         return 0;
3497
3498     return pluginView->pdfDocumentForPrinting();
3499 }
3500 #endif // PLATFORM(MAC)
3501
3502 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3503 {
3504     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3505     if (!frame)
3506         return;
3507
3508     Frame* coreFrame = frame->coreFrame();
3509     if (!coreFrame)
3510         return;
3511
3512 #if PLATFORM(MAC)
3513     if (pdfDocumentForPrintingFrame(coreFrame))
3514         return;
3515 #endif // PLATFORM(MAC)
3516
3517     if (!m_printContext)
3518         m_printContext = adoptPtr(new PrintContext(coreFrame));
3519
3520     drawingArea()->setLayerTreeStateIsFrozen(true);
3521     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3522
3523     float fullPageHeight;
3524     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3525
3526 #if PLATFORM(GTK)
3527     if (!m_printOperation)
3528         m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3529 #endif
3530 }
3531
3532 void WebPage::endPrinting()
3533 {
3534     drawingArea()->setLayerTreeStateIsFrozen(false);
3535     m_printContext = nullptr;
3536 }
3537
3538 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3539 {
3540     Vector<IntRect> resultPageRects;
3541     double resultTotalScaleFactorForPrinting = 1;
3542
3543     beginPrinting(frameID, printInfo);
3544
3545     if (m_printContext) {
3546         resultPageRects = m_printContext->pageRects();
3547         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3548     }
3549 #if PLATFORM(COCOA)
3550     else
3551         computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3552 #endif // PLATFORM(COCOA)
3553
3554     // If we're asked to print, we should actually print at least a blank page.
3555     if (resultPageRects.isEmpty())
3556         resultPageRects.append(IntRect(0, 0, 1, 1));
3557
3558     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3559 }
3560