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