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