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