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