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