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