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