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