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