[MediaStream] Move capture device monitoring to WebKit
[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/PromisedBlobInfo.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     RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes,
1340         MonotonicTime::now(), nullptr, singleClick, screenPoint.x(), screenPoint.y(), documentPoint.x(), documentPoint.y(),
1341 #if ENABLE(POINTER_LOCK)
1342         0, 0,
1343 #endif
1344         false, false, false, false, 0, 0, nullptr, 0, WebCore::NoTap, nullptr);
1345
1346     mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1347 }
1348
1349 void WebPage::stopLoadingFrame(uint64_t frameID)
1350 {
1351     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1352     if (!frame)
1353         return;
1354
1355     corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1356 }
1357
1358 void WebPage::stopLoading()
1359 {
1360     SendStopResponsivenessTimer stopper;
1361
1362     corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1363 }
1364
1365 bool WebPage::defersLoading() const
1366 {
1367     return m_page->defersLoading();
1368 }
1369
1370 void WebPage::setDefersLoading(bool defersLoading)
1371 {
1372     m_page->setDefersLoading(defersLoading);
1373 }
1374
1375 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, SandboxExtension::Handle&& sandboxExtensionHandle)
1376 {
1377     SendStopResponsivenessTimer stopper;
1378
1379     ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1380     m_pendingNavigationID = navigationID;
1381
1382     m_sandboxExtensionTracker.beginReload(m_mainFrame.get(), WTFMove(sandboxExtensionHandle));
1383     corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1384
1385     if (m_pendingNavigationID) {
1386         // This can happen if FrameLoader::reload() returns early because the document URL is empty.
1387         // The reload does nothing so we need to reset the pending navigation. See webkit.org/b/153210.
1388         m_pendingNavigationID = 0;
1389     }
1390 }
1391
1392 void WebPage::goToBackForwardItem(uint64_t navigationID, const BackForwardItemIdentifier& backForwardItemID, FrameLoadType backForwardType, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad)
1393 {
1394     SendStopResponsivenessTimer stopper;
1395
1396     ASSERT(isBackForwardLoadType(backForwardType));
1397
1398     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1399     ASSERT(item);
1400     if (!item)
1401         return;
1402
1403     LOG(Loading, "In WebProcess pid %i, WebPage %" PRIu64 " is navigating to back/forward URL %s", getCurrentProcessID(), m_pageID, item->url().string().utf8().data());
1404
1405     ASSERT(!m_pendingNavigationID);
1406     m_pendingNavigationID = navigationID;
1407
1408     m_page->goToItem(*item, backForwardType, shouldTreatAsContinuingLoad);
1409 }
1410
1411 void WebPage::tryRestoreScrollPosition()
1412 {
1413     m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1414 }
1415
1416 void WebPage::layoutIfNeeded()
1417 {
1418     if (m_mainFrame->coreFrame()->view())
1419         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1420 }
1421
1422 WebPage* WebPage::fromCorePage(Page* page)
1423 {
1424     return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1425 }
1426
1427 void WebPage::setSize(const WebCore::IntSize& viewSize)
1428 {
1429     if (m_viewSize == viewSize)
1430         return;
1431
1432     m_viewSize = viewSize;
1433     FrameView* view = m_page->mainFrame().view();
1434     view->resize(viewSize);
1435     m_drawingArea->setNeedsDisplay();
1436
1437 #if USE(COORDINATED_GRAPHICS)
1438     if (view->useFixedLayout())
1439         sendViewportAttributesChanged(m_page->viewportArguments());
1440 #endif
1441 }
1442
1443 #if USE(COORDINATED_GRAPHICS)
1444 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1445 {
1446     FrameView* view = m_page->mainFrame().view();
1447     ASSERT(view && view->useFixedLayout());
1448
1449     // Viewport properties have no impact on zero sized fixed viewports.
1450     if (m_viewSize.isEmpty())
1451         return;
1452
1453     // Recalculate the recommended layout size, when the available size (device pixel) changes.
1454     Settings& settings = m_page->settings();
1455
1456     int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1457
1458     // If unset  we use the viewport dimensions. This fits with the behavior of desktop browsers.
1459     int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1460     int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1461
1462     ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1463
1464     // If no layout was done yet set contentFixedOrigin to (0,0).
1465     IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1466
1467     // Put the width and height to the viewport width and height. In css units however.
1468     // Use FloatSize to avoid truncated values during scale.
1469     FloatSize contentFixedSize = m_viewSize;
1470
1471 #if ENABLE(CSS_DEVICE_ADAPTATION)
1472     // CSS viewport descriptors might be applied to already affected viewport size
1473     // if the page enables/disables stylesheets, so need to keep initial viewport size.
1474     view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1475 #endif
1476
1477     contentFixedSize.scale(1 / attr.initialScale);
1478     view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1479
1480     attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1481
1482     // This also takes care of the relayout.
1483     setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1484
1485 #if USE(COORDINATED_GRAPHICS_THREADED)
1486     m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1487 #else
1488     send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1489 #endif
1490 }
1491 #endif
1492
1493 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1494 {
1495     FrameView* frameView = m_page->mainFrame().view();
1496
1497     ScrollPosition scrollPosition = frameView->scrollPosition();
1498     ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1499
1500     // If the current scroll position in a direction is the max scroll position 
1501     // we don't want to scroll at all.
1502     IntSize newScrollOffset;
1503     if (scrollPosition.x() < maximumScrollPosition.x())
1504         newScrollOffset.setWidth(scrollOffset.width());
1505     if (scrollPosition.y() < maximumScrollPosition.y())
1506         newScrollOffset.setHeight(scrollOffset.height());
1507
1508     if (newScrollOffset.isZero())
1509         return;
1510
1511     frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1512 }
1513
1514 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1515 {
1516 #if PLATFORM(MAC)
1517     LocalDefaultSystemAppearance localAppearance(m_page->useSystemAppearance(), m_page->useDarkAppearance());
1518 #endif
1519
1520     GraphicsContextStateSaver stateSaver(graphicsContext);
1521     graphicsContext.clip(rect);
1522
1523     m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1524 }
1525
1526 double WebPage::textZoomFactor() const
1527 {
1528     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1529     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1530         if (pluginView->handlesPageScaleFactor())
1531             return pluginView->pageScaleFactor();
1532         return pageScaleFactor();
1533     }
1534
1535     Frame* frame = m_mainFrame->coreFrame();
1536     if (!frame)
1537         return 1;
1538     return frame->textZoomFactor();
1539 }
1540
1541 void WebPage::setTextZoomFactor(double zoomFactor)
1542 {
1543     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1544     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1545         if (pluginView->handlesPageScaleFactor())
1546             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1547         else
1548             scalePage(zoomFactor, IntPoint());
1549         return;
1550     }
1551
1552     Frame* frame = m_mainFrame->coreFrame();
1553     if (!frame)
1554         return;
1555     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1556 }
1557
1558 double WebPage::pageZoomFactor() const
1559 {
1560     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1561     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1562         if (pluginView->handlesPageScaleFactor())
1563             return pluginView->pageScaleFactor();
1564         return pageScaleFactor();
1565     }
1566
1567     Frame* frame = m_mainFrame->coreFrame();
1568     if (!frame)
1569         return 1;
1570     return frame->pageZoomFactor();
1571 }
1572
1573 void WebPage::setPageZoomFactor(double zoomFactor)
1574 {
1575     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1576     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1577         if (pluginView->handlesPageScaleFactor())
1578             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1579         else
1580             scalePage(zoomFactor, IntPoint());
1581         return;
1582     }
1583
1584     Frame* frame = m_mainFrame->coreFrame();
1585     if (!frame)
1586         return;
1587     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1588 }
1589
1590 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1591 {
1592     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1593     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1594         if (pluginView->handlesPageScaleFactor())
1595             pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1596         else
1597             scalePage(pageZoomFactor, IntPoint());
1598         return;
1599     }
1600
1601     Frame* frame = m_mainFrame->coreFrame();
1602     if (!frame)
1603         return;
1604     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1605 }
1606
1607 void WebPage::windowScreenDidChange(uint32_t displayID)
1608 {
1609     m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1610 }
1611
1612 void WebPage::scalePage(double scale, const IntPoint& origin)
1613 {
1614     double totalScale = scale * viewScaleFactor();
1615     bool willChangeScaleFactor = totalScale != totalScaleFactor();
1616
1617 #if PLATFORM(IOS)
1618     if (willChangeScaleFactor) {
1619         if (!m_inDynamicSizeUpdate)
1620             m_dynamicSizeUpdateHistory.clear();
1621         m_scaleWasSetByUIProcess = false;
1622     }
1623 #endif
1624     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1625     if (pluginView && pluginView->handlesPageScaleFactor()) {
1626         // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1627         // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1628         if (m_page->pageScaleFactor() != 1) {
1629             m_page->setPageScaleFactor(1, origin);
1630             for (auto* pluginView : m_pluginViews)
1631                 pluginView->pageScaleFactorDidChange();
1632         }
1633
1634         pluginView->setPageScaleFactor(totalScale, origin);
1635         return;
1636     }
1637
1638     m_page->setPageScaleFactor(totalScale, origin);
1639
1640     // We can't early return before setPageScaleFactor because the origin might be different.
1641     if (!willChangeScaleFactor)
1642         return;
1643
1644     for (auto* pluginView : m_pluginViews)
1645         pluginView->pageScaleFactorDidChange();
1646
1647 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1648     m_drawingArea->deviceOrPageScaleFactorChanged();
1649 #endif
1650
1651     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1652 }
1653
1654 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1655 {
1656     double totalScale = scale * viewScaleFactor();
1657     if (totalScale == totalScaleFactor())
1658         return;
1659
1660     IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1661     double scaleRatio = scale / pageScaleFactor();
1662     scrollPositionAtNewScale.scale(scaleRatio);
1663     scalePage(scale, scrollPositionAtNewScale);
1664 }
1665
1666 double WebPage::totalScaleFactor() const
1667 {
1668     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1669     if (pluginView && pluginView->handlesPageScaleFactor())
1670         return pluginView->pageScaleFactor();
1671
1672     return m_page->pageScaleFactor();
1673 }
1674
1675 double WebPage::pageScaleFactor() const
1676 {
1677     return totalScaleFactor() / viewScaleFactor();
1678 }
1679
1680 double WebPage::viewScaleFactor() const
1681 {
1682     return m_page->viewScaleFactor();
1683 }
1684
1685 void WebPage::scaleView(double scale)
1686 {
1687     if (viewScaleFactor() == scale)
1688         return;
1689
1690     float pageScale = pageScaleFactor();
1691
1692     IntPoint scrollPositionAtNewScale;
1693     if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1694         double scaleRatio = scale / viewScaleFactor();
1695         scrollPositionAtNewScale = mainFrameView->scrollPosition();
1696         scrollPositionAtNewScale.scale(scaleRatio);
1697     }
1698
1699     m_page->setViewScaleFactor(scale);
1700     scalePage(pageScale, scrollPositionAtNewScale);
1701 }
1702
1703 void WebPage::setDeviceScaleFactor(float scaleFactor)
1704 {
1705     if (scaleFactor == m_page->deviceScaleFactor())
1706         return;
1707
1708     m_page->setDeviceScaleFactor(scaleFactor);
1709
1710     // Tell all our plug-in views that the device scale factor changed.
1711 #if PLATFORM(MAC)
1712     for (auto* pluginView : m_pluginViews)
1713         pluginView->setDeviceScaleFactor(scaleFactor);
1714
1715     updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1716 #endif
1717
1718     if (findController().isShowingOverlay()) {
1719         // We must have updated layout to get the selection rects right.
1720         layoutIfNeeded();
1721         findController().deviceScaleFactorDidChange();
1722     }
1723
1724 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1725     m_drawingArea->deviceOrPageScaleFactorChanged();
1726 #endif
1727 }
1728
1729 float WebPage::deviceScaleFactor() const
1730 {
1731     return m_page->deviceScaleFactor();
1732 }
1733
1734 void WebPage::accessibilitySettingsDidChange()
1735 {
1736     m_page->accessibilitySettingsDidChange();
1737 }
1738
1739 #if ENABLE(ACCESSIBILITY_EVENTS)
1740 void WebPage::updateAccessibilityEventsEnabled(bool enabled)
1741 {
1742     m_page->settings().setAccessibilityEventsEnabled(enabled);
1743 }
1744 #endif
1745
1746 void WebPage::setUseFixedLayout(bool fixed)
1747 {
1748     // Do not overwrite current settings if initially setting it to false.
1749     if (m_useFixedLayout == fixed)
1750         return;
1751     m_useFixedLayout = fixed;
1752
1753 #if !PLATFORM(IOS)
1754     m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1755 #endif
1756
1757     FrameView* view = mainFrameView();
1758     if (!view)
1759         return;
1760
1761     view->setUseFixedLayout(fixed);
1762     if (!fixed)
1763         setFixedLayoutSize(IntSize());
1764
1765     send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1766 }
1767
1768 bool WebPage::setFixedLayoutSize(const IntSize& size)
1769 {
1770     FrameView* view = mainFrameView();
1771     if (!view || view->fixedLayoutSize() == size)
1772         return false;
1773
1774     LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " setFixedLayoutSize " << size);
1775     view->setFixedLayoutSize(size);
1776
1777     send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1778     return true;
1779 }
1780
1781 IntSize WebPage::fixedLayoutSize() const
1782 {
1783     FrameView* view = mainFrameView();
1784     if (!view)
1785         return IntSize();
1786     return view->fixedLayoutSize();
1787 }
1788
1789 void WebPage::disabledAdaptationsDidChange(const OptionSet<DisabledAdaptations>& disabledAdaptations)
1790 {
1791 #if PLATFORM(IOS)
1792     if (m_viewportConfiguration.setDisabledAdaptations(disabledAdaptations))
1793         viewportConfigurationChanged();
1794 #else
1795     UNUSED_PARAM(disabledAdaptations);
1796 #endif
1797 }
1798
1799 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
1800 {
1801 #if PLATFORM(IOS)
1802     if (m_viewportConfiguration.setViewportArguments(viewportArguments))
1803         viewportConfigurationChanged();
1804 #endif
1805
1806 #if USE(COORDINATED_GRAPHICS)
1807     FrameView* view = m_page->mainFrame().view();
1808     if (view && view->useFixedLayout())
1809         sendViewportAttributesChanged(viewportArguments);
1810 #if USE(COORDINATED_GRAPHICS_THREADED)
1811     else
1812         m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
1813 #endif
1814 #endif
1815
1816 #if !PLATFORM(IOS) && !USE(COORDINATED_GRAPHICS)
1817     UNUSED_PARAM(viewportArguments);
1818 #endif
1819 }
1820
1821 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1822 {
1823     if (!m_page)
1824         return;
1825     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1826 }
1827
1828 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1829 {
1830     m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1831 }
1832     
1833 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1834 {
1835     m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1836 }
1837     
1838 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1839 {
1840     m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1841 }
1842
1843 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1844 {
1845     if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1846         m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1847 }
1848
1849 void WebPage::setPaginationMode(uint32_t mode)
1850 {
1851     Pagination pagination = m_page->pagination();
1852     pagination.mode = static_cast<Pagination::Mode>(mode);
1853     m_page->setPagination(pagination);
1854 }
1855
1856 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1857 {
1858     Pagination pagination = m_page->pagination();
1859     pagination.behavesLikeColumns = behavesLikeColumns;
1860     m_page->setPagination(pagination);
1861 }
1862
1863 void WebPage::setPageLength(double pageLength)
1864 {
1865     Pagination pagination = m_page->pagination();
1866     pagination.pageLength = pageLength;
1867     m_page->setPagination(pagination);
1868 }
1869
1870 void WebPage::setGapBetweenPages(double gap)
1871 {
1872     Pagination pagination = m_page->pagination();
1873     pagination.gap = gap;
1874     m_page->setPagination(pagination);
1875 }
1876
1877 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
1878 {
1879     m_page->setPaginationLineGridEnabled(lineGridEnabled);
1880 }
1881
1882 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1883 {
1884     auto& webProcess = WebProcess::singleton();
1885     InjectedBundle* injectedBundle = webProcess.injectedBundle();
1886     if (!injectedBundle)
1887         return;
1888
1889     injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1890 }
1891
1892 #if !PLATFORM(IOS)
1893
1894 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
1895 {
1896     if (m_headerBanner)
1897         m_headerBanner->detachFromPage();
1898
1899     m_headerBanner = pageBanner;
1900
1901     if (m_headerBanner)
1902         m_headerBanner->addToPage(PageBanner::Header, this);
1903 }
1904
1905 PageBanner* WebPage::headerPageBanner()
1906 {
1907     return m_headerBanner.get();
1908 }
1909
1910 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
1911 {
1912     if (m_footerBanner)
1913         m_footerBanner->detachFromPage();
1914
1915     m_footerBanner = pageBanner;
1916
1917     if (m_footerBanner)
1918         m_footerBanner->addToPage(PageBanner::Footer, this);
1919 }
1920
1921 PageBanner* WebPage::footerPageBanner()
1922 {
1923     return m_footerBanner.get();
1924 }
1925
1926 void WebPage::hidePageBanners()
1927 {
1928     if (m_headerBanner)
1929         m_headerBanner->hide();
1930     if (m_footerBanner)
1931         m_footerBanner->hide();
1932 }
1933
1934 void WebPage::showPageBanners()
1935 {
1936     if (m_headerBanner)
1937         m_headerBanner->showIfHidden();
1938     if (m_footerBanner)
1939         m_footerBanner->showIfHidden();
1940 }
1941
1942 void WebPage::setHeaderBannerHeightForTesting(int height)
1943 {
1944 #if ENABLE(RUBBER_BANDING)
1945     corePage()->addHeaderWithHeight(height);
1946 #endif
1947 }
1948
1949 void WebPage::setFooterBannerHeightForTesting(int height)
1950 {
1951 #if ENABLE(RUBBER_BANDING)
1952     corePage()->addFooterWithHeight(height);
1953 #endif
1954 }
1955
1956 #endif // !PLATFORM(IOS)
1957
1958 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
1959 {
1960     SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1961     snapshotOptions |= SnapshotOptionsShareable;
1962
1963     RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1964
1965     ShareableBitmap::Handle handle;
1966     if (image)
1967         image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
1968
1969     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1970 }
1971
1972 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1973 {
1974     IntRect snapshotRect = rect;
1975     IntSize bitmapSize = snapshotRect.size();
1976     if (options & SnapshotOptionsPrinting) {
1977         ASSERT(additionalScaleFactor == 1);
1978         Frame* coreFrame = m_mainFrame->coreFrame();
1979         if (!coreFrame)
1980             return nullptr;
1981         bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
1982     } else {
1983         double scaleFactor = additionalScaleFactor;
1984         if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1985             scaleFactor *= corePage()->deviceScaleFactor();
1986         bitmapSize.scale(scaleFactor);
1987     }
1988
1989     return snapshotAtSize(rect, bitmapSize, options);
1990 }
1991
1992 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
1993 {
1994     IntRect snapshotRect = rect;
1995     float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1996     float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1997     float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1998
1999     if (options & SnapshotOptionsPrinting) {
2000         PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
2001         return;
2002     }
2003
2004     Color documentBackgroundColor = frameView.documentBackgroundColor();
2005     Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
2006     graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
2007
2008     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2009         double deviceScaleFactor = frame.page()->deviceScaleFactor();
2010         graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
2011         scaleFactor /= deviceScaleFactor;
2012     }
2013
2014     graphicsContext.scale(scaleFactor);
2015     graphicsContext.translate(-snapshotRect.location());
2016
2017     FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
2018     if (options & SnapshotOptionsExcludeSelectionHighlighting)
2019         shouldPaintSelection = FrameView::ExcludeSelection;
2020
2021     FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
2022     if (options & SnapshotOptionsInViewCoordinates)
2023         coordinateSpace = FrameView::ViewCoordinates;
2024
2025     frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
2026
2027     if (options & SnapshotOptionsPaintSelectionRectangle) {
2028         FloatRect selectionRectangle = frame.selection().selectionBounds();
2029         graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
2030         graphicsContext.strokeRect(selectionRectangle, 1);
2031     }
2032 }
2033
2034 static ShareableBitmap::Configuration snapshotOptionsToBitmapConfiguration(SnapshotOptions options, WebPage& page)
2035 {
2036     ShareableBitmap::Configuration configuration;
2037 #if USE(CG)
2038     if (options & SnapshotOptionsUseScreenColorSpace)
2039         configuration.colorSpace.cgColorSpace = screenColorSpace(page.corePage()->mainFrame().view());
2040 #endif
2041     return configuration;
2042 }
2043
2044 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2045 {
2046     Frame* coreFrame = m_mainFrame->coreFrame();
2047     if (!coreFrame)
2048         return nullptr;
2049
2050     FrameView* frameView = coreFrame->view();
2051     if (!frameView)
2052         return nullptr;
2053
2054     auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2055     if (!snapshot)
2056         return nullptr;
2057     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2058
2059     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2060
2061     return snapshot;
2062 }
2063
2064 #if USE(CF)
2065 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2066 {
2067     Frame* coreFrame = m_mainFrame->coreFrame();
2068     if (!coreFrame)
2069         return nullptr;
2070
2071     FrameView* frameView = coreFrame->view();
2072     if (!frameView)
2073         return nullptr;
2074
2075     auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2076
2077 #if USE(CG)
2078     auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2079     auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2080     auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2081
2082     CGPDFContextBeginPage(pdfContext.get(), nullptr);
2083
2084     GraphicsContext graphicsContext { pdfContext.get() };
2085     graphicsContext.scale({ 1, -1 });
2086     graphicsContext.translate(0, -bitmapSize.height());
2087     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2088
2089     CGPDFContextEndPage(pdfContext.get());
2090     CGPDFContextClose(pdfContext.get());
2091 #endif
2092
2093     return WTFMove(data);
2094 }
2095 #endif
2096
2097 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2098 {
2099     Frame* coreFrame = m_mainFrame->coreFrame();
2100     if (!coreFrame)
2101         return nullptr;
2102
2103     FrameView* frameView = coreFrame->view();
2104     if (!frameView)
2105         return nullptr;
2106
2107     if (!node.renderer())
2108         return nullptr;
2109
2110     LayoutRect topLevelRect;
2111     IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2112     if (snapshotRect.isEmpty())
2113         return nullptr;
2114
2115     double scaleFactor = 1;
2116     IntSize snapshotSize = snapshotRect.size();
2117     unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2118     if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2119         scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2120         snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2121     }
2122
2123     auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2124     if (!snapshot)
2125         return nullptr;
2126     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2127
2128     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2129         double deviceScaleFactor = corePage()->deviceScaleFactor();
2130         graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2131         scaleFactor /= deviceScaleFactor;
2132     }
2133
2134     graphicsContext->scale(scaleFactor);
2135     graphicsContext->translate(-snapshotRect.location());
2136
2137     Color savedBackgroundColor = frameView->baseBackgroundColor();
2138     frameView->setBaseBackgroundColor(Color::transparent);
2139     frameView->setNodeToDraw(&node);
2140
2141     frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2142
2143     frameView->setBaseBackgroundColor(savedBackgroundColor);
2144     frameView->setNodeToDraw(nullptr);
2145
2146     return snapshot;
2147 }
2148
2149 void WebPage::pageDidScroll()
2150 {
2151 #if PLATFORM(IOS)
2152     if (!m_inDynamicSizeUpdate)
2153         m_dynamicSizeUpdateHistory.clear();
2154 #endif
2155     m_uiClient->pageDidScroll(this);
2156
2157     m_pageScrolledHysteresis.impulse();
2158
2159     send(Messages::WebPageProxy::PageDidScroll());
2160 }
2161
2162 void WebPage::pageStoppedScrolling()
2163 {
2164     // Maintain the current history item's scroll position up-to-date.
2165     if (Frame* frame = m_mainFrame->coreFrame())
2166         frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2167 }
2168
2169 #if ENABLE(CONTEXT_MENUS)
2170 WebContextMenu* WebPage::contextMenu()
2171 {
2172     if (!m_contextMenu)
2173         m_contextMenu = WebContextMenu::create(this);
2174     return m_contextMenu.get();
2175 }
2176
2177 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2178 {
2179     corePage()->contextMenuController().clearContextMenu();
2180
2181     // Simulate a mouse click to generate the correct menu.
2182     PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2183     corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2184     bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2185     auto* menu = handled ? contextMenu() : nullptr;
2186     PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2187     corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2188
2189     return menu;
2190 }
2191 #endif
2192
2193 // Events 
2194
2195 static const WebEvent* g_currentEvent = 0;
2196
2197 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2198 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2199 // platform events passed to the event handler code.
2200 const WebEvent* WebPage::currentEvent()
2201 {
2202     return g_currentEvent;
2203 }
2204
2205 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
2206 {
2207     auto* drawingArea = this->drawingArea();
2208     if (!drawingArea)
2209         return;
2210
2211     drawingArea->setLayerTreeStateIsFrozen(frozen);
2212 }
2213
2214 void WebPage::callVolatilityCompletionHandlers(bool succeeded)
2215 {
2216     auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2217     for (auto& completionHandler : completionHandlers)
2218         completionHandler(succeeded);
2219 }
2220
2221 void WebPage::layerVolatilityTimerFired()
2222 {
2223     Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2224     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2225     if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2226         m_layerVolatilityTimer.stop();
2227         if (didSucceed)
2228             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Succeeded in marking layers as volatile", this);
2229         else
2230             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Failed to mark layers as volatile within %gms", this, maximumLayerVolatilityTimerInterval.milliseconds());
2231         callVolatilityCompletionHandlers(didSucceed);
2232         return;
2233     }
2234
2235     RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.milliseconds());
2236     m_layerVolatilityTimer.startRepeating(newInterval);
2237 }
2238
2239 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2240 {
2241     return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2242 }
2243
2244 void WebPage::markLayersVolatile(WTF::Function<void (bool)>&& completionHandler)
2245 {
2246     RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2247
2248     if (m_layerVolatilityTimer.isActive())
2249         m_layerVolatilityTimer.stop();
2250
2251     if (completionHandler)
2252         m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2253
2254     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2255     if (didSucceed || m_isSuspendedUnderLock) {
2256         if (didSucceed)
2257             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2258         else {
2259             // 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.
2260             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2261         }
2262         callVolatilityCompletionHandlers(didSucceed);
2263         return;
2264     }
2265
2266     RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.milliseconds());
2267     m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2268 }
2269
2270 void WebPage::cancelMarkLayersVolatile()
2271 {
2272     RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2273     m_layerVolatilityTimer.stop();
2274     m_markLayersAsVolatileCompletionHandlers.clear();
2275 }
2276
2277 class CurrentEvent {
2278 public:
2279     explicit CurrentEvent(const WebEvent& event)
2280         : m_previousCurrentEvent(g_currentEvent)
2281     {
2282         g_currentEvent = &event;
2283     }
2284
2285     ~CurrentEvent()
2286     {
2287         g_currentEvent = m_previousCurrentEvent;
2288     }
2289
2290 private:
2291     const WebEvent* m_previousCurrentEvent;
2292 };
2293
2294 #if ENABLE(CONTEXT_MENUS)
2295 static bool isContextClick(const PlatformMouseEvent& event)
2296 {
2297 #if PLATFORM(COCOA)
2298     return WebEventFactory::shouldBeHandledAsContextClick(event);
2299 #else
2300     return event.button() == WebCore::RightButton;
2301 #endif
2302 }
2303
2304 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2305 {
2306     IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2307     HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2308
2309     Frame* frame = &page->corePage()->mainFrame();
2310     if (result.innerNonSharedNode())
2311         frame = result.innerNonSharedNode()->document().frame();
2312
2313     bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2314     if (handled)
2315         page->contextMenu()->show();
2316
2317     return handled;
2318 }
2319
2320 void WebPage::contextMenuForKeyEvent()
2321 {
2322     corePage()->contextMenuController().clearContextMenu();
2323
2324     Frame& frame = m_page->focusController().focusedOrMainFrame();
2325     bool handled = frame.eventHandler().sendContextMenuEventForKey();
2326     if (handled)
2327         contextMenu()->show();
2328 }
2329 #endif
2330
2331 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2332 {
2333     Frame& frame = page->corePage()->mainFrame();
2334     if (!frame.view())
2335         return false;
2336
2337     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2338
2339     switch (platformMouseEvent.type()) {
2340         case PlatformEvent::MousePressed: {
2341 #if ENABLE(CONTEXT_MENUS)
2342             if (isContextClick(platformMouseEvent))
2343                 page->corePage()->contextMenuController().clearContextMenu();
2344 #endif
2345
2346             bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2347 #if ENABLE(CONTEXT_MENUS)
2348             if (isContextClick(platformMouseEvent))
2349                 handled = handleContextMenuEvent(platformMouseEvent, page);
2350 #endif
2351             return handled;
2352         }
2353         case PlatformEvent::MouseReleased:
2354             return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2355
2356         case PlatformEvent::MouseMoved:
2357 #if PLATFORM(COCOA)
2358             // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2359             // button is currently pressed. It is possible that neither of those things will be true since on
2360             // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2361             // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2362             // efficient scrollbars-only version of the event.
2363             if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2364                 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2365 #endif
2366             return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2367
2368         case PlatformEvent::MouseForceChanged:
2369         case PlatformEvent::MouseForceDown:
2370         case PlatformEvent::MouseForceUp:
2371             return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2372
2373         default:
2374             ASSERT_NOT_REACHED();
2375             return false;
2376     }
2377 }
2378
2379 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2380 {
2381     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2382
2383     m_userActivityHysteresis.impulse();
2384
2385     bool shouldHandleEvent = true;
2386
2387 #if ENABLE(CONTEXT_MENUS)
2388     // Don't try to handle any pending mouse events if a context menu is showing.
2389     if (m_isShowingContextMenu)
2390         shouldHandleEvent = false;
2391 #endif
2392 #if ENABLE(DRAG_SUPPORT)
2393     if (m_isStartingDrag)
2394         shouldHandleEvent = false;
2395 #endif
2396
2397     if (!shouldHandleEvent) {
2398         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2399         return;
2400     }
2401
2402     bool handled = false;
2403
2404 #if !PLATFORM(IOS)
2405     if (!handled && m_headerBanner)
2406         handled = m_headerBanner->mouseEvent(mouseEvent);
2407     if (!handled && m_footerBanner)
2408         handled = m_footerBanner->mouseEvent(mouseEvent);
2409 #endif // !PLATFORM(IOS)
2410
2411     if (!handled) {
2412         CurrentEvent currentEvent(mouseEvent);
2413         handled = handleMouseEvent(mouseEvent, this);
2414     }
2415
2416     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2417 }
2418
2419 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2420 {
2421     Frame& frame = page->mainFrame();
2422     if (!frame.view())
2423         return false;
2424
2425     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2426     return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2427 }
2428
2429 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2430 {
2431     m_userActivityHysteresis.impulse();
2432
2433     CurrentEvent currentEvent(wheelEvent);
2434
2435     bool handled = handleWheelEvent(wheelEvent, m_page.get());
2436
2437     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2438 }
2439
2440 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2441 {
2442     if (!page->mainFrame().view())
2443         return false;
2444
2445     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2446         return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2447     return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2448 }
2449
2450 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2451 {
2452     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2453
2454     m_userActivityHysteresis.impulse();
2455
2456     CurrentEvent currentEvent(keyboardEvent);
2457
2458     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2459     // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2460     if (!handled)
2461         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2462
2463     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2464 }
2465
2466 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2467 {
2468     bool isEnabled = false;
2469     int32_t state = 0;
2470     Frame& frame = m_page->focusController().focusedOrMainFrame();
2471     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2472         isEnabled = pluginView->isEditingCommandEnabled(commandName);
2473     else {
2474         Editor::Command command = frame.editor().command(commandName);
2475         state = command.state();
2476         isEnabled = command.isSupported() && command.isEnabled();
2477     }
2478
2479     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2480 }
2481
2482 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2483 {
2484     executeEditingCommand(commandName, argument);
2485 }
2486
2487 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest, WebBackForwardListProxy::OverwriteExistingItem overwrite)
2488 {
2489     for (const auto& itemState : itemStates) {
2490         auto historyItem = toHistoryItem(itemState);
2491         historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2492         static_cast<WebBackForwardListProxy*>(corePage()->backForward().client())->addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, overwrite);
2493     }
2494 }
2495
2496 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2497 {
2498     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes, WebBackForwardListProxy::OverwriteExistingItem::No);
2499 }
2500
2501 void WebPage::updateBackForwardListForReattach(const Vector<WebKit::BackForwardListItemState>& itemStates)
2502 {
2503     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2504 }
2505
2506 #if ENABLE(TOUCH_EVENTS)
2507 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2508 {
2509     if (!page->mainFrame().view())
2510         return false;
2511
2512     return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2513 }
2514 #endif
2515
2516 #if ENABLE(IOS_TOUCH_EVENTS)
2517 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2518 {
2519     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2520
2521     m_lastInteractionLocation = touchEvent.position();
2522     CurrentEvent currentEvent(touchEvent);
2523     handled = handleTouchEvent(touchEvent, m_page.get());
2524     updatePotentialTapSecurityOrigin(touchEvent, handled);
2525 }
2526
2527 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2528 {
2529     EventDispatcher::TouchEventQueue queuedEvents;
2530     WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2531     dispatchAsynchronousTouchEvents(queuedEvents);
2532
2533     dispatchTouchEvent(touchEvent, handled);
2534 }
2535
2536 void WebPage::updatePotentialTapSecurityOrigin(const WebTouchEvent& touchEvent, bool wasHandled)
2537 {
2538     if (wasHandled)
2539         return;
2540
2541     if (!touchEvent.isPotentialTap())
2542         return;
2543
2544     if (touchEvent.type() != WebEvent::TouchStart)
2545         return;
2546
2547     auto& mainFrame = m_page->mainFrame();
2548     auto document = mainFrame.document();
2549     if (!document)
2550         return;
2551
2552     if (!document->handlingTouchEvent())
2553         return;
2554
2555     Frame* touchEventTargetFrame = &mainFrame;
2556     while (auto subframe = touchEventTargetFrame->eventHandler().touchEventTargetSubframe())
2557         touchEventTargetFrame = subframe;
2558
2559     auto& touches = touchEventTargetFrame->eventHandler().touches();
2560     if (touches.isEmpty())
2561         return;
2562
2563     ASSERT(touches.size() == 1);
2564
2565     if (auto targetDocument = touchEventTargetFrame->document())
2566         m_potentialTapSecurityOrigin = &targetDocument->securityOrigin();
2567 }
2568 #elif ENABLE(TOUCH_EVENTS)
2569 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2570 {
2571     CurrentEvent currentEvent(touchEvent);
2572
2573     bool handled = handleTouchEvent(touchEvent, m_page.get());
2574
2575     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2576 }
2577 #endif
2578
2579 #if ENABLE(MAC_GESTURE_EVENTS)
2580 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2581 {
2582     if (!page->mainFrame().view())
2583         return false;
2584
2585     return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2586 }
2587
2588 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2589 {
2590     CurrentEvent currentEvent(gestureEvent);
2591     bool handled = handleGestureEvent(gestureEvent, m_page.get());
2592     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2593 }
2594 #endif
2595
2596 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2597 {
2598     return page->userInputBridge().scrollRecursively(direction, granularity);
2599 }
2600
2601 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2602 {
2603     return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2604 }
2605
2606 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2607 {
2608     return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2609 }
2610
2611 void WebPage::centerSelectionInVisibleArea()
2612 {
2613     Frame& frame = m_page->focusController().focusedOrMainFrame();
2614     frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2615     findController().showFindIndicatorInSelection();
2616 }
2617
2618 bool WebPage::isControlledByAutomation() const
2619 {
2620     return m_page->isControlledByAutomation();
2621 }
2622
2623 void WebPage::setControlledByAutomation(bool controlled)
2624 {
2625     m_page->setControlledByAutomation(controlled);
2626 }
2627
2628 void WebPage::insertNewlineInQuotedContent()
2629 {
2630     Frame& frame = m_page->focusController().focusedOrMainFrame();
2631     if (frame.selection().isNone())
2632         return;
2633     frame.editor().insertParagraphSeparatorInQuotedContent();
2634 }
2635
2636 #if ENABLE(REMOTE_INSPECTOR)
2637 void WebPage::setAllowsRemoteInspection(bool allow)
2638 {
2639     m_page->setRemoteInspectionAllowed(allow);
2640 }
2641
2642 void WebPage::setRemoteInspectionNameOverride(const String& name)
2643 {
2644     m_page->setRemoteInspectionNameOverride(name);
2645 }
2646 #endif
2647
2648 void WebPage::setDrawsBackground(bool drawsBackground)
2649 {
2650     if (m_drawsBackground == drawsBackground)
2651         return;
2652
2653     m_drawsBackground = drawsBackground;
2654
2655     if (FrameView* frameView = mainFrameView()) {
2656         Color backgroundColor = drawsBackground ? Color::white : Color::transparent;
2657         bool isTransparent = !drawsBackground;
2658         frameView->updateBackgroundRecursively(backgroundColor, isTransparent);
2659     }
2660
2661     m_drawingArea->pageBackgroundTransparencyChanged();
2662     m_drawingArea->setNeedsDisplay();
2663 }
2664
2665 #if PLATFORM(COCOA)
2666 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
2667 {
2668     if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
2669         LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
2670         return;
2671     }
2672
2673     m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
2674
2675     setTopContentInset(contentInset);
2676
2677     deallocateSendRightSafely(fencePort.port());
2678 }
2679 #endif
2680
2681 void WebPage::setTopContentInset(float contentInset)
2682 {
2683     if (contentInset == m_page->topContentInset())
2684         return;
2685
2686     m_page->setTopContentInset(contentInset);
2687
2688     for (auto* pluginView : m_pluginViews)
2689         pluginView->topContentInsetDidChange();
2690 }
2691
2692 void WebPage::viewWillStartLiveResize()
2693 {
2694     if (!m_page)
2695         return;
2696
2697     // FIXME: This should propagate to all ScrollableAreas.
2698     Frame& frame = m_page->focusController().focusedOrMainFrame();
2699     if (FrameView* view = frame.view())
2700         view->willStartLiveResize();
2701 }
2702
2703 void WebPage::viewWillEndLiveResize()
2704 {
2705     if (!m_page)
2706         return;
2707
2708     // FIXME: This should propagate to all ScrollableAreas.
2709     Frame& frame = m_page->focusController().focusedOrMainFrame();
2710     if (FrameView* view = frame.view())
2711         view->willEndLiveResize();
2712 }
2713
2714 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
2715 {
2716     if (!m_page)
2717         return;
2718
2719     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2720
2721     Frame& frame = m_page->focusController().focusedOrMainFrame();
2722     frame.document()->setFocusedElement(0);
2723
2724     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2725         PlatformKeyboardEvent platformEvent(platform(event));
2726         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2727         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
2728
2729         send(Messages::WebPageProxy::VoidCallback(callbackID));
2730         return;
2731     }
2732
2733     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
2734     send(Messages::WebPageProxy::VoidCallback(callbackID));
2735 }
2736
2737 void WebPage::setCanStartMediaTimerFired()
2738 {
2739     if (m_page)
2740         m_page->setCanStartMedia(true);
2741 }
2742
2743 void WebPage::updateIsInWindow(bool isInitialState)
2744 {
2745     bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
2746
2747     if (!isInWindow) {
2748         m_setCanStartMediaTimer.stop();
2749         m_page->setCanStartMedia(false);
2750         
2751         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2752         if (!isInitialState)
2753             WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2754     } else {
2755         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2756         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2757         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2758         if (m_mayStartMediaWhenInWindow)
2759             m_setCanStartMediaTimer.startOneShot(0_s);
2760
2761         WebProcess::singleton().pageDidEnterWindow(m_pageID);
2762     }
2763
2764     if (isInWindow)
2765         layoutIfNeeded();
2766 }
2767
2768 void WebPage::visibilityDidChange()
2769 {
2770     bool isVisible = m_activityState.contains(ActivityState::IsVisible);
2771     if (!isVisible) {
2772         // We save the document / scroll state when backgrounding a tab so that we are able to restore it
2773         // if it gets terminated while in the background.
2774         if (auto* frame = m_mainFrame->coreFrame())
2775             frame->loader().history().saveDocumentAndScrollState();
2776     }
2777 }
2778
2779 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
2780 {
2781     LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
2782
2783     auto changed = m_activityState ^ activityState;
2784     m_activityState = activityState;
2785
2786     if (changed)
2787         updateThrottleState();
2788
2789     {
2790         SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
2791         m_page->setActivityState(activityState);
2792     }
2793     
2794     for (auto* pluginView : m_pluginViews)
2795         pluginView->activityStateDidChange(changed);
2796
2797     m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
2798     WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
2799
2800     if (changed & ActivityState::IsInWindow)
2801         updateIsInWindow();
2802
2803     if (changed & ActivityState::IsVisible)
2804         visibilityDidChange();
2805 }
2806
2807 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
2808 {
2809     m_layerHostingMode = layerHostingMode;
2810
2811     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2812
2813     for (auto* pluginView : m_pluginViews)
2814         pluginView->setLayerHostingMode(m_layerHostingMode);
2815 }
2816
2817 void WebPage::setSessionID(PAL::SessionID sessionID)
2818 {
2819     if (sessionID.isEphemeral())
2820         WebProcess::singleton().addWebsiteDataStore(WebsiteDataStoreParameters::privateSessionParameters(sessionID));
2821     m_page->setSessionID(sessionID);
2822 }
2823
2824 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, std::optional<WebsitePoliciesData>&& websitePolicies)
2825 {
2826     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2827     if (!frame)
2828         return;
2829     frame->didReceivePolicyDecision(listenerID, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
2830 }
2831
2832 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
2833 {
2834     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2835     if (!frame)
2836         return;
2837     frame->continueWillSubmitForm(listenerID);
2838 }
2839
2840 void WebPage::didStartPageTransition()
2841 {
2842     m_drawingArea->setLayerTreeStateIsFrozen(true);
2843
2844 #if PLATFORM(MAC)
2845     bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
2846 #endif
2847     m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
2848     m_isAssistingNodeDueToUserInteraction = false;
2849     m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
2850 #if PLATFORM(MAC)
2851     if (hasPreviouslyFocusedDueToUserInteraction)
2852         send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
2853     if (m_needsHiddenContentEditableQuirk) {
2854         m_needsHiddenContentEditableQuirk = false;
2855         send(Messages::WebPageProxy::SetNeedsHiddenContentEditableQuirk(m_needsHiddenContentEditableQuirk));
2856     }
2857     if (m_needsPlainTextQuirk) {
2858         m_needsPlainTextQuirk = false;
2859         send(Messages::WebPageProxy::SetNeedsPlainTextQuirk(m_needsPlainTextQuirk));
2860     }
2861 #endif
2862 }
2863
2864 void WebPage::didCompletePageTransition()
2865 {
2866     m_drawingArea->setLayerTreeStateIsFrozen(false);
2867 }
2868
2869 void WebPage::show()
2870 {
2871     send(Messages::WebPageProxy::ShowPage());
2872 }
2873
2874 String WebPage::userAgent(const URL& webCoreURL) const
2875 {
2876     return userAgent(nullptr, webCoreURL);
2877 }
2878
2879 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2880 {
2881     if (frame) {
2882         String userAgent = m_loaderClient->userAgentForURL(*frame, webcoreURL);
2883         if (!userAgent.isEmpty())
2884             return userAgent;
2885     }
2886
2887     String userAgent = platformUserAgent(webcoreURL);
2888     if (!userAgent.isEmpty())
2889         return userAgent;
2890     return m_userAgent;
2891 }
2892     
2893 void WebPage::setUserAgent(const String& userAgent)
2894 {
2895     if (m_userAgent == userAgent)
2896         return;
2897
2898     m_userAgent = userAgent;
2899
2900     if (m_page)
2901         m_page->userAgentChanged();
2902 }
2903
2904 void WebPage::suspendActiveDOMObjectsAndAnimations()
2905 {
2906     m_page->suspendActiveDOMObjectsAndAnimations();
2907 }
2908
2909 void WebPage::resumeActiveDOMObjectsAndAnimations()
2910 {
2911     m_page->resumeActiveDOMObjectsAndAnimations();
2912 }
2913
2914 IntPoint WebPage::screenToRootView(const IntPoint& point)
2915 {
2916     IntPoint windowPoint;
2917     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2918     return windowPoint;
2919 }
2920     
2921 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2922 {
2923     IntRect screenRect;
2924     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect), Seconds::infinity(), IPC::SendSyncOption::DoNotProcessIncomingMessagesWhenWaitingForSyncReply);
2925     return screenRect;
2926 }
2927     
2928 #if PLATFORM(IOS)
2929 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2930 {
2931     IntPoint windowPoint;
2932     sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2933     return windowPoint;
2934 }
2935
2936 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2937 {
2938     IntRect screenRect;
2939     sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2940     return screenRect;
2941 }
2942 #endif
2943
2944 KeyboardUIMode WebPage::keyboardUIMode()
2945 {
2946     bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
2947     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2948 }
2949
2950 void WebPage::runJavaScript(const String& script, bool forceUserGesture, std::optional<String> worldName, CallbackID callbackID)
2951 {
2952     // NOTE: We need to be careful when running scripts that the objects we depend on don't
2953     // disappear during script execution.
2954
2955     RefPtr<SerializedScriptValue> serializedResultValue;
2956     JSLockHolder lock(commonVM());
2957     bool hadException = true;
2958     ExceptionDetails details;
2959     auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
2960     if (world) {
2961         if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
2962             hadException = false;
2963             serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
2964                 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
2965         }
2966     }
2967
2968     IPC::DataReference dataReference;
2969     if (serializedResultValue)
2970         dataReference = serializedResultValue->data();
2971     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
2972 }
2973
2974 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
2975 {
2976     runJavaScript(script, forceUserGesture, std::nullopt, callbackID);
2977 }
2978
2979 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
2980 {
2981     runJavaScript(script, forceUserGesture, worldName, callbackID);
2982 }
2983
2984 void WebPage::getContentsAsString(CallbackID callbackID)
2985 {
2986     String resultString = m_mainFrame->contentsAsString();
2987     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2988 }
2989
2990 #if ENABLE(MHTML)
2991 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
2992 {
2993     auto buffer = MHTMLArchive::generateMHTMLData(m_page.get());
2994
2995     // FIXME: Use SharedBufferDataReference.
2996     IPC::DataReference dataReference;
2997     dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2998     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2999 }
3000 #endif
3001
3002 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3003 {
3004     String resultString = renderTreeExternalRepresentation();
3005     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3006 }
3007
3008 static Frame* frameWithSelection(Page* page)
3009 {
3010     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3011         if (frame->selection().isRange())
3012             return frame;
3013     }
3014
3015     return 0;
3016 }
3017
3018 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3019 {
3020 #if PLATFORM(COCOA)
3021     RetainPtr<CFDataRef> data;
3022     if (Frame* frame = frameWithSelection(m_page.get()))
3023         data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3024 #endif
3025
3026     IPC::DataReference dataReference;
3027 #if PLATFORM(COCOA)
3028     if (data)
3029         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
3030 #endif
3031     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3032 }
3033
3034 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3035 {
3036     WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3037     String resultString = focusedOrMainFrame->selectionAsString();
3038     if (resultString.isEmpty())
3039         resultString = focusedOrMainFrame->contentsAsString();
3040     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3041 }
3042
3043 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3044 {
3045     String resultString;
3046     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3047        resultString = frame->source();
3048
3049     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3050 }
3051
3052 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3053 {
3054     RefPtr<SharedBuffer> buffer;
3055     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3056         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3057             buffer = pluginView->liveResourceData();
3058         if (!buffer) {
3059             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3060                 buffer = loader->mainResourceData();
3061         }
3062     }
3063
3064     // FIXME: Use SharedBufferDataReference.
3065     IPC::DataReference dataReference;
3066     if (buffer)
3067         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
3068     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3069 }
3070
3071 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3072 {
3073     DocumentLoader* loader = frame->loader().documentLoader();
3074     if (!loader)
3075         return nullptr;
3076
3077     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3078     if (!subresource)
3079         return nullptr;
3080
3081     return &subresource->data();
3082 }
3083
3084 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3085 {
3086     RefPtr<SharedBuffer> buffer;
3087     if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3088         URL resourceURL(URL(), resourceURLString);
3089         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3090     }
3091
3092     // FIXME: Use SharedBufferDataReference.
3093     IPC::DataReference dataReference;
3094     if (buffer)
3095         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
3096     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3097 }
3098
3099 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3100 {
3101 #if PLATFORM(COCOA)
3102     RetainPtr<CFDataRef> data;
3103     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3104         data = frame->webArchiveData(nullptr, nullptr);
3105 #else
3106     UNUSED_PARAM(frameID);
3107 #endif
3108
3109     IPC::DataReference dataReference;
3110 #if PLATFORM(COCOA)
3111     if (data)
3112         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
3113 #endif
3114     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3115 }
3116
3117 void WebPage::forceRepaintWithoutCallback()
3118 {
3119     m_drawingArea->forceRepaint();
3120 }
3121
3122 void WebPage::forceRepaint(CallbackID callbackID)
3123 {
3124     if (m_drawingArea->forceRepaintAsync(callbackID))
3125         return;
3126
3127     forceRepaintWithoutCallback();
3128     send(Messages::WebPageProxy::VoidCallback(callbackID));
3129 }
3130
3131 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3132 {
3133     WebPreferencesStore::removeTestRunnerOverrides();
3134     updatePreferences(store);
3135 }
3136
3137 void WebPage::updatePreferences(const WebPreferencesStore& store)
3138 {
3139     updatePreferencesGenerated(store);
3140
3141     Settings& settings = m_page->settings();
3142
3143     bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3144     settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3145     settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3146     settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3147     settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3148     settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3149     settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3150     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3151     settings.setFrameFlattening(static_cast<WebCore::FrameFlattening>(store.getUInt32ValueForKey(WebPreferencesKey::frameFlatteningKey())));
3152     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3153 #if ENABLE(DATA_DETECTION)
3154     settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3155 #endif
3156
3157     DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3158
3159     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3160     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3161     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3162     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3163
3164     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3165     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3166
3167     if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3168         setSessionID(PAL::SessionID::legacyPrivateSessionID());
3169     else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3170         setSessionID(PAL::SessionID::defaultSessionID());
3171
3172     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3173     if (m_processSuppressionEnabled != processSuppressionEnabled) {
3174         m_processSuppressionEnabled = processSuppressionEnabled;
3175         updateThrottleState();
3176     }
3177
3178 #if PLATFORM(COCOA)
3179     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3180 #endif
3181 #if ENABLE(PAYMENT_REQUEST)
3182     settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3183 #endif
3184
3185     // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3186     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3187
3188 #if PLATFORM(IOS)
3189     m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3190     m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3191     setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3192
3193     settings.setUseImageDocumentForSubframePDF(true);
3194 #if HAVE(AVKIT)
3195     DeprecatedGlobalSettings::setAVKitEnabled(true);
3196 #endif
3197 #endif
3198
3199 #if ENABLE(SERVICE_WORKER)
3200     if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3201         ASSERT(parentProcessHasServiceWorkerEntitlement());
3202         if (!parentProcessHasServiceWorkerEntitlement())
3203             RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3204     }
3205 #endif
3206
3207     settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3208
3209     if (m_drawingArea)
3210         m_drawingArea->updatePreferences(store);
3211 }
3212
3213 #if ENABLE(DATA_DETECTION)
3214 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3215 {
3216     DataDetectionResult dataDetectionResult;
3217     dataDetectionResult.results = detectionResults;
3218     send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3219 }
3220 #endif
3221
3222 #if PLATFORM(COCOA)
3223 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3224 {
3225     FrameView* frameView = corePage()->mainFrame().view();
3226     if (!frameView)
3227         return;
3228
3229     layerTransaction.setContentsSize(frameView->contentsSize());
3230     layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3231     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3232     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3233     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3234
3235     layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3236     layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3237     layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3238
3239 #if PLATFORM(IOS)
3240     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3241     layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3242     layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3243     layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3244     layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3245     layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3246     layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3247     layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3248     layerTransaction.setIsInStableState(m_isInStableState);
3249     layerTransaction.setAllowsUserScaling(allowsUserScaling());
3250     if (m_pendingDynamicViewportSizeUpdateID) {
3251         layerTransaction.setDynamicViewportSizeUpdateID(*m_pendingDynamicViewportSizeUpdateID);
3252         m_pendingDynamicViewportSizeUpdateID = std::nullopt;
3253     }
3254     if (m_lastTransactionPageScaleFactor != layerTransaction.pageScaleFactor()) {
3255         m_lastTransactionPageScaleFactor = layerTransaction.pageScaleFactor();
3256         m_lastTransactionIDWithScaleChange = layerTransaction.transactionID();
3257     }
3258 #endif
3259
3260     layerTransaction.setScrollPosition(frameView->scrollPosition());
3261
3262     if (m_hasPendingEditorStateUpdate) {
3263         layerTransaction.setEditorState(editorState());
3264         m_hasPendingEditorStateUpdate = false;
3265     }
3266 }
3267
3268 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3269 {
3270 #if PLATFORM(IOS)
3271     if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3272         Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3273         m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3274
3275         m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3276     }
3277 #else
3278     UNUSED_PARAM(timestamp);
3279 #endif
3280 }
3281 #endif
3282
3283 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3284 {
3285     if (m_isClosed)
3286         return nullptr;
3287     if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3288         m_inspector = WebInspector::create(this);
3289     return m_inspector.get();
3290 }
3291
3292 WebInspectorUI* WebPage::inspectorUI()
3293 {
3294     if (m_isClosed)
3295         return nullptr;
3296     if (!m_inspectorUI)
3297         m_inspectorUI = WebInspectorUI::create(*this);
3298     return m_inspectorUI.get();
3299 }
3300
3301 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3302 {
3303     if (m_isClosed)
3304         return nullptr;
3305     if (!m_remoteInspectorUI)
3306         m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3307     return m_remoteInspectorUI.get();
3308 }
3309
3310 void WebPage::inspectorFrontendCountChanged(unsigned count)
3311 {
3312     send(Messages::WebPageProxy::DidChangeInspectorFrontendCount(count));
3313 }
3314
3315 #if (PLATFORM(IOS) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3316 PlaybackSessionManager& WebPage::playbackSessionManager()
3317 {
3318     if (!m_playbackSessionManager)
3319         m_playbackSessionManager = PlaybackSessionManager::create(*this);
3320     return *m_playbackSessionManager;
3321 }
3322
3323 VideoFullscreenManager& WebPage::videoFullscreenManager()
3324 {
3325     if (!m_videoFullscreenManager)
3326         m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3327     return *m_videoFullscreenManager;
3328 }
3329
3330 void WebPage::videoControlsManagerDidChange()
3331 {
3332 #if ENABLE(FULLSCREEN_API)
3333     if (auto* manager = fullScreenManager())
3334         manager->videoControlsManagerDidChange();
3335 #endif
3336 }
3337
3338 #endif
3339
3340 #if PLATFORM(IOS)
3341 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3342 {
3343     m_page->setAllowsMediaDocumentInlinePlayback(allows);
3344 }
3345 #endif
3346
3347 #if ENABLE(FULLSCREEN_API)
3348 WebFullScreenManager* WebPage::fullScreenManager()
3349 {
3350     if (!m_fullScreenManager)
3351         m_fullScreenManager = WebFullScreenManager::create(this);
3352     return m_fullScreenManager.get();
3353 }
3354 #endif
3355
3356 void WebPage::addConsoleMessage(uint64_t frameID, MessageSource messageSource, MessageLevel messageLevel, const String& message, uint64_t requestID)
3357 {
3358     if (auto* frame = WebProcess::singleton().webFrame(frameID))
3359         frame->addConsoleMessage(messageSource, messageLevel, message, requestID);
3360 }
3361
3362 void WebPage::sendCSPViolationReport(uint64_t frameID, const WebCore::URL& reportURL, IPC::FormDataReference&& reportData)
3363 {
3364     auto report = reportData.takeData();
3365     if (!report)
3366         return;
3367     if (auto* frame = WebProcess::singleton().webFrame(frameID))
3368         PingLoader::sendViolationReport(*frame->coreFrame(), reportURL, report.releaseNonNull(), ViolationReportType::ContentSecurityPolicy);
3369 }
3370
3371 void WebPage::enqueueSecurityPolicyViolationEvent(uint64_t frameID, SecurityPolicyViolationEvent::Init&& eventInit)
3372 {
3373     auto* frame = WebProcess::singleton().webFrame(frameID);
3374     if (!frame)
3375         return;
3376     auto* coreFrame = frame->coreFrame();
3377     if (!coreFrame)
3378         return;
3379     if (auto* document = coreFrame->document())
3380         document->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
3381 }
3382
3383 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3384 {
3385     if (m_notificationPermissionRequestManager)
3386         return m_notificationPermissionRequestManager.get();
3387
3388     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3389     return m_notificationPermissionRequestManager.get();
3390 }
3391
3392 #if ENABLE(DRAG_SUPPORT)
3393
3394 #if PLATFORM(GTK)
3395 void WebPage::performDragControllerAction(DragControllerAction action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3396 {
3397     if (!m_page) {
3398         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3399         return;
3400     }
3401
3402     DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3403     switch (action) {
3404     case DragControllerAction::Entered: {
3405         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3406         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }));
3407         return;
3408     }
3409     case DragControllerAction::Updated: {
3410         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3411         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }));
3412         return;
3413     }
3414     case DragControllerAction::Exited:
3415         m_page->dragController().dragExited(dragData);
3416         return;
3417
3418     case DragControllerAction::PerformDragOperation: {
3419         m_page->dragController().performDragOperation(dragData);
3420         return;
3421     }
3422     }
3423     ASSERT_NOT_REACHED();
3424 }
3425 #else
3426 void WebPage::performDragControllerAction(DragControllerAction action, const WebCore::DragData& dragData, SandboxExtension::Handle&& sandboxExtensionHandle, SandboxExtension::HandleArray&& sandboxExtensionsHandleArray)
3427 {
3428     if (!m_page) {
3429         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3430         return;
3431     }
3432
3433     switch (action) {
3434     case DragControllerAction::Entered: {
3435         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3436         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), m_page->dragCaretController().caretRectInRootViewCoordinates()));
3437         return;
3438     }
3439     case DragControllerAction::Updated: {
3440         DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3441         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), m_page->dragCaretController().caretRectInRootViewCoordinates()));
3442         return;
3443     }
3444     case DragControllerAction::Exited:
3445         m_page->dragController().dragExited(dragData);
3446         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3447         return;
3448         
3449     case DragControllerAction::PerformDragOperation: {
3450         ASSERT(!m_pendingDropSandboxExtension);
3451
3452         m_pendingDropSandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
3453         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3454             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(WTFMove(sandboxExtensionsHandleArray[i])))
3455                 m_pendingDropExtensionsForFileUpload.append(extension);
3456         }
3457
3458         bool handled = m_page->dragController().performDragOperation(dragData);
3459
3460         // If we started loading a local file, the sandbox extension tracker would have adopted this
3461         // pending drop sandbox extension. If not, we'll play it safe and clear it.
3462         m_pendingDropSandboxExtension = nullptr;
3463
3464         m_pendingDropExtensionsForFileUpload.clear();
3465 #if ENABLE(DATA_INTERACTION)
3466         send(Messages::WebPageProxy::DidPerformDataInteractionControllerOperation(handled));
3467 #else
3468         UNUSED_PARAM(handled);
3469 #endif
3470         return;
3471     }
3472     }
3473     ASSERT_NOT_REACHED();
3474 }
3475 #endif
3476
3477 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3478 {
3479     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3480     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3481
3482     m_page->dragController().dragEnded();
3483     FrameView* view = m_page->mainFrame().view();
3484     if (!view)
3485         return;
3486     // FIXME: These are fake modifier keys here, but they should be real ones instead.
3487     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), 0, WebCore::NoTap);
3488     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3489
3490     send(Messages::WebPageProxy::DidEndDragging());
3491 }
3492
3493 void WebPage::willPerformLoadDragDestinationAction()
3494 {
3495     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(WTFMove(m_pendingDropSandboxExtension));
3496 }
3497
3498 void WebPage::mayPerformUploadDragDestinationAction()
3499 {
3500     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3501         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3502     m_pendingDropExtensionsForFileUpload.clear();
3503 }
3504
3505 void WebPage::didStartDrag()
3506 {
3507     m_isStartingDrag = false;
3508     m_page->mainFrame().eventHandler().didStartDrag();
3509 }
3510
3511 void WebPage::dragCancelled()
3512 {
3513     m_isStartingDrag = false;
3514     m_page->mainFrame().eventHandler().dragCancelled();
3515 }
3516     
3517 #endif // ENABLE(DRAG_SUPPORT)
3518
3519 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3520 {
3521     return m_undoStepMap.get(stepID);
3522 }
3523
3524 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3525 {
3526     m_undoStepMap.set(stepID, entry);
3527 }
3528
3529 void WebPage::removeWebEditCommand(uint64_t stepID)
3530 {
3531     m_undoStepMap.remove(stepID);
3532 }
3533
3534 bool WebPage::isAlwaysOnLoggingAllowed() const
3535 {
3536     return corePage() && corePage()->isAlwaysOnLoggingAllowed();
3537 }
3538
3539 void WebPage::unapplyEditCommand(uint64_t stepID)
3540 {
3541     WebUndoStep* step = webUndoStep(stepID);
3542     if (!step)
3543         return;
3544
3545     step->step().unapply();
3546 }
3547
3548 void WebPage::reapplyEditCommand(uint64_t stepID)
3549 {
3550     WebUndoStep* step = webUndoStep(stepID);
3551     if (!step)
3552         return;
3553
3554     m_isInRedo = true;
3555     step->step().reapply();
3556     m_isInRedo = false;
3557 }
3558
3559 void WebPage::didRemoveEditCommand(uint64_t commandID)
3560 {
3561     removeWebEditCommand(commandID);
3562 }
3563
3564 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3565 {
3566     m_activePopupMenu = menu;
3567 }
3568
3569 #if ENABLE(INPUT_TYPE_COLOR)
3570
3571 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3572 {
3573     m_activeColorChooser = colorChooser;
3574 }
3575
3576 void WebPage::didEndColorPicker()
3577 {
3578     m_activeColorChooser->didEndChooser();
3579 }
3580
3581 void WebPage::didChooseColor(const WebCore::Color& color)
3582 {
3583     m_activeColorChooser->didChooseColor(color);
3584 }
3585
3586 #endif
3587
3588 #if ENABLE(DATALIST_ELEMENT)
3589
3590 void WebPage::setActiveDataListSuggestionPicker(WebDataListSuggestionPicker* dataListSuggestionPicker)
3591 {
3592     m_activeDataListSuggestionPicker = dataListSuggestionPicker;
3593 }
3594
3595 void WebPage::didSelectDataListOption(const String& selectedOption)
3596 {
3597     m_activeDataListSuggestionPicker->didSelectOption(selectedOption);
3598 }
3599
3600 void WebPage::didCloseSuggestions()
3601 {
3602     m_activeDataListSuggestionPicker->didCloseSuggestions();
3603     m_activeDataListSuggestionPicker = nullptr;
3604 }
3605
3606 #endif
3607
3608 void WebPage::setActiveOpenPanelResultListener(Ref<WebOpenPanelResultListener>&& openPanelResultListener)
3609 {
3610     m_activeOpenPanelResultListener = WTFMove(openPanelResultListener);
3611 }
3612
3613 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3614 {
3615     return m_page->findString(target, core(options));
3616 }
3617
3618 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3619 {
3620     findController().findString(string, static_cast<FindOptions>(options), maxMatchCount);
3621 }
3622
3623 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3624 {
3625     findController().findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3626 }
3627
3628 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3629 {
3630     findController().getImageForFindMatch(matchIndex);
3631 }
3632
3633 void WebPage::selectFindMatch(uint32_t matchIndex)
3634 {
3635     findController().selectFindMatch(matchIndex);
3636 }
3637
3638 void WebPage::hideFindUI()
3639 {
3640     findController().hideFindUI();
3641 }
3642
3643 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3644 {
3645     findController().countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3646 }
3647
3648 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3649 {
3650     changeSelectedIndex(newIndex);
3651     m_activePopupMenu = nullptr;
3652 }
3653
3654 void WebPage::changeSelectedIndex(int32_t index)
3655 {
3656     if (!m_activePopupMenu)
3657         return;
3658
3659     m_activePopupMenu->didChangeSelectedIndex(index);
3660 }
3661
3662 #if PLATFORM(IOS)
3663 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3664 {
3665     if (!m_activeOpenPanelResultListener)
3666         return;
3667
3668     RefPtr<Icon> icon;
3669     if (!iconData.isEmpty()) {
3670         RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3671         RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3672         RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3673         icon = Icon::createIconForImage(imageRef.get());
3674     }
3675
3676     m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3677     m_activeOpenPanelResultListener = nullptr;
3678 }
3679 #endif
3680
3681 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3682 {
3683     if (!m_activeOpenPanelResultListener)
3684         return;
3685
3686     m_activeOpenPanelResultListener->didChooseFiles(files);
3687     m_activeOpenPanelResultListener = nullptr;
3688 }
3689
3690 void WebPage::didCancelForOpenPanel()
3691 {
3692     m_activeOpenPanelResultListener = nullptr;
3693 }
3694
3695 #if ENABLE(SANDBOX_EXTENSIONS)
3696 void WebPage::extendSandboxForFilesFromOpenPanel(SandboxExtension::HandleArray&& handles)
3697 {
3698     for (size_t i = 0; i < handles.size(); ++i) {
3699         bool result = SandboxExtension::consumePermanently(handles[i]);
3700         if (!result) {
3701             // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3702             WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3703         }
3704     }
3705 }
3706 #endif
3707
3708 #if ENABLE(GEOLOCATION)
3709 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3710 {
3711     geolocationPermissionRequestManager().didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3712 }
3713 #endif
3714
3715 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3716 {
3717     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3718 }
3719
3720 #if ENABLE(MEDIA_STREAM)
3721
3722 #if !PLATFORM(IOS)
3723 void WebPage::prepareToSendUserMediaPermissionRequest()
3724 {
3725 }
3726 #endif
3727
3728 void WebPage::userMediaAccessWasGranted(uint64_t userMediaID, WebCore::CaptureDevice&& audioDevice, WebCore::CaptureDevice&& videoDevice, String&& mediaDeviceIdentifierHashSalt)
3729 {
3730     m_userMediaPermissionRequestManager->userMediaAccessWasGranted(userMediaID, WTFMove(audioDevice), WTFMove(videoDevice), WTFMove(mediaDeviceIdentifierHashSalt));
3731 }
3732
3733 void WebPage::userMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String&& invalidConstraint)
3734 {
3735     m_userMediaPermissionRequestManager->userMediaAccessWasDenied(userMediaID, static_cast<UserMediaRequest::MediaAccessDenialReason>(reason), WTFMove(invalidConstraint));
3736 }
3737
3738 void WebPage::didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vector<CaptureDevice>& devices, String&& deviceIdentifierHashSalt, bool originHasPersistentAccess)
3739 {
3740     m_userMediaPermissionRequestManager->didCompleteMediaDeviceEnumeration(userMediaID, devices, WTFMove(deviceIdentifierHashSalt), originHasPersistentAccess);
3741 }
3742
3743 void WebPage::captureDevicesChanged(DeviceAccessState accessState)
3744 {
3745     m_userMediaPermissionRequestManager->captureDevicesChanged(accessState);
3746 }
3747
3748 #if ENABLE(SANDBOX_EXTENSIONS)
3749 void WebPage::grantUserMediaDeviceSandboxExtensions(MediaDeviceSandboxExtensions&& extensions)
3750 {
3751     m_userMediaPermissionRequestManager->grantUserMediaDeviceSandboxExtensions(WTFMove(extensions));
3752 }
3753
3754 void WebPage::revokeUserMediaDeviceSandboxExtensions(const Vector<String>& extensionIDs)
3755 {
3756     m_userMediaPermissionRequestManager->revokeUserMediaDeviceSandboxExtensions(extensionIDs);
3757 }
3758 #endif
3759 #endif
3760
3761 #if !PLATFORM(IOS)
3762 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3763 {
3764     Frame& frame = m_page->focusController().focusedOrMainFrame();
3765     frame.editor().advanceToNextMisspelling(startBeforeSelection);
3766 }
3767 #endif
3768
3769 bool WebPage::hasRichlyEditableSelection() const
3770 {
3771     auto& frame = m_page->focusController().focusedOrMainFrame();
3772     if (m_page->dragCaretController().isContentRichlyEditable())
3773         return true;
3774
3775     return frame.selection().selection().isContentRichlyEditable();
3776 }
3777
3778 void WebPage::changeSpellingToWord(const String& word)
3779 {
3780     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3781 }
3782
3783 void WebPage::unmarkAllMisspellings()
3784 {
3785     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3786         if (Document* document = frame->document())
3787             document->markers().removeMarkers(DocumentMarker::Spelling);
3788     }
3789 }
3790
3791 void WebPage::unmarkAllBadGrammar()
3792 {
3793     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3794         if (Document* document = frame->document())
3795             document->markers().removeMarkers(DocumentMarker::Grammar);
3796     }
3797 }
3798
3799 #if USE(APPKIT)
3800 void WebPage::uppercaseWord()
3801 {
3802     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3803 }
3804
3805 void WebPage::lowercaseWord()
3806 {
3807     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3808 }
3809
3810 void WebPage::capitalizeWord()
3811 {
3812     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3813 }
3814 #endif
3815     
3816 void WebPage::setTextForActivePopupMenu(int32_t index)
3817 {
3818     if (!m_activePopupMenu)
3819         return;
3820
3821     m_activePopupMenu->setTextForIndex(index);
3822 }
3823
3824 #if PLATFORM(GTK)
3825 void WebPage::failedToShowPopupMenu()
3826 {
3827     if (!m_activePopupMenu)
3828         return;
3829
3830     m_activePopupMenu->client()->popupDidHide();
3831 }
3832 #endif
3833
3834 #if ENABLE(CONTEXT_MENUS)
3835 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3836 {
3837     if (!m_contextMenu)
3838         return;
3839
3840     m_contextMenu->itemSelected(item);
3841     m_contextMenu = nullptr;
3842 }
3843 #endif
3844
3845 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3846 {
3847     bool selectReplacement = true;
3848     bool smartReplace = false;
3849     return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3850 }
3851
3852 #if !PLATFORM(IOS)
3853 void WebPage::clearSelection()
3854 {
3855     m_page->focusController().focusedOrMainFrame().selection().clear();
3856 }
3857 #endif
3858
3859 void WebPage::restoreSelectionInFocusedEditableElement()
3860 {
3861     Frame& frame = m_page->focusController().focusedOrMainFrame();
3862     if (!frame.selection().isNone())
3863         return;
3864
3865     if (auto document = frame.document()) {
3866         if (auto element = document->focusedElement())
3867             element->updateFocusAppearance(SelectionRestorationMode::Restore, SelectionRevealMode::DoNotReveal);
3868     }
3869 }
3870
3871 bool WebPage::mainFrameHasCustomContentProvider() const
3872 {
3873     if (Frame* frame = mainFrame()) {
3874         WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3875         ASSERT(webFrameLoaderClient);
3876         return webFrameLoaderClient->frameHasCustomContentProvider();
3877     }
3878
3879     return false;
3880 }
3881
3882 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3883 {
3884     m_mimeTypesWithCustomContentProviders.add(mimeType);
3885 }
3886
3887 void WebPage::updateMainFrameScrollOffsetPinning()
3888 {
3889     Frame& frame = m_page->mainFrame();
3890     ScrollPosition scrollPosition = frame.view()->scrollPosition();
3891     ScrollPosition maximumScrollPosition = frame.view()->maximumScrollPosition();
3892     ScrollPosition minimumScrollPosition = frame.view()->minimumScrollPosition();
3893
3894     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3895     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3896     bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3897     bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3898
3899     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3900         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3901         
3902         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3903         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3904         m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3905         m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3906     }
3907 }
3908
3909 void WebPage::mainFrameDidLayout()
3910 {
3911     unsigned pageCount = m_page->pageCount();
3912     if (pageCount != m_cachedPageCount) {
3913         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3914         m_cachedPageCount = pageCount;
3915     }
3916
3917 #if PLATFORM(COCOA)
3918     m_viewGestureGeometryCollector->mainFrameDidLayout();
3919 #endif
3920 #if PLATFORM(IOS)
3921     if (FrameView* frameView = mainFrameView()) {
3922         IntSize newContentSize = frameView->contentsSize();
3923         LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " mainFrameDidLayout setting content size to " << newContentSize);
3924         if (m_viewportConfiguration.setContentsSize(newContentSize))
3925             viewportConfigurationChanged();
3926     }
3927     findController().redraw();
3928 #endif
3929 }
3930
3931 void WebPage::addPluginView(PluginView* pluginView)
3932 {
3933     ASSERT(!m_pluginViews.contains(pluginView));
3934
3935     m_pluginViews.add(pluginView);
3936     m_hasSeenPlugin = true;
3937 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3938     LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3939     m_determinePrimarySnapshottedPlugInTimer.startOneShot(0_s);
3940 #endif
3941 }
3942
3943 void WebPage::removePluginView(PluginView* pluginView)
3944 {
3945     ASSERT(m_pluginViews.contains(pluginView));
3946
3947     m_pluginViews.remove(pluginView);
3948 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3949     LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3950 #endif
3951 }
3952
3953 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3954 {
3955 #if PLATFORM(COCOA)
3956     m_hasCachedWindowFrame = false;
3957 #endif
3958     send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3959 }
3960
3961 #if PLATFORM(COCOA)
3962 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3963 {
3964     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3965     m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3966     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3967     m_accessibilityPosition = accessibilityViewCoordinates;
3968     
3969     // Tell all our plug-in views that the window and view frames have changed.
3970     for (auto* pluginView : m_pluginViews)
3971         pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3972
3973     m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3974 }
3975 #endif
3976
3977 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3978 {
3979     m_mainFrameIsScrollable = isScrollable;
3980     m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3981
3982     if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3983         frameView->setCanHaveScrollbars(isScrollable);
3984         frameView->setProhibitsScrolling(!isScrollable);
3985     }
3986 }
3987
3988 bool WebPage::windowIsFocused() const
3989 {
3990     return m_page->focusController().isActive();
3991 }
3992
3993 bool WebPage::windowAndWebPageAreFocused() const
3994 {
3995     if (!isVisible())
3996         return false;
3997
3998     return m_page->focusController().isFocused() && m_page->focusController().isActive();
3999 }
4000
4001 void WebPage::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
4002 {
4003     if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
4004         if (WebInspector* inspector = this->inspector())
4005             inspector->didReceiveMessage(connection, decoder);
4006         return;
4007     }
4008
4009     if (decoder.messageReceiverName() == Messages::WebInspectorUI::messageReceiverName()) {
4010         if (WebInspectorUI* inspectorUI = this->inspectorUI())
4011             inspectorUI->didReceiveMessage(connection, decoder);
4012         return;
4013     }
4014
4015     if (decoder.messageReceiverName() == Messages::RemoteWebInspectorUI::messageReceiverName()) {
4016         if (RemoteWebInspectorUI* remoteInspectorUI = this->remoteInspectorUI())
4017             remoteInspectorUI->didReceiveMessage(connection, decoder);
4018         return;
4019     }
4020
4021 #if ENABLE(FULLSCREEN_API)
4022     if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
4023         fullScreenManager()->didReceiveMessage(connection, decoder);
4024         return;
4025     }
4026 #endif
4027
4028     didReceiveWebPageMessage(connection, decoder);
4029 }
4030
4031 void WebPage::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
4032 {   
4033     didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
4034 }
4035     
4036 InjectedBundleBackForwardList* WebPage::backForwardList()
4037 {
4038     if (!m_backForwardList)
4039         m_backForwardList = InjectedBundleBackForwardList::create(this);
4040     return m_backForwardList.get();
4041 }
4042
4043 #if ENABLE(ASYNC_SCROLLING)
4044 ScrollingCoordinator* WebPage::scrollingCoordinator() const
4045 {
4046     return m_page->scrollingCoordinator();
4047 }
4048 #endif
4049
4050 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
4051 {
4052     invalidate();
4053 }
4054
4055 void WebPage::SandboxExtensionTracker::invalidate()
4056 {
4057     m_pendingProvisionalSandboxExtension = nullptr;
4058
4059     if (m_provisionalSandboxExtension) {
4060         m_provisionalSandboxExtension->revoke();
4061         m_provisionalSandboxExtension = nullptr;
4062     }
4063
4064     if (m_committedSandboxExtension) {
4065         m_committedSandboxExtension->revoke();
4066         m_committedSandboxExtension = nullptr;
4067     }
4068 }
4069
4070 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(RefPtr<SandboxExtension>&& pendingDropSandboxExtension)
4071 {
4072     setPendingProvisionalSandboxExtension(WTFMove(pendingDropSandboxExtension));
4073 }
4074
4075 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, SandboxExtension::Handle&& handle)
4076 {
4077     ASSERT_UNUSED(frame, frame->isMainFrame());
4078
4079     setPendingProvisionalSandboxExtension(SandboxExtension::create(WTFMove(handle)));
4080 }
4081
4082 void WebPage::SandboxExtensionTracker::beginReload(WebFrame* frame, SandboxExtension::Handle&& handle)
4083 {
4084     ASSERT_UNUSED(frame, frame->isMainFrame());
4085
4086     // Maintain existing provisional SandboxExtension in case of a reload, if the new handle is null. This is needed
4087     // because the UIProcess sends us a null handle if it already sent us a handle for this path in the past.
4088     if (auto sandboxExtension = SandboxExtension::create(WTFMove(handle)))
4089         setPendingProvisionalSandboxExtension(WTFMove(sandboxExtension));
4090 }
4091
4092 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(RefPtr<SandboxExtension>&& pendingProvisionalSandboxExtension)
4093 {
4094     m_pendingProvisionalSandboxExtension = WTFMove(pendingProvisionalSandboxExtension);
4095 }
4096
4097 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
4098 {
4099     ASSERT(frame->isMainFrame());
4100
4101     FrameLoader& frameLoader = frame->coreFrame()->loader();
4102     FrameLoadType frameLoadType = frameLoader.loadType();
4103
4104     // If the page is being reloaded, it should reuse whatever extension is committed.
4105     if (isReload(frameLoadType))
4106         return true;
4107
4108     DocumentLoader* documentLoader = frameLoader.documentLoader();
4109     DocumentLoader* provisionalDocumentLoader = frameLoader.provisionalDocumentLoader();
4110     if (!documentLoader || !provisionalDocumentLoader)
4111         return false;
4112
4113     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
4114         return true;
4115
4116     return false;
4117 }
4118
4119 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
4120 {
4121     if (!frame->isMainFrame())
4122         return;
4123
4124     // We should only reuse the commited sandbox extension if it is not null. It can be
4125     // null if the last load was for an error page.
4126     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame))
4127         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension;
4128
4129     ASSERT(!m_provisionalSandboxExtension);
4130
4131     m_provisionalSandboxExtension = WTFMove(m_pendingProvisionalSandboxExtension);
4132     if (!m_provisionalSandboxExtension)
4133         return;
4134
4135     ASSERT(!m_provisionalSandboxExtension || frame->coreFrame()->loader().provisionalDocumentLoader()->url().isLocalFile());
4136
4137     m_provisionalSandboxExtension->consume();
4138 }
4139
4140 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
4141 {
4142     if (!frame->isMainFrame())
4143         return;
4144
4145     if (m_committedSandboxExtension)
4146         m_committedSandboxExtension->revoke();
4147
4148     m_committedSandboxExtension = WTFMove(m_provisionalSandboxExtension);
4149
4150     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started.
4151     // This extension is not cleared, because it does not pertain to the failed load, and will be needed.
4152 }
4153
4154 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
4155 {
4156     if (!frame->isMainFrame())
4157         return;
4158
4159     if (!m_provisionalSandboxExtension)
4160         return;
4161
4162     m_provisionalSandboxExtension->revoke();
4163     m_provisionalSandboxExtension = nullptr;
4164
4165     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started
4166     // (notably, if the current one fails because the new one cancels it). This extension is not cleared,
4167     // because it does not pertain to the failed load, and will be needed.
4168 }
4169