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