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