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