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