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