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