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