Replace DATA_TRANSFER_ITEMS by a runtime flag and add a stub implementation
[WebKit.git] / Source / WebKit / WebProcess / WebPage / WebPage.cpp
1 /*
2  * Copyright (C) 2010-2016 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 "APIWebsitePolicies.h"
34 #include "AssistedNodeInformation.h"
35 #include "DataReference.h"
36 #include "DragControllerAction.h"
37 #include "DrawingArea.h"
38 #include "DrawingAreaMessages.h"
39 #include "EditorState.h"
40 #include "EventDispatcher.h"
41 #include "FindController.h"
42 #include "GeolocationPermissionRequestManager.h"
43 #include "InjectedBundle.h"
44 #include "InjectedBundleBackForwardList.h"
45 #include "InjectedBundleScriptWorld.h"
46 #include "LibWebRTCProvider.h"
47 #include "LoadParameters.h"
48 #include "Logging.h"
49 #include "NetscapePlugin.h"
50 #include "NotificationPermissionRequestManager.h"
51 #include "PageBanner.h"
52 #include "PluginProcessAttributes.h"
53 #include "PluginProxy.h"
54 #include "PluginView.h"
55 #include "PrintInfo.h"
56 #include "RemoteWebInspectorUI.h"
57 #include "RemoteWebInspectorUIMessages.h"
58 #include "SessionState.h"
59 #include "SessionStateConversion.h"
60 #include "SessionTracker.h"
61 #include "ShareableBitmap.h"
62 #include "UserMediaPermissionRequestManager.h"
63 #include "ViewGestureGeometryCollector.h"
64 #include "VisitedLinkTableController.h"
65 #include "WKBundleAPICast.h"
66 #include "WKRetainPtr.h"
67 #include "WKSharedAPICast.h"
68 #include "WebAlternativeTextClient.h"
69 #include "WebBackForwardListItem.h"
70 #include "WebBackForwardListProxy.h"
71 #include "WebChromeClient.h"
72 #include "WebColorChooser.h"
73 #include "WebContextMenu.h"
74 #include "WebContextMenuClient.h"
75 #include "WebCoreArgumentCoders.h"
76 #include "WebDatabaseProvider.h"
77 #include "WebDiagnosticLoggingClient.h"
78 #include "WebDocumentLoader.h"
79 #include "WebDragClient.h"
80 #include "WebEditorClient.h"
81 #include "WebEvent.h"
82 #include "WebEventConversion.h"
83 #include "WebEventFactory.h"
84 #include "WebFrame.h"
85 #include "WebFrameLoaderClient.h"
86 #include "WebFullScreenManager.h"
87 #include "WebFullScreenManagerMessages.h"
88 #include "WebGamepadProvider.h"
89 #include "WebGeolocationClient.h"
90 #include "WebImage.h"
91 #include "WebInspector.h"
92 #include "WebInspectorClient.h"
93 #include "WebInspectorMessages.h"
94 #include "WebInspectorUI.h"
95 #include "WebInspectorUIMessages.h"
96 #include "WebMediaKeyStorageManager.h"
97 #include "WebNotificationClient.h"
98 #include "WebOpenPanelResultListener.h"
99 #include "WebPageCreationParameters.h"
100 #include "WebPageGroupProxy.h"
101 #include "WebPageMessages.h"
102 #include "WebPageOverlay.h"
103 #include "WebPageProxyMessages.h"
104 #include "WebPaymentCoordinator.h"
105 #include "WebPerformanceLoggingClient.h"
106 #include "WebPlugInClient.h"
107 #include "WebPluginInfoProvider.h"
108 #include "WebPopupMenu.h"
109 #include "WebPreferencesDefinitions.h"
110 #include "WebPreferencesKeys.h"
111 #include "WebPreferencesStore.h"
112 #include "WebProcess.h"
113 #include "WebProcessPoolMessages.h"
114 #include "WebProcessProxyMessages.h"
115 #include "WebProgressTrackerClient.h"
116 #include "WebSocketProvider.h"
117 #include "WebStorageNamespaceProvider.h"
118 #include "WebURLSchemeHandlerProxy.h"
119 #include "WebUndoStep.h"
120 #include "WebUserContentController.h"
121 #include "WebUserMediaClient.h"
122 #include "WebValidationMessageClient.h"
123 #include <JavaScriptCore/APICast.h>
124 #include <WebCore/ApplicationCacheStorage.h>
125 #include <WebCore/ArchiveResource.h>
126 #include <WebCore/BackForwardController.h>
127 #include <WebCore/Chrome.h>
128 #include <WebCore/CommonVM.h>
129 #include <WebCore/ContextMenuController.h>
130 #include <WebCore/DataTransfer.h>
131 #include <WebCore/DatabaseManager.h>
132 #include <WebCore/DocumentFragment.h>
133 #include <WebCore/DocumentLoader.h>
134 #include <WebCore/DocumentMarkerController.h>
135 #include <WebCore/DragController.h>
136 #include <WebCore/DragData.h>
137 #include <WebCore/Editing.h>
138 #include <WebCore/Editor.h>
139 #include <WebCore/ElementIterator.h>
140 #include <WebCore/EventHandler.h>
141 #include <WebCore/EventNames.h>
142 #include <WebCore/FocusController.h>
143 #include <WebCore/FormState.h>
144 #include <WebCore/FrameLoadRequest.h>
145 #include <WebCore/FrameLoaderTypes.h>
146 #include <WebCore/FrameView.h>
147 #include <WebCore/HTMLFormElement.h>
148 #include <WebCore/HTMLImageElement.h>
149 #include <WebCore/HTMLInputElement.h>
150 #include <WebCore/HTMLOListElement.h>
151 #include <WebCore/HTMLPlugInElement.h>
152 #include <WebCore/HTMLPlugInImageElement.h>
153 #include <WebCore/HTMLUListElement.h>
154 #include <WebCore/HistoryController.h>
155 #include <WebCore/HistoryItem.h>
156 #include <WebCore/HitTestResult.h>
157 #include <WebCore/InspectorController.h>
158 #include <WebCore/JSDOMExceptionHandling.h>
159 #include <WebCore/JSDOMWindow.h>
160 #include <WebCore/KeyboardEvent.h>
161 #include <WebCore/MIMETypeRegistry.h>
162 #include <WebCore/MainFrame.h>
163 #include <WebCore/MouseEvent.h>
164 #include <WebCore/Page.h>
165 #include <WebCore/PageConfiguration.h>
166 #include <WebCore/PlatformKeyboardEvent.h>
167 #include <WebCore/PluginDocument.h>
168 #include <WebCore/PrintContext.h>
169 #include <WebCore/Range.h>
170 #include <WebCore/RenderLayer.h>
171 #include <WebCore/RenderTreeAsText.h>
172 #include <WebCore/RenderView.h>
173 #include <WebCore/ResourceRequest.h>
174 #include <WebCore/ResourceResponse.h>
175 #include <WebCore/RuntimeEnabledFeatures.h>
176 #include <WebCore/SchemeRegistry.h>
177 #include <WebCore/ScriptController.h>
178 #include <WebCore/SerializedScriptValue.h>
179 #include <WebCore/SessionID.h>
180 #include <WebCore/Settings.h>
181 #include <WebCore/ShadowRoot.h>
182 #include <WebCore/SharedBuffer.h>
183 #include <WebCore/StyleProperties.h>
184 #include <WebCore/SubframeLoader.h>
185 #include <WebCore/SubstituteData.h>
186 #include <WebCore/TextIterator.h>
187 #include <WebCore/UserInputBridge.h>
188 #include <WebCore/UserScript.h>
189 #include <WebCore/UserStyleSheet.h>
190 #include <WebCore/VisiblePosition.h>
191 #include <WebCore/VisibleUnits.h>
192 #include <WebCore/WebGLStateTracker.h>
193 #include <WebCore/markup.h>
194 #include <bindings/ScriptValue.h>
195 #include <profiler/ProfilerDatabase.h>
196 #include <runtime/JSCInlines.h>
197 #include <runtime/JSCJSValue.h>
198 #include <runtime/JSLock.h>
199 #include <runtime/SamplingProfiler.h>
200 #include <wtf/RunLoop.h>
201 #include <wtf/SetForScope.h>
202
203 #if ENABLE(DATA_DETECTION)
204 #include "DataDetectionResult.h"
205 #endif
206
207 #if ENABLE(MHTML)
208 #include <WebCore/MHTMLArchive.h>
209 #endif
210
211 #if ENABLE(POINTER_LOCK)
212 #include <WebCore/PointerLockController.h>
213 #endif
214
215 #if ENABLE(PROXIMITY_EVENTS)
216 #include "WebDeviceProximityClient.h"
217 #endif
218
219 #if PLATFORM(COCOA)
220 #include "PDFPlugin.h"
221 #include "PlaybackSessionManager.h"
222 #include "RemoteLayerTreeTransaction.h"
223 #include "VideoFullscreenManager.h"
224 #include "WKStringCF.h"
225 #include <WebCore/LegacyWebArchive.h>
226 #endif
227
228 #if PLATFORM(GTK)
229 #include "WebPrintOperationGtk.h"
230 #include "WebSelectionData.h"
231 #include <gtk/gtk.h>
232 #endif
233
234 #if PLATFORM(IOS)
235 #include "RemoteLayerTreeDrawingArea.h"
236 #include <CoreGraphics/CoreGraphics.h>
237 #include <WebCore/Icon.h>
238 #include <pal/spi/cocoa/CoreTextSPI.h>
239 #endif
240
241 #ifndef NDEBUG
242 #include <wtf/RefCountedLeakCounter.h>
243 #endif
244
245 #if ENABLE(DATA_DETECTION)
246 #include <WebCore/DataDetection.h>
247 #endif
248
249 #if ENABLE(VIDEO) && USE(GSTREAMER)
250 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
251 #endif
252
253 using namespace JSC;
254 using namespace WebCore;
255
256 namespace WebKit {
257
258 static const Seconds pageScrollHysteresisDuration { 300_ms };
259 static const Seconds initialLayerVolatilityTimerInterval { 20_ms };
260 static const Seconds maximumLayerVolatilityTimerInterval { 2_s };
261
262 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
263 #define RELEASE_LOG_ERROR_IF_ALLOWED(...) RELEASE_LOG_ERROR_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
264
265 class SendStopResponsivenessTimer {
266 public:
267     ~SendStopResponsivenessTimer()
268     {
269         WebProcess::singleton().parentProcessConnection()->send(Messages::WebProcessProxy::StopResponsivenessTimer(), 0);
270     }
271 };
272
273 class DeferredPageDestructor {
274 public:
275     static void createDeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
276     {
277         new DeferredPageDestructor(WTFMove(page), webPage);
278     }
279
280 private:
281     DeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
282         : m_page(WTFMove(page))
283         , m_webPage(webPage)
284     {
285         tryDestruction();
286     }
287
288     void tryDestruction()
289     {
290         if (m_page->insideNestedRunLoop()) {
291             m_page->whenUnnested([this] { tryDestruction(); });
292             return;
293         }
294
295         m_page = nullptr;
296         m_webPage = nullptr;
297         delete this;
298     }
299
300     std::unique_ptr<Page> m_page;
301     RefPtr<WebPage> m_webPage;
302 };
303
304 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
305
306 Ref<WebPage> WebPage::create(uint64_t pageID, WebPageCreationParameters&& parameters)
307 {
308     Ref<WebPage> page = adoptRef(*new WebPage(pageID, WTFMove(parameters)));
309
310     if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
311         WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
312
313     return page;
314 }
315
316 WebPage::WebPage(uint64_t pageID, WebPageCreationParameters&& parameters)
317     : m_pageID(pageID)
318     , m_viewSize(parameters.viewSize)
319 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
320     , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
321 #endif
322     , m_layerHostingMode(parameters.layerHostingMode)
323 #if PLATFORM(COCOA)
324     , m_viewGestureGeometryCollector(makeUniqueRef<ViewGestureGeometryCollector>(*this))
325 #elif HAVE(ACCESSIBILITY) && PLATFORM(GTK)
326     , m_accessibilityObject(nullptr)
327 #endif
328     , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
329 #if ENABLE(CONTEXT_MENUS)
330     , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
331 #endif
332     , m_editorClient { std::make_unique<API::InjectedBundle::EditorClient>() }
333     , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
334     , m_loaderClient(std::make_unique<API::InjectedBundle::PageLoaderClient>())
335     , m_resourceLoadClient(std::make_unique<API::InjectedBundle::ResourceLoadClient>())
336     , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
337     , m_findController(makeUniqueRef<FindController>(this))
338     , m_userContentController(WebUserContentController::getOrCreate(parameters.userContentControllerID))
339 #if ENABLE(GEOLOCATION)
340     , m_geolocationPermissionRequestManager(makeUniqueRef<GeolocationPermissionRequestManager>(this))
341 #endif
342 #if ENABLE(MEDIA_STREAM)
343     , m_userMediaPermissionRequestManager { std::make_unique<UserMediaPermissionRequestManager>(*this) }
344 #endif
345     , m_pageScrolledHysteresis([this](HysteresisState state) { if (state == HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisDuration)
346     , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
347     , m_canRunModal(parameters.canRunModal)
348 #if PLATFORM(IOS)
349     , m_forceAlwaysUserScalable(parameters.ignoresViewportScaleLimits)
350     , m_screenSize(parameters.screenSize)
351     , m_availableScreenSize(parameters.availableScreenSize)
352     , m_allowsBlockSelection(parameters.allowsBlockSelection)
353 #endif
354     , m_layerVolatilityTimer(*this, &WebPage::layerVolatilityTimerFired)
355     , m_activityState(parameters.activityState)
356     , m_processSuppressionEnabled(true)
357     , m_userActivity("Process suppression disabled for page.")
358     , m_userActivityHysteresis([this](HysteresisState) { updateUserActivity(); })
359     , m_userInterfaceLayoutDirection(parameters.userInterfaceLayoutDirection)
360     , m_overrideContentSecurityPolicy { parameters.overrideContentSecurityPolicy }
361     , m_cpuLimit(parameters.cpuLimit)
362 {
363     ASSERT(m_pageID);
364
365     m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
366
367 #if PLATFORM(IOS)
368     Settings::setShouldManageAudioSessionCategory(true);
369 #endif
370
371     PageConfiguration pageConfiguration(
372         makeUniqueRef<WebEditorClient>(this),
373         WebSocketProvider::create(),
374         makeUniqueRef<WebKit::LibWebRTCProvider>()
375     );
376     pageConfiguration.chromeClient = new WebChromeClient(*this);
377 #if ENABLE(CONTEXT_MENUS)
378     pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
379 #endif
380 #if ENABLE(DRAG_SUPPORT)
381     pageConfiguration.dragClient = new WebDragClient(this);
382 #endif
383     pageConfiguration.backForwardClient = WebBackForwardListProxy::create(this);
384     pageConfiguration.inspectorClient = new WebInspectorClient(this);
385 #if USE(AUTOCORRECTION_PANEL)
386     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
387 #endif
388
389     pageConfiguration.plugInClient = new WebPlugInClient(*this);
390     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
391     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
392     pageConfiguration.diagnosticLoggingClient = std::make_unique<WebDiagnosticLoggingClient>(*this);
393     pageConfiguration.performanceLoggingClient = std::make_unique<WebPerformanceLoggingClient>(*this);
394
395     pageConfiguration.webGLStateTracker = std::make_unique<WebGLStateTracker>([this](bool isUsingHighPerformanceWebGL) {
396         send(Messages::WebPageProxy::SetIsUsingHighPerformanceWebGL(isUsingHighPerformanceWebGL));
397     });
398
399 #if PLATFORM(COCOA)
400     pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(*this);
401 #endif
402
403     pageConfiguration.applicationCacheStorage = &WebProcess::singleton().applicationCacheStorage();
404     pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
405     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
406     pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
407     pageConfiguration.userContentProvider = m_userContentController.ptr();
408     pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
409
410 #if ENABLE(APPLE_PAY)
411     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinator(*this);
412 #endif
413
414     m_page = std::make_unique<Page>(WTFMove(pageConfiguration));
415     updatePreferences(parameters.store);
416
417     m_drawingArea = DrawingArea::create(*this, parameters);
418     m_drawingArea->setPaintingEnabled(false);
419     m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
420
421 #if ENABLE(ASYNC_SCROLLING)
422     m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
423     if (!m_drawingArea->supportsAsyncScrolling())
424         m_useAsyncScrolling = false;
425     m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
426 #endif
427
428     m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
429     m_drawingArea->updatePreferences(parameters.store);
430
431 #if ENABLE(GEOLOCATION)
432     WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
433 #endif
434 #if ENABLE(NOTIFICATIONS)
435     WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
436 #endif
437 #if ENABLE(PROXIMITY_EVENTS)
438     WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this));
439 #endif
440 #if ENABLE(MEDIA_STREAM)
441     WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
442 #endif
443
444     m_page->setControlledByAutomation(parameters.controlledByAutomation);
445
446 #if ENABLE(REMOTE_INSPECTOR)
447     m_page->setRemoteInspectionAllowed(parameters.allowsRemoteInspection);
448     m_page->setRemoteInspectionNameOverride(parameters.remoteInspectionNameOverride);
449 #endif
450
451     m_page->setCanStartMedia(false);
452     m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
453
454     m_page->setGroupName(m_pageGroup->identifier());
455     m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
456     m_page->setUserInterfaceLayoutDirection(m_userInterfaceLayoutDirection);
457 #if PLATFORM(IOS)
458     m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
459 #endif
460
461     platformInitialize();
462
463     setUseFixedLayout(parameters.useFixedLayout);
464
465     setDrawsBackground(parameters.drawsBackground);
466
467     setUnderlayColor(parameters.underlayColor);
468
469     setPaginationMode(parameters.paginationMode);
470     setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
471     setPageLength(parameters.pageLength);
472     setGapBetweenPages(parameters.gapBetweenPages);
473     setPaginationLineGridEnabled(parameters.paginationLineGridEnabled);
474     
475     // If the page is created off-screen, its visibilityState should be prerender.
476     m_page->setActivityState(m_activityState);
477     if (!isVisible())
478         m_page->setIsPrerender();
479
480     updateIsInWindow(true);
481
482     setMinimumLayoutSize(parameters.minimumLayoutSize);
483     setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
484     setViewportSizeForCSSViewportUnits(parameters.viewportSizeForCSSViewportUnits);
485     
486     setScrollPinningBehavior(parameters.scrollPinningBehavior);
487     if (parameters.scrollbarOverlayStyle)
488         m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
489     else
490         m_scrollbarOverlayStyle = std::optional<ScrollbarOverlayStyle>();
491
492     setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
493
494     setTopContentInset(parameters.topContentInset);
495
496     m_userAgent = parameters.userAgent;
497
498     WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
499     
500     if (!parameters.itemStates.isEmpty())
501         restoreSessionInternal(parameters.itemStates, WasRestoredByAPIRequest::No);
502
503     if (parameters.sessionID.isValid())
504         setSessionID(parameters.sessionID);
505
506     m_drawingArea->setPaintingEnabled(true);
507     
508     setMediaVolume(parameters.mediaVolume);
509
510     setMuted(parameters.muted);
511
512     // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
513     m_page->addLayoutMilestones(DidFirstLayout | DidFirstVisuallyNonEmptyLayout);
514
515     auto& webProcess = WebProcess::singleton();
516     webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
517
518     // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
519     webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
520     webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
521     webProcess.addMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID, *this);
522 #if ENABLE(FULLSCREEN_API)
523     webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
524 #endif
525
526 #ifndef NDEBUG
527     webPageCounter.increment();
528 #endif
529
530 #if ENABLE(ASYNC_SCROLLING)
531     if (m_useAsyncScrolling)
532         webProcess.eventDispatcher().addScrollingTreeForPage(this);
533 #endif
534
535     for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
536         m_mimeTypesWithCustomContentProviders.add(mimeType);
537
538
539 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
540     if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
541         m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
542 #endif
543     m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
544
545     if (parameters.viewScaleFactor != 1)
546         scaleView(parameters.viewScaleFactor);
547
548     m_page->addLayoutMilestones(parameters.observedLayoutMilestones);
549
550 #if PLATFORM(COCOA)
551     m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
552     setSmartInsertDeleteEnabled(parameters.smartInsertDeleteEnabled);
553 #endif
554
555 #if ENABLE(WEB_RTC)
556     if (!parameters.iceCandidateFilteringEnabled)
557         disableICECandidateFiltering();
558 #if USE(LIBWEBRTC)
559     if (parameters.enumeratingAllNetworkInterfacesEnabled)
560         enableEnumeratingAllNetworkInterfaces();
561 #endif
562 #endif
563
564     for (auto iterator : parameters.urlSchemeHandlers)
565         registerURLSchemeHandler(iterator.value, iterator.key);
566
567     m_userContentController->addUserContentWorlds(parameters.userContentWorlds);
568     m_userContentController->addUserScripts(parameters.userScripts);
569     m_userContentController->addUserStyleSheets(parameters.userStyleSheets);
570     m_userContentController->addUserScriptMessageHandlers(parameters.messageHandlers);
571 #if ENABLE(CONTENT_EXTENSIONS)
572     m_userContentController->addContentRuleLists(parameters.contentRuleLists);
573 #endif
574 }
575
576 #if ENABLE(WEB_RTC)
577 void WebPage::disableICECandidateFiltering()
578 {
579     m_page->disableICECandidateFiltering();
580 }
581
582 void WebPage::enableICECandidateFiltering()
583 {
584     m_page->enableICECandidateFiltering();
585 }
586
587 #if USE(LIBWEBRTC)
588 void WebPage::disableEnumeratingAllNetworkInterfaces()
589 {
590     m_page->libWebRTCProvider().disableEnumeratingAllNetworkInterfaces();
591 }
592
593 void WebPage::enableEnumeratingAllNetworkInterfaces()
594 {
595     m_page->libWebRTCProvider().enableEnumeratingAllNetworkInterfaces();
596 }
597 #endif
598 #endif
599
600 void WebPage::reinitializeWebPage(WebPageCreationParameters&& parameters)
601 {
602     if (m_activityState != parameters.activityState)
603         setActivityState(parameters.activityState, false, Vector<CallbackID>());
604     if (m_layerHostingMode != parameters.layerHostingMode)
605         setLayerHostingMode(parameters.layerHostingMode);
606 }
607
608 void WebPage::updateThrottleState()
609 {
610     // We should suppress if the page is not active, is visually idle, and supression is enabled.
611     bool isLoading = m_activityState & ActivityState::IsLoading;
612     bool isPlayingAudio = m_activityState & ActivityState::IsAudible;
613     bool isCapturingMedia = m_activityState & ActivityState::IsCapturingMedia;
614     bool isVisuallyIdle = m_activityState & ActivityState::IsVisuallyIdle;
615     bool windowIsActive = m_activityState & ActivityState::WindowIsActive;
616     bool pageSuppressed = !windowIsActive && !isLoading && !isPlayingAudio && !isCapturingMedia && m_processSuppressionEnabled && isVisuallyIdle;
617
618     // The UserActivity keeps the processes runnable. So if the page should be suppressed, stop the activity.
619     // If the page should not be supressed, start it.
620     if (pageSuppressed)
621         m_userActivityHysteresis.stop();
622     else
623         m_userActivityHysteresis.start();
624 }
625
626 void WebPage::updateUserActivity()
627 {
628     if (m_userActivityHysteresis.state() == HysteresisState::Started)
629         m_userActivity.start();
630     else
631         m_userActivity.stop();
632 }
633
634 WebPage::~WebPage()
635 {
636     if (m_backForwardList)
637         m_backForwardList->detach();
638
639     ASSERT(!m_page);
640
641     auto& webProcess = WebProcess::singleton();
642 #if ENABLE(ASYNC_SCROLLING)
643     if (m_useAsyncScrolling)
644         webProcess.eventDispatcher().removeScrollingTreeForPage(this);
645 #endif
646
647     platformDetach();
648     
649     m_sandboxExtensionTracker.invalidate();
650
651     for (auto* pluginView : m_pluginViews)
652         pluginView->webPageDestroyed();
653
654 #if !PLATFORM(IOS)
655     if (m_headerBanner)
656         m_headerBanner->detachFromPage();
657     if (m_footerBanner)
658         m_footerBanner->detachFromPage();
659 #endif // !PLATFORM(IOS)
660
661     webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
662
663     // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
664     webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
665     webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
666     webProcess.removeMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID);
667 #if ENABLE(FULLSCREEN_API)
668     webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
669 #endif
670
671 #ifndef NDEBUG
672     webPageCounter.decrement();
673 #endif
674     
675 #if (PLATFORM(IOS) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
676     if (m_playbackSessionManager)
677         m_playbackSessionManager->invalidate();
678
679     if (m_videoFullscreenManager)
680         m_videoFullscreenManager->invalidate();
681 #endif
682 }
683
684 void WebPage::dummy(bool&)
685 {
686 }
687
688 IPC::Connection* WebPage::messageSenderConnection()
689 {
690     return WebProcess::singleton().parentProcessConnection();
691 }
692
693 uint64_t WebPage::messageSenderDestinationID()
694 {
695     return pageID();
696 }
697
698 #if ENABLE(CONTEXT_MENUS)
699 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>&& contextMenuClient)
700 {
701     if (!contextMenuClient) {
702         m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
703         return;
704     }
705
706     m_contextMenuClient = WTFMove(contextMenuClient);
707 }
708 #endif
709
710 void WebPage::setInjectedBundleEditorClient(std::unique_ptr<API::InjectedBundle::EditorClient>&& editorClient)
711 {
712     if (!editorClient) {
713         m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
714         return;
715     }
716
717     m_editorClient = WTFMove(editorClient);
718 }
719
720 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>&& formClient)
721 {
722     if (!formClient) {
723         m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
724         return;
725     }
726
727     m_formClient = WTFMove(formClient);
728 }
729
730 void WebPage::setInjectedBundlePageLoaderClient(std::unique_ptr<API::InjectedBundle::PageLoaderClient>&& loaderClient)
731 {
732     if (!loaderClient) {
733         m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
734         return;
735     }
736
737     m_loaderClient = WTFMove(loaderClient);
738
739     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
740     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
741     // for backwards compatibility.
742     if (auto milestones = m_loaderClient->layoutMilestones())
743         listenForLayoutMilestones(milestones);
744 }
745
746 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
747 {
748     m_policyClient.initialize(client);
749 }
750
751 void WebPage::setInjectedBundleResourceLoadClient(std::unique_ptr<API::InjectedBundle::ResourceLoadClient>&& client)
752 {
753     if (!m_resourceLoadClient)
754         m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
755     else
756         m_resourceLoadClient = WTFMove(client);
757 }
758
759 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>&& uiClient)
760 {
761     if (!uiClient) {
762         m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
763         return;
764     }
765
766     m_uiClient = WTFMove(uiClient);
767 }
768
769 #if ENABLE(FULLSCREEN_API)
770 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
771 {
772     m_fullScreenClient.initialize(client);
773 }
774 #endif
775
776 #if ENABLE(NETSCAPE_PLUGIN_API)
777 RefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
778 {
779     String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
780     String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
781
782 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
783     HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
784     unsigned pluginArea = 0;
785     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
786 #else
787     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
788 #endif
789
790     bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
791
792     uint64_t pluginProcessToken;
793     uint32_t pluginLoadPolicy;
794     String unavailabilityDescription;
795     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)))
796         return nullptr;
797
798     PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
799     bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
800
801     if (isBlockedPlugin || !pluginProcessToken) {
802 #if ENABLE(PDFKIT_PLUGIN)
803         String path = parameters.url.path();
804         if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
805             auto pdfPlugin = PDFPlugin::create(frame);
806             return WTFMove(pdfPlugin);
807         }
808 #else
809         UNUSED_PARAM(frame);
810 #endif
811     }
812
813     if (isBlockedPlugin) {
814         send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, pluginElement->isReplacementObscured(unavailabilityDescription)));
815         return nullptr;
816     }
817
818     if (!pluginProcessToken)
819         return nullptr;
820
821     bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
822     return PluginProxy::create(pluginProcessToken, isRestartedProcess);
823 }
824 #endif // ENABLE(NETSCAPE_PLUGIN_API)
825
826 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
827 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
828 {
829     return WebGLAllowCreation;
830 }
831
832 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
833 {
834     return WebGLAllowCreation;
835 }
836 #endif
837
838 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
839 {
840     Frame& frame = m_page->focusController().focusedOrMainFrame();
841
842     EditorState result;
843
844     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
845         if (!pluginView->getSelectionString().isNull()) {
846             result.selectionIsNone = false;
847             result.selectionIsRange = true;
848             result.isInPlugin = true;
849             return result;
850         }
851     }
852
853     const VisibleSelection& selection = frame.selection().selection();
854
855     result.selectionIsNone = selection.isNone();
856     result.selectionIsRange = selection.isRange();
857     result.isContentEditable = selection.isContentEditable();
858     result.isContentRichlyEditable = selection.isContentRichlyEditable();
859     result.isInPasswordField = selection.isInPasswordField();
860     result.hasComposition = frame.editor().hasComposition();
861     result.shouldIgnoreSelectionChanges = frame.editor().ignoreSelectionChanges();
862
863 #if PLATFORM(COCOA)
864     if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && result.isContentEditable) {
865         auto& postLayoutData = result.postLayoutData();
866         if (!selection.isNone()) {
867             Node* nodeToRemove;
868             if (auto* style = Editor::styleForSelectionStart(&frame, nodeToRemove)) {
869                 if (isFontWeightBold(style->fontCascade().weight()))
870                     postLayoutData.typingAttributes |= AttributeBold;
871                 if (isItalic(style->fontCascade().italic()))
872                     postLayoutData.typingAttributes |= AttributeItalics;
873
874                 RefPtr<EditingStyle> typingStyle = frame.selection().typingStyle();
875                 if (typingStyle && typingStyle->style()) {
876                     String value = typingStyle->style()->getPropertyValue(CSSPropertyWebkitTextDecorationsInEffect);
877                 if (value.contains("underline"))
878                     postLayoutData.typingAttributes |= AttributeUnderline;
879                 } else {
880                     if (style->textDecorationsInEffect() & TextDecorationUnderline)
881                         postLayoutData.typingAttributes |= AttributeUnderline;
882                 }
883
884                 if (style->visitedDependentColor(CSSPropertyColor).isValid())
885                     postLayoutData.textColor = style->visitedDependentColor(CSSPropertyColor);
886
887                 switch (style->textAlign()) {
888                 case RIGHT:
889                 case WEBKIT_RIGHT:
890                     postLayoutData.textAlignment = RightAlignment;
891                     break;
892                 case LEFT:
893                 case WEBKIT_LEFT:
894                     postLayoutData.textAlignment = LeftAlignment;
895                     break;
896                 case CENTER:
897                 case WEBKIT_CENTER:
898                     postLayoutData.textAlignment = CenterAlignment;
899                     break;
900                 case JUSTIFY:
901                     postLayoutData.textAlignment = JustifiedAlignment;
902                     break;
903                 case TASTART:
904                     postLayoutData.textAlignment = style->isLeftToRightDirection() ? LeftAlignment : RightAlignment;
905                     break;
906                 case TAEND:
907                     postLayoutData.textAlignment = style->isLeftToRightDirection() ? RightAlignment : LeftAlignment;
908                     break;
909                 }
910                 
911                 HTMLElement* enclosingListElement = enclosingList(selection.start().deprecatedNode());
912                 if (enclosingListElement) {
913                     if (is<HTMLUListElement>(*enclosingListElement))
914                         postLayoutData.enclosingListType = UnorderedList;
915                     else if (is<HTMLOListElement>(*enclosingListElement))
916                         postLayoutData.enclosingListType = OrderedList;
917                     else
918                         ASSERT_NOT_REACHED();
919                 } else
920                     postLayoutData.enclosingListType = NoList;
921
922                 if (nodeToRemove)
923                     nodeToRemove->remove();
924             }
925         }
926     }
927 #endif
928
929     platformEditorState(frame, result, shouldIncludePostLayoutData);
930
931     m_lastEditorStateWasContentEditable = result.isContentEditable ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
932
933     return result;
934 }
935
936 void WebPage::updateEditorStateAfterLayoutIfEditabilityChanged()
937 {
938     // FIXME: We should update EditorStateIsContentEditable to track whether the state is richly
939     // editable or plainttext-only.
940     if (m_lastEditorStateWasContentEditable == EditorStateIsContentEditable::Unset)
941         return;
942
943     Frame& frame = m_page->focusController().focusedOrMainFrame();
944     EditorStateIsContentEditable editorStateIsContentEditable = frame.selection().selection().isContentEditable() ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
945     if (m_lastEditorStateWasContentEditable != editorStateIsContentEditable)
946         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
947 }
948
949 String WebPage::renderTreeExternalRepresentation() const
950 {
951     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
952 }
953
954 String WebPage::renderTreeExternalRepresentationForPrinting() const
955 {
956     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
957 }
958
959 uint64_t WebPage::renderTreeSize() const
960 {
961     if (!m_page)
962         return 0;
963     return m_page->renderTreeSize();
964 }
965
966 void WebPage::setTracksRepaints(bool trackRepaints)
967 {
968     if (FrameView* view = mainFrameView())
969         view->setTracksRepaints(trackRepaints);
970 }
971
972 bool WebPage::isTrackingRepaints() const
973 {
974     if (FrameView* view = mainFrameView())
975         return view->isTrackingRepaints();
976
977     return false;
978 }
979
980 void WebPage::resetTrackedRepaints()
981 {
982     if (FrameView* view = mainFrameView())
983         view->resetTrackedRepaints();
984 }
985
986 Ref<API::Array> WebPage::trackedRepaintRects()
987 {
988     FrameView* view = mainFrameView();
989     if (!view)
990         return API::Array::create();
991
992     Vector<RefPtr<API::Object>> repaintRects;
993     repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
994
995     for (const auto& repaintRect : view->trackedRepaintRects())
996         repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
997
998     return API::Array::create(WTFMove(repaintRects));
999 }
1000
1001 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
1002 {
1003     if (!frame.document()->isPluginDocument())
1004         return 0;
1005
1006     PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
1007
1008     if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
1009         return 0;
1010
1011     PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
1012     return pluginView;
1013 }
1014
1015 PluginView* WebPage::pluginViewForFrame(Frame* frame)
1016 {
1017     if (!frame->document()->isPluginDocument())
1018         return 0;
1019
1020     PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
1021     PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
1022     return pluginView;
1023 }
1024
1025 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
1026 {
1027     Frame& frame = m_page->focusController().focusedOrMainFrame();
1028
1029     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
1030         pluginView->handleEditingCommand(commandName, argument);
1031         return;
1032     }
1033     
1034     frame.editor().command(commandName).execute(argument);
1035 }
1036
1037 void WebPage::setEditable(bool editable)
1038 {
1039     m_page->setEditable(editable);
1040     m_page->setTabKeyCyclesThroughElements(!editable);
1041     Frame& frame = m_page->focusController().focusedOrMainFrame();
1042     if (editable) {
1043         frame.editor().applyEditingStyleToBodyElement();
1044         // If the page is made editable and the selection is empty, set it to something.
1045         if (frame.selection().isNone())
1046             frame.selection().setSelectionFromNone();
1047     }
1048 }
1049
1050 bool WebPage::isEditingCommandEnabled(const String& commandName)
1051 {
1052     Frame& frame = m_page->focusController().focusedOrMainFrame();
1053
1054     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1055         return pluginView->isEditingCommandEnabled(commandName);
1056     
1057     Editor::Command command = frame.editor().command(commandName);
1058     return command.isSupported() && command.isEnabled();
1059 }
1060     
1061 void WebPage::clearMainFrameName()
1062 {
1063     if (Frame* frame = mainFrame())
1064         frame->tree().clearName();
1065 }
1066
1067 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
1068 {
1069     m_drawingArea->setRootCompositingLayer(layer);
1070 }
1071
1072 void WebPage::exitAcceleratedCompositingMode()
1073 {
1074     m_drawingArea->setRootCompositingLayer(0);
1075 }
1076
1077 void WebPage::close()
1078 {
1079     if (m_isClosed)
1080         return;
1081
1082     m_isClosed = true;
1083
1084     // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1085     if (!mainWebFrame()->url().isEmpty())
1086         reportUsedFeatures();
1087
1088     if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
1089         WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1090
1091     if (m_inspector) {
1092         m_inspector->disconnectFromPage();
1093         m_inspector = nullptr;
1094     }
1095
1096     m_page->inspectorController().disconnectAllFrontends();
1097
1098 #if ENABLE(FULLSCREEN_API)
1099     m_fullScreenManager = nullptr;
1100 #endif
1101
1102     if (m_activePopupMenu) {
1103         m_activePopupMenu->disconnectFromPage();
1104         m_activePopupMenu = nullptr;
1105     }
1106
1107     if (m_activeOpenPanelResultListener) {
1108         m_activeOpenPanelResultListener->disconnectFromPage();
1109         m_activeOpenPanelResultListener = nullptr;
1110     }
1111
1112 #if ENABLE(INPUT_TYPE_COLOR)
1113     if (m_activeColorChooser) {
1114         m_activeColorChooser->disconnectFromPage();
1115         m_activeColorChooser = nullptr;
1116     }
1117 #endif
1118
1119 #if PLATFORM(GTK)
1120     if (m_printOperation) {
1121         m_printOperation->disconnectFromPage();
1122         m_printOperation = nullptr;
1123     }
1124 #endif
1125
1126 #if ENABLE(VIDEO) && USE(GSTREAMER)
1127     if (m_installMediaPluginsCallback) {
1128         m_installMediaPluginsCallback->invalidate();
1129         m_installMediaPluginsCallback = nullptr;
1130     }
1131 #endif
1132
1133     m_sandboxExtensionTracker.invalidate();
1134
1135 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1136     m_determinePrimarySnapshottedPlugInTimer.stop();
1137 #endif
1138
1139 #if ENABLE(CONTEXT_MENUS)
1140     m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1141 #endif
1142     m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
1143     m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1144     m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
1145     m_policyClient.initialize(0);
1146     m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
1147     m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1148 #if ENABLE(FULLSCREEN_API)
1149     m_fullScreenClient.initialize(0);
1150 #endif
1151
1152     m_printContext = nullptr;
1153     m_mainFrame->coreFrame()->loader().detachFromParent();
1154     m_drawingArea = nullptr;
1155
1156     DeferredPageDestructor::createDeferredPageDestructor(WTFMove(m_page), this);
1157
1158     bool isRunningModal = m_isRunningModal;
1159     m_isRunningModal = false;
1160
1161     // The WebPage can be destroyed by this call.
1162     WebProcess::singleton().removeWebPage(m_pageID);
1163
1164     WebProcess::singleton().updateActivePages();
1165
1166     if (isRunningModal)
1167         RunLoop::main().stop();
1168 }
1169
1170 void WebPage::tryClose()
1171 {
1172     SendStopResponsivenessTimer stopper;
1173
1174     if (!corePage()->userInputBridge().tryClosePage())
1175         return;
1176
1177     send(Messages::WebPageProxy::ClosePage(true));
1178 }
1179
1180 void WebPage::sendClose()
1181 {
1182     send(Messages::WebPageProxy::ClosePage(false));
1183 }
1184
1185 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
1186 {
1187     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1188     if (!frame)
1189         return;
1190
1191     frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(URL(URL(), url)), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1192 }
1193
1194 #if !PLATFORM(COCOA)
1195 void WebPage::platformDidReceiveLoadParameters(const LoadParameters& loadParameters)
1196 {
1197 }
1198 #endif
1199
1200 void WebPage::loadRequest(const LoadParameters& loadParameters)
1201 {
1202     SendStopResponsivenessTimer stopper;
1203
1204     m_pendingNavigationID = loadParameters.navigationID;
1205
1206     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), loadParameters.sandboxExtensionHandle);
1207
1208     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1209     // to all the client to set up any needed state.
1210     m_loaderClient->willLoadURLRequest(*this, loadParameters.request, WebProcess::singleton().transformHandlesToObjects(loadParameters.userData.object()).get());
1211
1212     platformDidReceiveLoadParameters(loadParameters);
1213
1214     // Initate the load in WebCore.
1215     FrameLoadRequest frameLoadRequest { *m_mainFrame->coreFrame(), loadParameters.request, ShouldOpenExternalURLsPolicy::ShouldNotAllow };
1216     ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(loadParameters.shouldOpenExternalURLsPolicy);
1217     frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1218
1219     corePage()->userInputBridge().loadRequest(WTFMove(frameLoadRequest));
1220
1221     ASSERT(!m_pendingNavigationID);
1222 }
1223
1224 void WebPage::loadDataImpl(uint64_t navigationID, Ref<SharedBuffer>&& sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1225 {
1226     SendStopResponsivenessTimer stopper;
1227
1228     m_pendingNavigationID = navigationID;
1229
1230     ResourceRequest request(baseURL);
1231     ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1232     SubstituteData substituteData(WTFMove(sharedBuffer), unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1233
1234     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1235     // to all the client to set up any needed state.
1236     m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1237
1238     // Initate the load in WebCore.
1239     m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(*m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData));
1240 }
1241
1242 void WebPage::loadStringImpl(uint64_t navigationID, const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1243 {
1244     if (!htmlString.isNull() && htmlString.is8Bit()) {
1245         auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
1246         loadDataImpl(navigationID, WTFMove(sharedBuffer), MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, userData);
1247     } else {
1248         auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
1249         loadDataImpl(navigationID, WTFMove(sharedBuffer), MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, userData);
1250     }
1251 }
1252
1253 void WebPage::loadData(const LoadParameters& loadParameters)
1254 {
1255     platformDidReceiveLoadParameters(loadParameters);
1256
1257     auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1258     URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1259     loadDataImpl(loadParameters.navigationID, WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, URL(), loadParameters.userData);
1260 }
1261
1262 void WebPage::loadString(const LoadParameters& loadParameters)
1263 {
1264     platformDidReceiveLoadParameters(loadParameters);
1265
1266     URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1267     loadStringImpl(loadParameters.navigationID, loadParameters.string, loadParameters.MIMEType, baseURL, URL(), loadParameters.userData);
1268 }
1269
1270 void WebPage::loadAlternateHTMLString(const LoadParameters& loadParameters)
1271 {
1272     platformDidReceiveLoadParameters(loadParameters);
1273
1274     URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1275     URL unreachableURL = loadParameters.unreachableURLString.isEmpty() ? URL() : URL(URL(), loadParameters.unreachableURLString);
1276     URL provisionalLoadErrorURL = loadParameters.provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), loadParameters.provisionalLoadErrorURLString);
1277     m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1278     loadStringImpl(0, loadParameters.string, ASCIILiteral("text/html"), baseURL, unreachableURL, loadParameters.userData);
1279     m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1280 }
1281
1282 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1283 {
1284     Frame* mainFrame = m_mainFrame->coreFrame();
1285     Document* mainFrameDocument = mainFrame->document();
1286     if (!mainFrameDocument)
1287         return;
1288
1289     const int singleClick = 1;
1290     RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, true, true, currentTime(), nullptr, singleClick, screenPoint.x(), screenPoint.y(), documentPoint.x(), documentPoint.y(),
1291 #if ENABLE(POINTER_LOCK)
1292         0, 0,
1293 #endif
1294         false, false, false, false, 0, nullptr, 0, WebCore::NoTap, nullptr);
1295
1296     mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1297 }
1298
1299 void WebPage::stopLoadingFrame(uint64_t frameID)
1300 {
1301     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1302     if (!frame)
1303         return;
1304
1305     corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1306 }
1307
1308 void WebPage::stopLoading()
1309 {
1310     SendStopResponsivenessTimer stopper;
1311
1312     corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1313 }
1314
1315 bool WebPage::defersLoading() const
1316 {
1317     return m_page->defersLoading();
1318 }
1319
1320 void WebPage::setDefersLoading(bool defersLoading)
1321 {
1322     m_page->setDefersLoading(defersLoading);
1323 }
1324
1325 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, const SandboxExtension::Handle& sandboxExtensionHandle)
1326 {
1327     SendStopResponsivenessTimer stopper;
1328
1329     ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1330     m_pendingNavigationID = navigationID;
1331
1332     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1333     corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1334 }
1335
1336 void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID)
1337 {
1338     SendStopResponsivenessTimer stopper;
1339
1340     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1341     ASSERT(item);
1342     if (!item)
1343         return;
1344
1345     ASSERT(!m_pendingNavigationID);
1346     m_pendingNavigationID = navigationID;
1347
1348     m_page->goToItem(*item, FrameLoadType::Forward);
1349 }
1350
1351 void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID)
1352 {
1353     SendStopResponsivenessTimer stopper;
1354
1355     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1356     ASSERT(item);
1357     if (!item)
1358         return;
1359
1360     ASSERT(!m_pendingNavigationID);
1361     m_pendingNavigationID = navigationID;
1362
1363     m_page->goToItem(*item, FrameLoadType::Back);
1364 }
1365
1366 void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID)
1367 {
1368     SendStopResponsivenessTimer stopper;
1369
1370     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1371     ASSERT(item);
1372     if (!item)
1373         return;
1374
1375     ASSERT(!m_pendingNavigationID);
1376     m_pendingNavigationID = navigationID;
1377
1378     m_page->goToItem(*item, FrameLoadType::IndexedBackForward);
1379 }
1380
1381 void WebPage::tryRestoreScrollPosition()
1382 {
1383     m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1384 }
1385
1386 void WebPage::layoutIfNeeded()
1387 {
1388     if (m_mainFrame->coreFrame()->view())
1389         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1390 }
1391
1392 WebPage* WebPage::fromCorePage(Page* page)
1393 {
1394     return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1395 }
1396
1397 void WebPage::setSize(const WebCore::IntSize& viewSize)
1398 {
1399     if (m_viewSize == viewSize)
1400         return;
1401
1402     m_viewSize = viewSize;
1403     FrameView* view = m_page->mainFrame().view();
1404     view->resize(viewSize);
1405     m_drawingArea->setNeedsDisplay();
1406
1407 #if USE(COORDINATED_GRAPHICS)
1408     if (view->useFixedLayout())
1409         sendViewportAttributesChanged(m_page->viewportArguments());
1410 #endif
1411 }
1412
1413 #if USE(COORDINATED_GRAPHICS)
1414 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1415 {
1416     FrameView* view = m_page->mainFrame().view();
1417     ASSERT(view && view->useFixedLayout());
1418
1419     // Viewport properties have no impact on zero sized fixed viewports.
1420     if (m_viewSize.isEmpty())
1421         return;
1422
1423     // Recalculate the recommended layout size, when the available size (device pixel) changes.
1424     Settings& settings = m_page->settings();
1425
1426     int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1427
1428     // If unset  we use the viewport dimensions. This fits with the behavior of desktop browsers.
1429     int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1430     int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1431
1432     ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1433
1434     // If no layout was done yet set contentFixedOrigin to (0,0).
1435     IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1436
1437     // Put the width and height to the viewport width and height. In css units however.
1438     // Use FloatSize to avoid truncated values during scale.
1439     FloatSize contentFixedSize = m_viewSize;
1440
1441 #if ENABLE(CSS_DEVICE_ADAPTATION)
1442     // CSS viewport descriptors might be applied to already affected viewport size
1443     // if the page enables/disables stylesheets, so need to keep initial viewport size.
1444     view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1445 #endif
1446
1447     contentFixedSize.scale(1 / attr.initialScale);
1448     view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1449
1450     attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1451
1452     // This also takes care of the relayout.
1453     setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1454
1455 #if USE(COORDINATED_GRAPHICS_THREADED)
1456     m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1457 #else
1458     send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1459 #endif
1460 }
1461 #endif
1462
1463 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1464 {
1465     FrameView* frameView = m_page->mainFrame().view();
1466
1467     ScrollPosition scrollPosition = frameView->scrollPosition();
1468     ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1469
1470     // If the current scroll position in a direction is the max scroll position 
1471     // we don't want to scroll at all.
1472     IntSize newScrollOffset;
1473     if (scrollPosition.x() < maximumScrollPosition.x())
1474         newScrollOffset.setWidth(scrollOffset.width());
1475     if (scrollPosition.y() < maximumScrollPosition.y())
1476         newScrollOffset.setHeight(scrollOffset.height());
1477
1478     if (newScrollOffset.isZero())
1479         return;
1480
1481     frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1482 }
1483
1484 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1485 {
1486     GraphicsContextStateSaver stateSaver(graphicsContext);
1487     graphicsContext.clip(rect);
1488
1489     m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1490 }
1491
1492 double WebPage::textZoomFactor() const
1493 {
1494     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1495     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1496         if (pluginView->handlesPageScaleFactor())
1497             return pluginView->pageScaleFactor();
1498         return pageScaleFactor();
1499     }
1500
1501     Frame* frame = m_mainFrame->coreFrame();
1502     if (!frame)
1503         return 1;
1504     return frame->textZoomFactor();
1505 }
1506
1507 void WebPage::setTextZoomFactor(double zoomFactor)
1508 {
1509     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1510     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1511         if (pluginView->handlesPageScaleFactor())
1512             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1513         else
1514             scalePage(zoomFactor, IntPoint());
1515         return;
1516     }
1517
1518     Frame* frame = m_mainFrame->coreFrame();
1519     if (!frame)
1520         return;
1521     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1522 }
1523
1524 double WebPage::pageZoomFactor() const
1525 {
1526     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1527     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1528         if (pluginView->handlesPageScaleFactor())
1529             return pluginView->pageScaleFactor();
1530         return pageScaleFactor();
1531     }
1532
1533     Frame* frame = m_mainFrame->coreFrame();
1534     if (!frame)
1535         return 1;
1536     return frame->pageZoomFactor();
1537 }
1538
1539 void WebPage::setPageZoomFactor(double zoomFactor)
1540 {
1541     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1542     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1543         if (pluginView->handlesPageScaleFactor())
1544             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1545         else
1546             scalePage(zoomFactor, IntPoint());
1547         return;
1548     }
1549
1550     Frame* frame = m_mainFrame->coreFrame();
1551     if (!frame)
1552         return;
1553     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1554 }
1555
1556 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1557 {
1558     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1559     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1560         if (pluginView->handlesPageScaleFactor())
1561             pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1562         else
1563             scalePage(pageZoomFactor, IntPoint());
1564         return;
1565     }
1566
1567     Frame* frame = m_mainFrame->coreFrame();
1568     if (!frame)
1569         return;
1570     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1571 }
1572
1573 void WebPage::windowScreenDidChange(uint32_t displayID)
1574 {
1575     m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1576 }
1577
1578 void WebPage::scalePage(double scale, const IntPoint& origin)
1579 {
1580     double totalScale = scale * viewScaleFactor();
1581     bool willChangeScaleFactor = totalScale != totalScaleFactor();
1582
1583 #if PLATFORM(IOS)
1584     if (willChangeScaleFactor) {
1585         if (!m_inDynamicSizeUpdate)
1586             m_dynamicSizeUpdateHistory.clear();
1587         m_scaleWasSetByUIProcess = false;
1588     }
1589 #endif
1590     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1591     if (pluginView && pluginView->handlesPageScaleFactor()) {
1592         // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1593         // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1594         if (m_page->pageScaleFactor() != 1) {
1595             m_page->setPageScaleFactor(1, origin);
1596             for (auto* pluginView : m_pluginViews)
1597                 pluginView->pageScaleFactorDidChange();
1598         }
1599
1600         pluginView->setPageScaleFactor(totalScale, origin);
1601         return;
1602     }
1603
1604     m_page->setPageScaleFactor(totalScale, origin);
1605
1606     // We can't early return before setPageScaleFactor because the origin might be different.
1607     if (!willChangeScaleFactor)
1608         return;
1609
1610     for (auto* pluginView : m_pluginViews)
1611         pluginView->pageScaleFactorDidChange();
1612
1613 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1614     m_drawingArea->deviceOrPageScaleFactorChanged();
1615 #endif
1616
1617     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1618 }
1619
1620 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1621 {
1622     double totalScale = scale * viewScaleFactor();
1623     if (totalScale == totalScaleFactor())
1624         return;
1625
1626     IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1627     double scaleRatio = scale / pageScaleFactor();
1628     scrollPositionAtNewScale.scale(scaleRatio);
1629     scalePage(scale, scrollPositionAtNewScale);
1630 }
1631
1632 double WebPage::totalScaleFactor() const
1633 {
1634     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1635     if (pluginView && pluginView->handlesPageScaleFactor())
1636         return pluginView->pageScaleFactor();
1637
1638     return m_page->pageScaleFactor();
1639 }
1640
1641 double WebPage::pageScaleFactor() const
1642 {
1643     return totalScaleFactor() / viewScaleFactor();
1644 }
1645
1646 double WebPage::viewScaleFactor() const
1647 {
1648     return m_page->viewScaleFactor();
1649 }
1650
1651 void WebPage::scaleView(double scale)
1652 {
1653     if (viewScaleFactor() == scale)
1654         return;
1655
1656     float pageScale = pageScaleFactor();
1657
1658     IntPoint scrollPositionAtNewScale;
1659     if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1660         double scaleRatio = scale / viewScaleFactor();
1661         scrollPositionAtNewScale = mainFrameView->scrollPosition();
1662         scrollPositionAtNewScale.scale(scaleRatio);
1663     }
1664
1665     m_page->setViewScaleFactor(scale);
1666     scalePage(pageScale, scrollPositionAtNewScale);
1667 }
1668
1669 void WebPage::setDeviceScaleFactor(float scaleFactor)
1670 {
1671     if (scaleFactor == m_page->deviceScaleFactor())
1672         return;
1673
1674     m_page->setDeviceScaleFactor(scaleFactor);
1675
1676     // Tell all our plug-in views that the device scale factor changed.
1677 #if PLATFORM(MAC)
1678     for (auto* pluginView : m_pluginViews)
1679         pluginView->setDeviceScaleFactor(scaleFactor);
1680
1681     updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1682 #endif
1683
1684     if (findController().isShowingOverlay()) {
1685         // We must have updated layout to get the selection rects right.
1686         layoutIfNeeded();
1687         findController().deviceScaleFactorDidChange();
1688     }
1689
1690 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1691     m_drawingArea->deviceOrPageScaleFactorChanged();
1692 #endif
1693 }
1694
1695 float WebPage::deviceScaleFactor() const
1696 {
1697     return m_page->deviceScaleFactor();
1698 }
1699
1700 void WebPage::accessibilitySettingsDidChange()
1701 {
1702     m_page->accessibilitySettingsDidChange();
1703 }
1704
1705 void WebPage::setUseFixedLayout(bool fixed)
1706 {
1707     // Do not overwrite current settings if initially setting it to false.
1708     if (m_useFixedLayout == fixed)
1709         return;
1710     m_useFixedLayout = fixed;
1711
1712 #if !PLATFORM(IOS)
1713     m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1714 #endif
1715 #if USE(COORDINATED_GRAPHICS)
1716     m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1717     m_page->settings().setDelegatesPageScaling(fixed);
1718     m_page->settings().setScrollingCoordinatorEnabled(fixed);
1719 #endif
1720
1721 #if USE(COORDINATED_GRAPHICS) && ENABLE(SMOOTH_SCROLLING)
1722     // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1723     // Ensure we don't do animated scrolling in the WebProcess in that case.
1724     m_page->settings().setScrollAnimatorEnabled(!fixed);
1725 #endif
1726
1727     FrameView* view = mainFrameView();
1728     if (!view)
1729         return;
1730
1731 #if USE(COORDINATED_GRAPHICS)
1732     view->setDelegatesScrolling(fixed);
1733     view->setPaintsEntireContents(fixed);
1734 #endif
1735     view->setUseFixedLayout(fixed);
1736     if (!fixed)
1737         setFixedLayoutSize(IntSize());
1738
1739     send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1740 }
1741
1742 bool WebPage::setFixedLayoutSize(const IntSize& size)
1743 {
1744     FrameView* view = mainFrameView();
1745     if (!view || view->fixedLayoutSize() == size)
1746         return false;
1747
1748     view->setFixedLayoutSize(size);
1749
1750     send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1751     return true;
1752 }
1753
1754 IntSize WebPage::fixedLayoutSize() const
1755 {
1756     FrameView* view = mainFrameView();
1757     if (!view)
1758         return IntSize();
1759     return view->fixedLayoutSize();
1760 }
1761
1762 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
1763 {
1764 #if PLATFORM(IOS)
1765     if (m_viewportConfiguration.setViewportArguments(viewportArguments))
1766         viewportConfigurationChanged();
1767 #endif
1768
1769 #if USE(COORDINATED_GRAPHICS)
1770     FrameView* view = m_page->mainFrame().view();
1771     if (view && view->useFixedLayout())
1772         sendViewportAttributesChanged(viewportArguments);
1773 #if USE(COORDINATED_GRAPHICS_THREADED)
1774     else
1775         m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
1776 #endif
1777 #endif
1778
1779 #if !PLATFORM(IOS) && !USE(COORDINATED_GRAPHICS)
1780     UNUSED_PARAM(viewportArguments);
1781 #endif
1782 }
1783
1784 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1785 {
1786     if (!m_page)
1787         return;
1788     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1789 }
1790
1791 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1792 {
1793     m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1794 }
1795     
1796 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1797 {
1798     m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1799 }
1800     
1801 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1802 {
1803     m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1804 }
1805
1806 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1807 {
1808     if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1809         m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1810 }
1811
1812 void WebPage::setPaginationMode(uint32_t mode)
1813 {
1814     Pagination pagination = m_page->pagination();
1815     pagination.mode = static_cast<Pagination::Mode>(mode);
1816     m_page->setPagination(pagination);
1817 }
1818
1819 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1820 {
1821     Pagination pagination = m_page->pagination();
1822     pagination.behavesLikeColumns = behavesLikeColumns;
1823     m_page->setPagination(pagination);
1824 }
1825
1826 void WebPage::setPageLength(double pageLength)
1827 {
1828     Pagination pagination = m_page->pagination();
1829     pagination.pageLength = pageLength;
1830     m_page->setPagination(pagination);
1831 }
1832
1833 void WebPage::setGapBetweenPages(double gap)
1834 {
1835     Pagination pagination = m_page->pagination();
1836     pagination.gap = gap;
1837     m_page->setPagination(pagination);
1838 }
1839
1840 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
1841 {
1842     m_page->setPaginationLineGridEnabled(lineGridEnabled);
1843 }
1844
1845 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1846 {
1847     auto& webProcess = WebProcess::singleton();
1848     InjectedBundle* injectedBundle = webProcess.injectedBundle();
1849     if (!injectedBundle)
1850         return;
1851
1852     injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1853 }
1854
1855 #if !PLATFORM(IOS)
1856
1857 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
1858 {
1859     if (m_headerBanner)
1860         m_headerBanner->detachFromPage();
1861
1862     m_headerBanner = pageBanner;
1863
1864     if (m_headerBanner)
1865         m_headerBanner->addToPage(PageBanner::Header, this);
1866 }
1867
1868 PageBanner* WebPage::headerPageBanner()
1869 {
1870     return m_headerBanner.get();
1871 }
1872
1873 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
1874 {
1875     if (m_footerBanner)
1876         m_footerBanner->detachFromPage();
1877
1878     m_footerBanner = pageBanner;
1879
1880     if (m_footerBanner)
1881         m_footerBanner->addToPage(PageBanner::Footer, this);
1882 }
1883
1884 PageBanner* WebPage::footerPageBanner()
1885 {
1886     return m_footerBanner.get();
1887 }
1888
1889 void WebPage::hidePageBanners()
1890 {
1891     if (m_headerBanner)
1892         m_headerBanner->hide();
1893     if (m_footerBanner)
1894         m_footerBanner->hide();
1895 }
1896
1897 void WebPage::showPageBanners()
1898 {
1899     if (m_headerBanner)
1900         m_headerBanner->showIfHidden();
1901     if (m_footerBanner)
1902         m_footerBanner->showIfHidden();
1903 }
1904
1905 void WebPage::setHeaderBannerHeightForTesting(int height)
1906 {
1907 #if ENABLE(RUBBER_BANDING)
1908     corePage()->addHeaderWithHeight(height);
1909 #endif
1910 }
1911
1912 void WebPage::setFooterBannerHeightForTesting(int height)
1913 {
1914 #if ENABLE(RUBBER_BANDING)
1915     corePage()->addFooterWithHeight(height);
1916 #endif
1917 }
1918
1919 #endif // !PLATFORM(IOS)
1920
1921 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
1922 {
1923     SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1924     snapshotOptions |= SnapshotOptionsShareable;
1925
1926     RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1927
1928     ShareableBitmap::Handle handle;
1929     if (image)
1930         image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
1931
1932     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1933 }
1934
1935 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1936 {
1937     IntRect snapshotRect = rect;
1938     IntSize bitmapSize = snapshotRect.size();
1939     if (options & SnapshotOptionsPrinting) {
1940         ASSERT(additionalScaleFactor == 1);
1941         Frame* coreFrame = m_mainFrame->coreFrame();
1942         if (!coreFrame)
1943             return nullptr;
1944         bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
1945     } else {
1946         double scaleFactor = additionalScaleFactor;
1947         if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1948             scaleFactor *= corePage()->deviceScaleFactor();
1949         bitmapSize.scale(scaleFactor);
1950     }
1951
1952     return snapshotAtSize(rect, bitmapSize, options);
1953 }
1954
1955 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
1956 {
1957     IntRect snapshotRect = rect;
1958     float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1959     float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1960     float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1961
1962     if (options & SnapshotOptionsPrinting) {
1963         PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
1964         return;
1965     }
1966
1967     Color documentBackgroundColor = frameView.documentBackgroundColor();
1968     Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
1969     graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
1970
1971     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1972         double deviceScaleFactor = frame.page()->deviceScaleFactor();
1973         graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
1974         scaleFactor /= deviceScaleFactor;
1975     }
1976
1977     graphicsContext.scale(scaleFactor);
1978     graphicsContext.translate(-snapshotRect.x(), -snapshotRect.y());
1979
1980     FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1981     if (options & SnapshotOptionsExcludeSelectionHighlighting)
1982         shouldPaintSelection = FrameView::ExcludeSelection;
1983
1984     FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1985     if (options & SnapshotOptionsInViewCoordinates)
1986         coordinateSpace = FrameView::ViewCoordinates;
1987
1988     frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
1989
1990     if (options & SnapshotOptionsPaintSelectionRectangle) {
1991         FloatRect selectionRectangle = frame.selection().selectionBounds();
1992         graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
1993         graphicsContext.strokeRect(selectionRectangle, 1);
1994     }
1995 }
1996
1997 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1998 {
1999     Frame* coreFrame = m_mainFrame->coreFrame();
2000     if (!coreFrame)
2001         return nullptr;
2002
2003     FrameView* frameView = coreFrame->view();
2004     if (!frameView)
2005         return nullptr;
2006
2007     auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
2008     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2009
2010     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2011
2012     return snapshot;
2013 }
2014
2015 #if USE(CF)
2016 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2017 {
2018     Frame* coreFrame = m_mainFrame->coreFrame();
2019     if (!coreFrame)
2020         return nullptr;
2021
2022     FrameView* frameView = coreFrame->view();
2023     if (!frameView)
2024         return nullptr;
2025
2026     auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2027
2028 #if USE(CG)
2029     auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2030     auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2031     auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2032
2033     CGPDFContextBeginPage(pdfContext.get(), nullptr);
2034
2035     GraphicsContext graphicsContext { pdfContext.get() };
2036     graphicsContext.scale({ 1, -1 });
2037     graphicsContext.translate(0, -bitmapSize.height());
2038     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2039
2040     CGPDFContextEndPage(pdfContext.get());
2041     CGPDFContextClose(pdfContext.get());
2042 #endif
2043
2044     return WTFMove(data);
2045 }
2046 #endif
2047
2048 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2049 {
2050     Frame* coreFrame = m_mainFrame->coreFrame();
2051     if (!coreFrame)
2052         return nullptr;
2053
2054     FrameView* frameView = coreFrame->view();
2055     if (!frameView)
2056         return nullptr;
2057
2058     if (!node.renderer())
2059         return nullptr;
2060
2061     LayoutRect topLevelRect;
2062     IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2063     if (snapshotRect.isEmpty())
2064         return nullptr;
2065
2066     double scaleFactor = 1;
2067     IntSize snapshotSize = snapshotRect.size();
2068     unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2069     if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2070         scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2071         snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2072     }
2073
2074     auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options));
2075
2076     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2077
2078     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2079         double deviceScaleFactor = corePage()->deviceScaleFactor();
2080         graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2081         scaleFactor /= deviceScaleFactor;
2082     }
2083
2084     graphicsContext->scale(scaleFactor);
2085     graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
2086
2087     Color savedBackgroundColor = frameView->baseBackgroundColor();
2088     frameView->setBaseBackgroundColor(Color::transparent);
2089     frameView->setNodeToDraw(&node);
2090
2091     frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2092
2093     frameView->setBaseBackgroundColor(savedBackgroundColor);
2094     frameView->setNodeToDraw(nullptr);
2095
2096     return snapshot;
2097 }
2098
2099 void WebPage::pageDidScroll()
2100 {
2101 #if PLATFORM(IOS)
2102     if (!m_inDynamicSizeUpdate)
2103         m_dynamicSizeUpdateHistory.clear();
2104 #endif
2105     m_uiClient->pageDidScroll(this);
2106
2107     m_pageScrolledHysteresis.impulse();
2108
2109     send(Messages::WebPageProxy::PageDidScroll());
2110 }
2111
2112 void WebPage::pageStoppedScrolling()
2113 {
2114     // Maintain the current history item's scroll position up-to-date.
2115     if (Frame* frame = m_mainFrame->coreFrame())
2116         frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2117 }
2118
2119 #if USE(COORDINATED_GRAPHICS)
2120 void WebPage::pageDidRequestScroll(const IntPoint& point)
2121 {
2122 #if USE(COORDINATED_GRAPHICS_THREADED)
2123     drawingArea()->scroll(IntRect(point, IntSize()), IntSize());
2124 #endif
2125 }
2126 #endif
2127
2128 #if ENABLE(CONTEXT_MENUS)
2129 WebContextMenu* WebPage::contextMenu()
2130 {
2131     if (!m_contextMenu)
2132         m_contextMenu = WebContextMenu::create(this);
2133     return m_contextMenu.get();
2134 }
2135
2136 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2137 {
2138     corePage()->contextMenuController().clearContextMenu();
2139
2140     // Simulate a mouse click to generate the correct menu.
2141     PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick, WebCore::NoTap);
2142     corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2143     bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2144     auto* menu = handled ? contextMenu() : nullptr;
2145     PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick, WebCore::NoTap);
2146     corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2147
2148     return menu;
2149 }
2150 #endif
2151
2152 // Events 
2153
2154 static const WebEvent* g_currentEvent = 0;
2155
2156 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2157 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2158 // platform events passed to the event handler code.
2159 const WebEvent* WebPage::currentEvent()
2160 {
2161     return g_currentEvent;
2162 }
2163
2164 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
2165 {
2166     auto* drawingArea = this->drawingArea();
2167     if (!drawingArea)
2168         return;
2169
2170     drawingArea->setLayerTreeStateIsFrozen(frozen);
2171 }
2172
2173 void WebPage::callVolatilityCompletionHandlers()
2174 {
2175     auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2176     for (auto& completionHandler : completionHandlers)
2177         completionHandler();
2178 }
2179
2180 void WebPage::layerVolatilityTimerFired()
2181 {
2182     Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2183     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2184     if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2185         m_layerVolatilityTimer.stop();
2186         RELEASE_LOG_IF_ALLOWED("%p - WebPage - Attempted to mark layers as volatile, success? %d", this, didSucceed);
2187         callVolatilityCompletionHandlers();
2188         return;
2189     }
2190
2191     RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.value() * 1000);
2192     m_layerVolatilityTimer.startRepeating(newInterval);
2193 }
2194
2195 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2196 {
2197     return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2198 }
2199
2200 void WebPage::markLayersVolatile(WTF::Function<void ()>&& completionHandler)
2201 {
2202     RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2203
2204     if (m_layerVolatilityTimer.isActive())
2205         m_layerVolatilityTimer.stop();
2206
2207     if (completionHandler)
2208         m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2209
2210     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2211     if (didSucceed || m_isSuspendedUnderLock) {
2212         if (didSucceed)
2213             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2214         else {
2215             // 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.
2216             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2217         }
2218         callVolatilityCompletionHandlers();
2219         return;
2220     }
2221
2222     RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.value() * 1000);
2223     m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2224 }
2225
2226 void WebPage::cancelMarkLayersVolatile()
2227 {
2228     RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2229     m_layerVolatilityTimer.stop();
2230     m_markLayersAsVolatileCompletionHandlers.clear();
2231 }
2232
2233 class CurrentEvent {
2234 public:
2235     explicit CurrentEvent(const WebEvent& event)
2236         : m_previousCurrentEvent(g_currentEvent)
2237     {
2238         g_currentEvent = &event;
2239     }
2240
2241     ~CurrentEvent()
2242     {
2243         g_currentEvent = m_previousCurrentEvent;
2244     }
2245
2246 private:
2247     const WebEvent* m_previousCurrentEvent;
2248 };
2249
2250 #if ENABLE(CONTEXT_MENUS)
2251 static bool isContextClick(const PlatformMouseEvent& event)
2252 {
2253 #if PLATFORM(COCOA)
2254     return WebEventFactory::shouldBeHandledAsContextClick(event);
2255 #else
2256     return event.button() == WebCore::RightButton;
2257 #endif
2258 }
2259
2260 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2261 {
2262     IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2263     HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2264
2265     Frame* frame = &page->corePage()->mainFrame();
2266     if (result.innerNonSharedNode())
2267         frame = result.innerNonSharedNode()->document().frame();
2268
2269     bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2270     if (handled)
2271         page->contextMenu()->show();
2272
2273     return handled;
2274 }
2275
2276 void WebPage::contextMenuForKeyEvent()
2277 {
2278     corePage()->contextMenuController().clearContextMenu();
2279
2280     Frame& frame = m_page->focusController().focusedOrMainFrame();
2281     bool handled = frame.eventHandler().sendContextMenuEventForKey();
2282     if (handled)
2283         contextMenu()->show();
2284 }
2285 #endif
2286
2287 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2288 {
2289     Frame& frame = page->corePage()->mainFrame();
2290     if (!frame.view())
2291         return false;
2292
2293     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2294
2295     switch (platformMouseEvent.type()) {
2296         case PlatformEvent::MousePressed: {
2297 #if ENABLE(CONTEXT_MENUS)
2298             if (isContextClick(platformMouseEvent))
2299                 page->corePage()->contextMenuController().clearContextMenu();
2300 #endif
2301
2302             bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2303 #if ENABLE(CONTEXT_MENUS)
2304             if (isContextClick(platformMouseEvent))
2305                 handled = handleContextMenuEvent(platformMouseEvent, page);
2306 #endif
2307             return handled;
2308         }
2309         case PlatformEvent::MouseReleased:
2310             return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2311
2312         case PlatformEvent::MouseMoved:
2313 #if PLATFORM(COCOA)
2314             // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2315             // button is currently pressed. It is possible that neither of those things will be true since on
2316             // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2317             // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2318             // efficient scrollbars-only version of the event.
2319             if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2320                 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2321 #endif
2322             return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2323
2324         case PlatformEvent::MouseForceChanged:
2325         case PlatformEvent::MouseForceDown:
2326         case PlatformEvent::MouseForceUp:
2327             return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2328
2329         default:
2330             ASSERT_NOT_REACHED();
2331             return false;
2332     }
2333 }
2334
2335 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2336 {
2337     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2338
2339     m_userActivityHysteresis.impulse();
2340
2341     bool shouldHandleEvent = true;
2342
2343 #if ENABLE(CONTEXT_MENUS)
2344     // Don't try to handle any pending mouse events if a context menu is showing.
2345     if (m_isShowingContextMenu)
2346         shouldHandleEvent = false;
2347 #endif
2348 #if ENABLE(DRAG_SUPPORT)
2349     if (m_isStartingDrag)
2350         shouldHandleEvent = false;
2351 #endif
2352
2353     if (!shouldHandleEvent) {
2354         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2355         return;
2356     }
2357
2358     bool handled = false;
2359
2360 #if !PLATFORM(IOS)
2361     if (!handled && m_headerBanner)
2362         handled = m_headerBanner->mouseEvent(mouseEvent);
2363     if (!handled && m_footerBanner)
2364         handled = m_footerBanner->mouseEvent(mouseEvent);
2365 #endif // !PLATFORM(IOS)
2366
2367     if (!handled) {
2368         CurrentEvent currentEvent(mouseEvent);
2369         handled = handleMouseEvent(mouseEvent, this);
2370     }
2371
2372     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2373 }
2374
2375 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2376 {
2377     Frame& frame = page->mainFrame();
2378     if (!frame.view())
2379         return false;
2380
2381     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2382     return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2383 }
2384
2385 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2386 {
2387     m_userActivityHysteresis.impulse();
2388
2389     CurrentEvent currentEvent(wheelEvent);
2390
2391     bool handled = handleWheelEvent(wheelEvent, m_page.get());
2392
2393     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2394 }
2395
2396 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2397 {
2398     if (!page->mainFrame().view())
2399         return false;
2400
2401     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2402         return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2403     return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2404 }
2405
2406 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2407 {
2408     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2409
2410     m_userActivityHysteresis.impulse();
2411
2412     CurrentEvent currentEvent(keyboardEvent);
2413
2414     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2415     // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2416     if (!handled)
2417         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2418
2419     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2420 }
2421
2422 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2423 {
2424     bool isEnabled = false;
2425     int32_t state = 0;
2426     Frame& frame = m_page->focusController().focusedOrMainFrame();
2427     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2428         isEnabled = pluginView->isEditingCommandEnabled(commandName);
2429     else {
2430         Editor::Command command = frame.editor().command(commandName);
2431         state = command.state();
2432         isEnabled = command.isSupported() && command.isEnabled();
2433     }
2434
2435     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2436 }
2437
2438 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2439 {
2440     executeEditingCommand(commandName, argument);
2441 }
2442
2443 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest)
2444 {
2445     for (const auto& itemState : itemStates) {
2446         auto historyItem = toHistoryItem(itemState.pageState);
2447         historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2448         static_cast<WebBackForwardListProxy*>(corePage()->backForward().client())->addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID);
2449     }
2450 }
2451
2452 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2453 {
2454     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes);
2455 }
2456
2457 #if ENABLE(TOUCH_EVENTS)
2458 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2459 {
2460     if (!page->mainFrame().view())
2461         return false;
2462
2463     return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2464 }
2465 #endif
2466
2467 #if ENABLE(IOS_TOUCH_EVENTS)
2468 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2469 {
2470     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2471
2472     m_lastInteractionLocation = touchEvent.position();
2473     CurrentEvent currentEvent(touchEvent);
2474     handled = handleTouchEvent(touchEvent, m_page.get());
2475 }
2476
2477 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2478 {
2479     EventDispatcher::TouchEventQueue queuedEvents;
2480     WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2481     dispatchAsynchronousTouchEvents(queuedEvents);
2482
2483     dispatchTouchEvent(touchEvent, handled);
2484 }
2485 #elif ENABLE(TOUCH_EVENTS)
2486 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2487 {
2488     CurrentEvent currentEvent(touchEvent);
2489
2490     bool handled = handleTouchEvent(touchEvent, m_page.get());
2491
2492     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2493 }
2494 #endif
2495
2496 #if ENABLE(MAC_GESTURE_EVENTS)
2497 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2498 {
2499     if (!page->mainFrame().view())
2500         return false;
2501
2502     return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2503 }
2504
2505 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2506 {
2507     CurrentEvent currentEvent(gestureEvent);
2508     bool handled = handleGestureEvent(gestureEvent, m_page.get());
2509     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2510 }
2511 #endif
2512
2513 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2514 {
2515     return page->userInputBridge().scrollRecursively(direction, granularity);
2516 }
2517
2518 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2519 {
2520     return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2521 }
2522
2523 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2524 {
2525     return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2526 }
2527
2528 void WebPage::centerSelectionInVisibleArea()
2529 {
2530     Frame& frame = m_page->focusController().focusedOrMainFrame();
2531     frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2532     findController().showFindIndicatorInSelection();
2533 }
2534
2535 bool WebPage::isControlledByAutomation() const
2536 {
2537     return m_page->isControlledByAutomation();
2538 }
2539
2540 void WebPage::setControlledByAutomation(bool controlled)
2541 {
2542     m_page->setControlledByAutomation(controlled);
2543 }
2544
2545 void WebPage::insertNewlineInQuotedContent()
2546 {
2547     Frame& frame = m_page->focusController().focusedOrMainFrame();
2548     if (frame.selection().isNone())
2549         return;
2550     frame.editor().insertParagraphSeparatorInQuotedContent();
2551 }
2552
2553 #if ENABLE(REMOTE_INSPECTOR)
2554 void WebPage::setAllowsRemoteInspection(bool allow)
2555 {
2556     m_page->setRemoteInspectionAllowed(allow);
2557 }
2558
2559 void WebPage::setRemoteInspectionNameOverride(const String& name)
2560 {
2561     m_page->setRemoteInspectionNameOverride(name);
2562 }
2563 #endif
2564
2565 void WebPage::setDrawsBackground(bool drawsBackground)
2566 {
2567     if (m_drawsBackground == drawsBackground)
2568         return;
2569
2570     m_drawsBackground = drawsBackground;
2571
2572     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2573         if (FrameView* view = coreFrame->view())
2574             view->setTransparent(!drawsBackground);
2575     }
2576
2577     m_drawingArea->pageBackgroundTransparencyChanged();
2578     m_drawingArea->setNeedsDisplay();
2579 }
2580
2581 #if PLATFORM(COCOA)
2582 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
2583 {
2584     m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
2585
2586     setTopContentInset(contentInset);
2587
2588     mach_port_deallocate(mach_task_self(), fencePort.port());
2589 }
2590 #endif
2591
2592 void WebPage::setTopContentInset(float contentInset)
2593 {
2594     if (contentInset == m_page->topContentInset())
2595         return;
2596
2597     m_page->setTopContentInset(contentInset);
2598
2599     for (auto* pluginView : m_pluginViews)
2600         pluginView->topContentInsetDidChange();
2601 }
2602
2603 void WebPage::viewWillStartLiveResize()
2604 {
2605     if (!m_page)
2606         return;
2607
2608     // FIXME: This should propagate to all ScrollableAreas.
2609     Frame& frame = m_page->focusController().focusedOrMainFrame();
2610     if (FrameView* view = frame.view())
2611         view->willStartLiveResize();
2612 }
2613
2614 void WebPage::viewWillEndLiveResize()
2615 {
2616     if (!m_page)
2617         return;
2618
2619     // FIXME: This should propagate to all ScrollableAreas.
2620     Frame& frame = m_page->focusController().focusedOrMainFrame();
2621     if (FrameView* view = frame.view())
2622         view->willEndLiveResize();
2623 }
2624
2625 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
2626 {
2627     if (!m_page)
2628         return;
2629
2630     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2631
2632     Frame& frame = m_page->focusController().focusedOrMainFrame();
2633     frame.document()->setFocusedElement(0);
2634
2635     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2636         PlatformKeyboardEvent platformEvent(platform(event));
2637         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2638         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2639
2640         send(Messages::WebPageProxy::VoidCallback(callbackID));
2641         return;
2642     }
2643
2644     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
2645     send(Messages::WebPageProxy::VoidCallback(callbackID));
2646 }
2647
2648 void WebPage::setCanStartMediaTimerFired()
2649 {
2650     if (m_page)
2651         m_page->setCanStartMedia(true);
2652 }
2653
2654 void WebPage::updateIsInWindow(bool isInitialState)
2655 {
2656     bool isInWindow = m_activityState & WebCore::ActivityState::IsInWindow;
2657
2658     if (!isInWindow) {
2659         m_setCanStartMediaTimer.stop();
2660         m_page->setCanStartMedia(false);
2661         
2662         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2663         if (!isInitialState)
2664             WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2665     } else {
2666         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2667         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2668         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2669         if (m_mayStartMediaWhenInWindow)
2670             m_setCanStartMediaTimer.startOneShot(0_s);
2671
2672         WebProcess::singleton().pageDidEnterWindow(m_pageID);
2673     }
2674
2675     if (isInWindow)
2676         layoutIfNeeded();
2677 }
2678
2679 void WebPage::visibilityDidChange()
2680 {
2681     bool isVisible = m_activityState & ActivityState::IsVisible;
2682     if (!isVisible) {
2683         // We save the document / scroll state when backgrounding a tab so that we are able to restore it
2684         // if it gets terminated while in the background.
2685         if (auto* frame = m_mainFrame->coreFrame())
2686             frame->loader().history().saveDocumentAndScrollState();
2687     }
2688 }
2689
2690 void WebPage::setActivityState(ActivityState::Flags activityState, bool wantsDidUpdateActivityState, const Vector<CallbackID>& callbackIDs)
2691 {
2692     ActivityState::Flags changed = m_activityState ^ activityState;
2693     m_activityState = activityState;
2694
2695     if (changed)
2696         updateThrottleState();
2697
2698     m_page->setActivityState(activityState);
2699     for (auto* pluginView : m_pluginViews)
2700         pluginView->activityStateDidChange(changed);
2701
2702     m_drawingArea->activityStateDidChange(changed, wantsDidUpdateActivityState, callbackIDs);
2703     WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
2704
2705     if (changed & ActivityState::IsInWindow)
2706         updateIsInWindow();
2707
2708     if (changed & ActivityState::IsVisible)
2709         visibilityDidChange();
2710 }
2711
2712 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
2713 {
2714     m_layerHostingMode = layerHostingMode;
2715
2716     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2717
2718     for (auto* pluginView : m_pluginViews)
2719         pluginView->setLayerHostingMode(m_layerHostingMode);
2720 }
2721
2722 void WebPage::setSessionID(SessionID sessionID)
2723 {
2724     if (sessionID.isEphemeral())
2725         WebProcess::singleton().ensurePrivateBrowsingSession(sessionID);
2726     m_page->setSessionID(sessionID);
2727 }
2728
2729 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, const DownloadID& downloadID)
2730 {
2731     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2732     if (!frame)
2733         return;
2734     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID);
2735 }
2736
2737 void WebPage::didStartPageTransition()
2738 {
2739     m_drawingArea->setLayerTreeStateIsFrozen(true);
2740
2741 #if PLATFORM(MAC)
2742     bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
2743 #endif
2744     m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
2745     m_isAssistingNodeDueToUserInteraction = false;
2746     m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
2747 #if PLATFORM(MAC)
2748     if (hasPreviouslyFocusedDueToUserInteraction)
2749         send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
2750     if (m_needsHiddenContentEditableQuirk) {
2751         m_needsHiddenContentEditableQuirk = false;
2752         send(Messages::WebPageProxy::SetNeedsHiddenContentEditableQuirk(m_needsHiddenContentEditableQuirk));
2753     }
2754     if (m_needsPlainTextQuirk) {
2755         m_needsPlainTextQuirk = false;
2756         send(Messages::WebPageProxy::SetNeedsPlainTextQuirk(m_needsPlainTextQuirk));
2757     }
2758 #endif
2759 }
2760
2761 void WebPage::didCompletePageTransition()
2762 {
2763     m_drawingArea->setLayerTreeStateIsFrozen(false);
2764 }
2765
2766 void WebPage::show()
2767 {
2768     send(Messages::WebPageProxy::ShowPage());
2769 }
2770
2771 String WebPage::userAgent(const URL& webCoreURL) const
2772 {
2773     return userAgent(nullptr, webCoreURL);
2774 }
2775
2776 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2777 {
2778     if (frame) {
2779         String userAgent = m_loaderClient->userAgentForURL(*frame, webcoreURL);
2780         if (!userAgent.isEmpty())
2781             return userAgent;
2782     }
2783
2784     String userAgent = platformUserAgent(webcoreURL);
2785     if (!userAgent.isEmpty())
2786         return userAgent;
2787     return m_userAgent;
2788 }
2789     
2790 void WebPage::setUserAgent(const String& userAgent)
2791 {
2792     m_userAgent = userAgent;
2793 }
2794
2795 void WebPage::suspendActiveDOMObjectsAndAnimations()
2796 {
2797     m_page->suspendActiveDOMObjectsAndAnimations();
2798 }
2799
2800 void WebPage::resumeActiveDOMObjectsAndAnimations()
2801 {
2802     m_page->resumeActiveDOMObjectsAndAnimations();
2803 }
2804
2805 IntPoint WebPage::screenToRootView(const IntPoint& point)
2806 {
2807     IntPoint windowPoint;
2808     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2809     return windowPoint;
2810 }
2811     
2812 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2813 {
2814     IntRect screenRect;
2815     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2816     return screenRect;
2817 }
2818     
2819 #if PLATFORM(IOS)
2820 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2821 {
2822     IntPoint windowPoint;
2823     sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2824     return windowPoint;
2825 }
2826
2827 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2828 {
2829     IntRect screenRect;
2830     sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2831     return screenRect;
2832 }
2833 #endif
2834
2835 KeyboardUIMode WebPage::keyboardUIMode()
2836 {
2837     bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
2838     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2839 }
2840
2841 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
2842 {
2843     // NOTE: We need to be careful when running scripts that the objects we depend on don't
2844     // disappear during script execution.
2845
2846     RefPtr<SerializedScriptValue> serializedResultValue;
2847     JSLockHolder lock(commonVM());
2848     bool hadException = true;
2849     ExceptionDetails details;
2850     if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, forceUserGesture, &details)) {
2851         hadException = false;
2852         serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
2853             toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr);
2854     }
2855
2856     IPC::DataReference dataReference;
2857     if (serializedResultValue)
2858         dataReference = serializedResultValue->data();
2859     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
2860 }
2861
2862 void WebPage::getContentsAsString(CallbackID callbackID)
2863 {
2864     String resultString = m_mainFrame->contentsAsString();
2865     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2866 }
2867
2868 #if ENABLE(MHTML)
2869 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
2870 {
2871     auto buffer = MHTMLArchive::generateMHTMLData(m_page.get());
2872
2873     // FIXME: Use SharedBufferDataReference.
2874     IPC::DataReference dataReference;
2875     dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2876     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2877 }
2878 #endif
2879
2880 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
2881 {
2882     String resultString = renderTreeExternalRepresentation();
2883     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2884 }
2885
2886 static Frame* frameWithSelection(Page* page)
2887 {
2888     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2889         if (frame->selection().isRange())
2890             return frame;
2891     }
2892
2893     return 0;
2894 }
2895
2896 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
2897 {
2898 #if PLATFORM(COCOA)
2899     RetainPtr<CFDataRef> data;
2900     if (Frame* frame = frameWithSelection(m_page.get()))
2901         data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
2902 #endif
2903
2904     IPC::DataReference dataReference;
2905 #if PLATFORM(COCOA)
2906     if (data)
2907         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2908 #endif
2909     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2910 }
2911
2912 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
2913 {
2914     WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
2915     String resultString = focusedOrMainFrame->selectionAsString();
2916     if (resultString.isEmpty())
2917         resultString = focusedOrMainFrame->contentsAsString();
2918     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2919 }
2920
2921 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
2922 {
2923     String resultString;
2924     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2925        resultString = frame->source();
2926
2927     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2928 }
2929
2930 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
2931 {
2932     RefPtr<SharedBuffer> buffer;
2933     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2934         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
2935             buffer = pluginView->liveResourceData();
2936         if (!buffer) {
2937             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
2938                 buffer = loader->mainResourceData();
2939         }
2940     }
2941
2942     // FIXME: Use SharedBufferDataReference.
2943     IPC::DataReference dataReference;
2944     if (buffer)
2945         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2946     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2947 }
2948
2949 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2950 {
2951     DocumentLoader* loader = frame->loader().documentLoader();
2952     if (!loader)
2953         return nullptr;
2954
2955     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2956     if (!subresource)
2957         return nullptr;
2958
2959     return &subresource->data();
2960 }
2961
2962 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
2963 {
2964     RefPtr<SharedBuffer> buffer;
2965     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2966         URL resourceURL(URL(), resourceURLString);
2967         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2968         if (!buffer) {
2969             // Try to get the resource data from the cache.
2970             buffer = cachedResponseDataForURL(resourceURL);
2971         }
2972     }
2973
2974     // FIXME: Use SharedBufferDataReference.
2975     IPC::DataReference dataReference;
2976     if (buffer)
2977         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2978     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2979 }
2980
2981 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
2982 {
2983 #if PLATFORM(COCOA)
2984     RetainPtr<CFDataRef> data;
2985     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2986         data = frame->webArchiveData(nullptr, nullptr);
2987 #else
2988     UNUSED_PARAM(frameID);
2989 #endif
2990
2991     IPC::DataReference dataReference;
2992 #if PLATFORM(COCOA)
2993     if (data)
2994         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2995 #endif
2996     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2997 }
2998
2999 void WebPage::forceRepaintWithoutCallback()
3000 {
3001     m_drawingArea->forceRepaint();
3002 }
3003
3004 void WebPage::forceRepaint(CallbackID callbackID)
3005 {
3006     if (m_drawingArea->forceRepaintAsync(callbackID))
3007         return;
3008
3009     forceRepaintWithoutCallback();
3010     send(Messages::WebPageProxy::VoidCallback(callbackID));
3011 }
3012
3013 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3014 {
3015     WebPreferencesStore::removeTestRunnerOverrides();
3016     updatePreferences(store);
3017 }
3018
3019 void WebPage::updatePreferences(const WebPreferencesStore& store)
3020 {
3021     Settings& settings = m_page->settings();
3022
3023     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3024     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3025     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3026     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3027
3028     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3029
3030 #if PLATFORM(COCOA)
3031     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3032 #endif
3033
3034     // FIXME: This should be generated from macro expansion for all preferences,
3035     // but we currently don't match the naming of WebCore exactly so we are
3036     // handrolling the boolean and integer preferences until that is fixed.
3037
3038 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue, HumanReadableName, HumanReadableDescription) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
3039
3040     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
3041
3042 #undef INITIALIZE_SETTINGS
3043
3044     settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
3045     settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
3046     settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
3047     settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
3048     settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
3049     settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
3050     settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));    
3051     settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
3052     settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
3053     settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
3054     settings.setFrameFlattening(static_cast<WebCore::FrameFlattening>(store.getUInt32ValueForKey(WebPreferencesKey::frameFlatteningKey())));
3055     settings.setAsyncFrameScrollingEnabled(store.getBoolValueForKey(WebPreferencesKey::asyncFrameScrollingEnabledKey()));
3056     if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3057         setSessionID(SessionID::legacyPrivateSessionID());
3058     else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
3059         setSessionID(SessionID::defaultSessionID());
3060     settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
3061     settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3062     settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
3063     settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
3064     settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
3065     settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
3066     settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
3067     settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey()));
3068 #if ENABLE(WEB_ARCHIVE)
3069     settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
3070 #endif
3071     settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
3072     settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
3073     settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
3074     settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
3075     settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
3076     settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
3077     settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
3078     settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
3079     settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
3080     settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
3081     settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
3082     settings.setNeedsStorageAccessFromFileURLsQuirk(store.getBoolValueForKey(WebPreferencesKey::needsStorageAccessFromFileURLsQuirkKey()));
3083
3084     settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
3085     settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
3086     settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
3087     settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
3088     settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
3089     settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
3090     settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
3091     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3092     settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
3093
3094     settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
3095     settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
3096     settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
3097     settings.setDisplayListDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::displayListDrawingEnabledKey()));
3098     settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
3099     settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
3100     settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
3101     settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
3102     settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey()));
3103     settings.setUseGiantTiles(store.getBoolValueForKey(WebPreferencesKey::useGiantTilesKey()));
3104     settings.setSubpixelAntialiasedLayerTextEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelAntialiasedLayerTextEnabledKey()));
3105
3106     settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
3107     settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
3108 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
3109     RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey()));
3110 #endif
3111 #if ENABLE(WEB_ANIMATIONS)
3112     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled(store.getBoolValueForKey(WebPreferencesKey::webAnimationsEnabledKey()));
3113 #endif
3114     settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
3115     settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
3116     settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
3117     bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3118     settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3119     settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3120     settings.setRequiresUserGestureToLoadVideo(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureToLoadVideoKey()));
3121     settings.setMainContentUserGestureOverrideEnabled(store.getBoolValueForKey(WebPreferencesKey::mainContentUserGestureOverrideEnabledKey()));
3122     settings.setMediaUserGestureInheritsFromDocument(store.getBoolValueForKey(WebPreferencesKey::mediaUserGestureInheritsFromDocumentKey()));
3123     settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey()));
3124     settings.setAllowsInlineMediaPlaybackAfterFullscreen(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackAfterFullscreenKey()));
3125     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute(store.getBoolValueForKey(WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey()));
3126     settings.setInvisibleAutoplayNotPermitted(store.getBoolValueForKey(WebPreferencesKey::invisibleAutoplayNotPermittedKey()));
3127     settings.setMediaDataLoadsAutomatically(store.getBoolValueForKey(WebPreferencesKey::mediaDataLoadsAutomaticallyKey()));
3128 #if ENABLE(ATTACHMENT_ELEMENT)
3129     settings.setAttachmentElementEnabled(store.getBoolValueForKey(WebPreferencesKey::attachmentElementEnabledKey()));
3130 #endif
3131     settings.setAllowsPictureInPictureMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey()));
3132     settings.setMediaControlsScaleWithPageZoom(store.getBoolValueForKey(WebPreferencesKey::mediaControlsScaleWithPageZoomKey()));
3133     settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
3134     settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
3135     settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
3136 #if ENABLE(SMOOTH_SCROLLING)
3137     settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
3138 #endif
3139     settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
3140     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3141     settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
3142
3143     settings.setHttpEquivEnabled(store.getBoolValueForKey(WebPreferencesKey::httpEquivEnabledKey()));
3144
3145     settings.setSelectionPaintingWithoutSelectionGapsEnabled(store.getBoolValueForKey(WebPreferencesKey::selectionPaintingWithoutSelectionGapsEnabledKey()));
3146
3147     DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3148
3149 #if ENABLE(FULLSCREEN_API)
3150     settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
3151 #endif
3152
3153 #if USE(AVFOUNDATION)
3154     settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
3155     settings.setAVFoundationNSURLSessionEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationNSURLSessionEnabledKey()));
3156 #endif
3157
3158 #if USE(GSTREAMER)
3159     settings.setGStreamerEnabled(store.getBoolValueForKey(WebPreferencesKey::isGStreamerEnabledKey()));
3160 #endif
3161
3162 #if PLATFORM(COCOA)
3163     settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
3164 #endif
3165
3166 #if PLATFORM(IOS) && HAVE(AVKIT)
3167     settings.setAVKitEnabled(true);
3168 #endif
3169
3170 #if ENABLE(WEB_AUDIO)
3171     settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
3172 #endif
3173
3174 #if ENABLE(MEDIA_STREAM)
3175     RuntimeEnabledFeatures::sharedFeatures().setMediaDevicesEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaDevicesEnabledKey()));
3176     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
3177 #endif
3178
3179 #if ENABLE(WEB_RTC)
3180     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled(store.getBoolValueForKey(WebPreferencesKey::peerConnectionEnabledKey()));
3181     RuntimeEnabledFeatures::sharedFeatures().setWebRTCLegacyAPIEnabled(!store.getBoolValueForKey(WebPreferencesKey::webRTCLegacyAPIDisabledKey()));
3182 #endif
3183
3184 #if ENABLE(SERVICE_CONTROLS)
3185     settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
3186 #endif
3187
3188 #if ENABLE(SERVICE_WORKER)
3189     RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey()));
3190 #endif
3191
3192 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3193     settings.setAllowsAirPlayForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsAirPlayForMediaPlaybackKey()));
3194 #endif
3195
3196 #if ENABLE(RESOURCE_USAGE)
3197     settings.setResourceUsageOverlayVisible(store.getBoolValueForKey(WebPreferencesKey::resourceUsageOverlayVisibleKey()));
3198 #endif
3199
3200     settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
3201     settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
3202     settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
3203     settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
3204     settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
3205
3206 #if ENABLE(VIDEO_TRACK)
3207     settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
3208     settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
3209     settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
3210 #endif
3211
3212 #if ENABLE(NOTIFICATIONS)
3213     settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
3214 #endif
3215
3216     settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
3217     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3218     settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
3219
3220     settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
3221
3222     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3223
3224     settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
3225     settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
3226     settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
3227     settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
3228     settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
3229
3230 #if ENABLE(TEXT_AUTOSIZING)
3231     settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
3232     settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
3233 #endif
3234
3235     settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
3236     settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
3237
3238     settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
3239     settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
3240     settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
3241
3242     settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
3243     settings.setHiddenPageDOMTimerThrottlingAutoIncreases(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingAutoIncreasesKey()));
3244
3245     settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
3246     settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
3247     settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
3248     settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
3249     
3250     settings.setNewBlockInsideInlineModelEnabled(store.getBoolValueForKey(WebPreferencesKey::newBlockInsideInlineModelEnabledKey()));
3251     settings.setDeferredCSSParserEnabled(store.getBoolValueForKey(WebPreferencesKey::deferredCSSParserEnabledKey()));
3252
3253     settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
3254
3255     settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
3256
3257 #if ENABLE(MEDIA_SOURCE)
3258     settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
3259 #endif
3260
3261 #if ENABLE(MEDIA_STREAM)
3262     settings.setMockCaptureDevicesEnabled(store.getBoolValueForKey(WebPreferencesKey::mockCaptureDevicesEnabledKey()));
3263     settings.setMediaCaptureRequiresSecureConnection(store.getBoolValueForKey(WebPreferencesKey::mediaCaptureRequiresSecureConnectionKey()));
3264 #endif
3265
3266     settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
3267
3268     settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
3269     settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
3270     settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
3271     settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
3272
3273     settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
3274     settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
3275     
3276     settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3277     settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
3278
3279     settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
3280
3281     auto userInterfaceDirectionPolicyCandidate = static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey()));
3282     if (userInterfaceDirectionPolicyCandidate == WebCore::UserInterfaceDirectionPolicy::Content || userInterfaceDirectionPolicyCandidate == WebCore::UserInterfaceDirectionPolicy::System)
3283         settings.setUserInterfaceDirectionPolicy(userInterfaceDirectionPolicyCandidate);
3284     TextDirection systemLayoutDirectionCandidate = static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey()));
3285     if (systemLayoutDirectionCandidate == WebCore::LTR || systemLayoutDirectionCandidate == WebCore::RTL)
3286         settings.setSystemLayoutDirection(systemLayoutDirectionCandidate);
3287
3288 #if ENABLE(APPLE_PAY)
3289     settings.setApplePayEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3290     settings.setApplePayCapabilityDisclosureAllowed(store.getBoolValueForKey(WebPreferencesKey::applePayCapabilityDisclosureAllowedKey()));
3291 #endif
3292
3293 #if PLATFORM(IOS)
3294     settings.setUseImageDocumentForSubframePDF(true);
3295 #endif
3296
3297 #if ENABLE(DATA_DETECTION)
3298     settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3299 #endif
3300 #if ENABLE(GAMEPAD)
3301     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
3302 #endif
3303
3304 #if ENABLE(SERVICE_CONTROLS)
3305     settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
3306 #endif
3307
3308     RuntimeEnabledFeatures::sharedFeatures().setCacheAPIEnabled(store.getBoolValueForKey(WebPreferencesKey::cacheAPIEnabledKey()));
3309     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled(store.getBoolValueForKey(WebPreferencesKey::fetchAPIEnabledKey()));
3310
3311 #if ENABLE(DOWNLOAD_ATTRIBUTE)
3312     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled(store.getBoolValueForKey(WebPreferencesKey::downloadAttributeEnabledKey()));
3313 #endif
3314
3315     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled(store.getBoolValueForKey(WebPreferencesKey::shadowDOMEnabledKey()));
3316
3317     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3318
3319     // Experimental Features.
3320
3321     RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
3322     
3323     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled(store.getBoolValueForKey(WebPreferencesKey::customElementsEnabledKey()));
3324
3325     RuntimeEnabledFeatures::sharedFeatures().setDataTransferItemsEnabled(store.getBoolValueForKey(WebPreferencesKey::dataTransferItemsEnabledKey()));
3326
3327 #if ENABLE(WEBGL2)
3328     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled(store.getBoolValueForKey(WebPreferencesKey::webGL2EnabledKey()));
3329 #endif
3330
3331 #if ENABLE(WEBGPU)
3332     RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled(store.getBoolValueForKey(WebPreferencesKey::webGPUEnabledKey()));
3333 #endif
3334
3335     settings.setSpringTimingFunctionEnabled(store.getBoolValueForKey(WebPreferencesKey::springTimingFunctionEnabledKey()));
3336
3337     settings.setConstantPropertiesEnabled(store.getBoolValueForKey(WebPreferencesKey::constantPropertiesEnabledKey()));
3338
3339     settings.setViewportFitEnabled(store.getBoolValueForKey(WebPreferencesKey::viewportFitEnabledKey()));
3340
3341     settings.setVisualViewportEnabled(store.getBoolValueForKey(WebPreferencesKey::visualViewportEnabledKey()));
3342
3343     settings.setInputEventsEnabled(store.getBoolValueForKey(WebPreferencesKey::inputEventsEnabledKey()));
3344     RuntimeEnabledFeatures::sharedFeatures().setInputEventsEnabled(store.getBoolValueForKey(WebPreferencesKey::inputEventsEnabledKey()));
3345
3346     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::modernMediaControlsEnabledKey()));
3347
3348 #if ENABLE(ENCRYPTED_MEDIA)
3349     RuntimeEnabledFeatures::sharedFeatures().setEncryptedMediaAPIEnabled(store.getBoolValueForKey(WebPreferencesKey::encryptedMediaAPIEnabledKey()));
3350 #endif
3351
3352 #if ENABLE(INTERSECTION_OBSERVER)
3353     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(store.getBoolValueForKey(WebPreferencesKey::intersectionObserverEnabledKey()));
3354 #endif
3355
3356     RuntimeEnabledFeatures::sharedFeatures().setDisplayContentsEnabled(store.getBoolValueForKey(WebPreferencesKey::displayContentsEnabledKey()));
3357     RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(store.getBoolValueForKey(WebPreferencesKey::userTimingEnabledKey()));
3358     RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(store.getBoolValueForKey(WebPreferencesKey::resourceTimingEnabledKey()));
3359     RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(store.getBoolValueForKey(WebPreferencesKey::linkPreloadEnabledKey()));
3360     RuntimeEnabledFeatures::sharedFeatures().setMediaPreloadingEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaPreloadingEnabledKey()));
3361     RuntimeEnabledFeatures::sharedFeatures().setCredentialManagementEnabled(store.getBoolValueForKey(WebPreferencesKey::credentialManagementEnabledKey()));
3362     RuntimeEnabledFeatures::sharedFeatures().setIsSecureContextAttributeEnabled(store.getBoolValueForKey(WebPreferencesKey::isSecureContextAttributeEnabledKey()));
3363
3364     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3365     if (m_processSuppressionEnabled != processSuppressionEnabled) {
3366         m_processSuppressionEnabled = processSuppressionEnabled;
3367         updateThrottleState();
3368     }
3369
3370     settings.setSubresourceIntegrityEnabled(store.getBoolValueForKey(WebPreferencesKey::subresourceIntegrityEnabledKey()));
3371
3372 #if ENABLE(BEACON_API)
3373     settings.setBeaconAPIEnabled(store.getBoolValueForKey(WebPreferencesKey::beaconAPIEnabledKey()));
3374 #endif
3375
3376     platformPreferencesDidChange(store);
3377
3378     if (m_drawingArea)
3379         m_drawingArea->updatePreferences(store);
3380
3381 #if PLATFORM(IOS)
3382     m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3383     m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3384     setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3385 #endif
3386     settings.setLargeImageAsyncDecodingEnabled(store.getBoolValueForKey(WebPreferencesKey::largeImageAsyncDecodingEnabledKey()));
3387     settings.setAnimatedImageAsyncDecodingEnabled(store.getBoolValueForKey(WebPreferencesKey::animatedImageAsyncDecodingEnabledKey()));
3388     settings.setShouldSuppressKeyboardInputDuringProvisionalNavigation(store.getBoolValueForKey(WebPreferencesKey::shouldSuppressKeyboardInputDuringProvisionalNavigationKey()));
3389     settings.setMediaContentTypesRequiringHardwareSupport(store.getStringValueForKey(WebPreferencesKey::mediaContentTypesRequiringHardwareSupportKey()));
3390     settings.setAllowMediaContentTypesRequiringHardwareSupportAsFallback(store.getBoolValueForKey(WebPreferencesKey::allowMediaContentTypesRequiringHardwareSupportAsFallbackKey()));
3391
3392 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3393     RuntimeEnabledFeatures::sharedFeatures().setLegacyEncryptedMediaAPIEnabled(store.getBoolValueForKey(WebPreferencesKey::legacyEncryptedMediaAPIEnabledKey()));
3394 #endif
3395
3396     RuntimeEnabledFeatures::sharedFeatures().setInspectorAdditionsEnabled(store.getBoolValueForKey(WebPreferencesKey::inspectorAdditionsEnabledKey()));
3397 }
3398
3399 #if ENABLE(DATA_DETECTION)
3400 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3401 {
3402     DataDetectionResult dataDetectionResult;
3403     dataDetectionResult.results = detectionResults;
3404     send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3405 }
3406 #endif
3407
3408 #if PLATFORM(COCOA)
3409 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3410 {
3411     FrameView* frameView = corePage()->mainFrame().view();
3412     if (!frameView)
3413         return;
3414
3415     layerTransaction.setContentsSize(frameView->contentsSize());
3416     layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3417     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3418     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3419     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3420
3421     layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3422     layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3423     layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3424
3425 #if PLATFORM(IOS)
3426     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3427     layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3428     layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3429     layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3430     layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3431     layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3432     layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3433     layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3434     layerTransaction.setIsInStableState(m_isInStableState);
3435     layerTransaction.setAllowsUserScaling(allowsUserScaling());
3436 #endif
3437
3438 #if PLATFORM(MAC)
3439     layerTransaction.setScrollPosition(frameView->scrollPosition());
3440 #endif
3441 }
3442
3443 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3444 {
3445 #if PLATFORM(IOS)
3446     if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3447         Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3448         m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3449
3450         m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3451     }
3452 #else
3453     UNUSED_PARAM(timestamp);
3454 #endif
3455 }
3456 #endif
3457
3458 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3459 {
3460     if (m_isClosed)
3461         return nullptr;
3462     if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3463         m_inspector = WebInspector::create(this);
3464     return m_inspector.get();
3465 }
3466
3467 WebInspectorUI* WebPage::inspectorUI()
3468 {
3469     if (m_isClosed)
3470         return nullptr;
3471     if (!m_inspectorUI)
3472         m_inspectorUI = WebInspectorUI::create(*this);
3473     return m_inspectorUI.get();
3474 }
3475
3476 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3477 {
3478     if (m_isClosed)
3479         return nullptr;
3480     if (!m_remoteInspectorUI)
3481         m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3482     return m_remoteInspectorUI.get();
3483 }
3484
3485 #if (PLATFORM(IOS) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3486 PlaybackSessionManager& WebPage::playbackSessionManager()
3487 {
3488     if (!m_playbackSessionManager)
3489         m_playbackSessionManager = PlaybackSessionManager::create(*this);
3490     return *m_playbackSessionManager;
3491 }
3492
3493 VideoFullscreenManager& WebPage::videoFullscreenManager()
3494 {
3495     if (!m_videoFullscreenManager)
3496         m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3497     return *m_videoFullscreenManager;
3498 }
3499 #endif
3500
3501 #if PLATFORM(IOS)
3502 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3503 {
3504     m_page->setAllowsMediaDocumentInlinePlayback(allows);
3505 }
3506 #endif
3507
3508 #if ENABLE(FULLSCREEN_API)
3509 WebFullScreenManager* WebPage::fullScreenManager()
3510 {
3511     if (!m_fullScreenManager)
3512         m_fullScreenManager = WebFullScreenManager::create(this);
3513     return m_fullScreenManager.get();
3514 }
3515 #endif
3516
3517 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3518 {
3519     if (m_notificationPermissionRequestManager)
3520         return m_notificationPermissionRequestManager.get();
3521
3522     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3523     return m_notificationPermissionRequestManager.get();
3524 }
3525
3526 #if !PLATFORM(GTK) && !PLATFORM(COCOA) && !PLATFORM(WPE)
3527 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
3528 {
3529     Node* node = evt->target()->toNode();
3530     ASSERT(node);
3531     Frame* frame = node->document().frame();
3532     ASSERT(frame);
3533
3534     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
3535     if (!keyEvent)
3536         return false;
3537
3538     Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
3539
3540     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
3541         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
3542         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
3543         // (e.g. Tab that inserts a Tab character, or Enter).
3544         return !command.isTextInsertion() && command.execute(evt);
3545     }
3546
3547     if (command.execute(evt))
3548         return true;
3549
3550     // Don't allow text insertion for nodes that cannot edit.
3551     if (!frame->editor().canEdit())
3552         return false;
3553
3554     // Don't insert null or control characters as they can result in unexpected behaviour
3555     if (evt->charCode() < ' ')
3556         return false;
3557
3558     return frame->editor().insertText(evt->keyEvent()->text(), evt);
3559 }
3560 #endif
3561
3562 #if ENABLE(DRAG_SUPPORT)
3563
3564 #if PLATFORM(GTK)
3565 void WebPage::performDragControllerAction(uint64_t action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3566 {
3567     if (!m_page) {
3568         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3569         return;
3570     }
3571
3572     DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3573     switch (action) {
3574     case DragControllerActionEntered: {
3575         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3576         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }));
3577         break;
3578     }
3579     case DragControllerActionUpdated: {
3580         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3581         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }));
3582         break;
3583     }
3584     case DragControllerActionExited:
3585         m_page->dragController().dragExited(dragData);
3586         break;
3587
3588     case DragControllerActionPerformDragOperation: {
3589         m_page->dragController().performDragOperation(dragData);
3590  &nbs