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