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