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