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