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