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