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