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