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