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