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