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