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