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