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