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