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