Add API::InjectedBundle::ResourceLoadClient
[WebKit-https.git] / Source / WebKit2 / 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 "RemoteLayerTreeTransaction.h"
222 #include "WKStringCF.h"
223 #include "WebPlaybackSessionManager.h"
224 #include "WebVideoFullscreenManager.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/CoreTextSPI.h>
238 #include <WebCore/Icon.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 double pageScrollHysteresisSeconds = 0.3;
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(); }, pageScrollHysteresisSeconds)
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->rtcController().disableICECandidateFiltering();
580 }
581
582 void WebPage::enableICECandidateFiltering()
583 {
584     m_page->rtcController().disableICECandidateFiltering();
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<uint64_t>());
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
676 void WebPage::dummy(bool&)
677 {
678 }
679
680 IPC::Connection* WebPage::messageSenderConnection()
681 {
682     return WebProcess::singleton().parentProcessConnection();
683 }
684
685 uint64_t WebPage::messageSenderDestinationID()
686 {
687     return pageID();
688 }
689
690 #if ENABLE(CONTEXT_MENUS)
691 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>&& contextMenuClient)
692 {
693     if (!contextMenuClient) {
694         m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
695         return;
696     }
697
698     m_contextMenuClient = WTFMove(contextMenuClient);
699 }
700 #endif
701
702 void WebPage::setInjectedBundleEditorClient(std::unique_ptr<API::InjectedBundle::EditorClient>&& editorClient)
703 {
704     if (!editorClient) {
705         m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
706         return;
707     }
708
709     m_editorClient = WTFMove(editorClient);
710 }
711
712 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>&& formClient)
713 {
714     if (!formClient) {
715         m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
716         return;
717     }
718
719     m_formClient = WTFMove(formClient);
720 }
721
722 void WebPage::setInjectedBundlePageLoaderClient(std::unique_ptr<API::InjectedBundle::PageLoaderClient>&& loaderClient)
723 {
724     if (!loaderClient) {
725         m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
726         return;
727     }
728
729     m_loaderClient = WTFMove(loaderClient);
730
731     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
732     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
733     // for backwards compatibility.
734     if (auto milestones = m_loaderClient->layoutMilestones())
735         listenForLayoutMilestones(milestones);
736 }
737
738 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
739 {
740     m_policyClient.initialize(client);
741 }
742
743 void WebPage::setInjectedBundleResourceLoadClient(std::unique_ptr<API::InjectedBundle::ResourceLoadClient>&& client)
744 {
745     if (!m_resourceLoadClient)
746         m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
747     else
748         m_resourceLoadClient = WTFMove(client);
749 }
750
751 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>&& uiClient)
752 {
753     if (!uiClient) {
754         m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
755         return;
756     }
757
758     m_uiClient = WTFMove(uiClient);
759 }
760
761 #if ENABLE(FULLSCREEN_API)
762 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
763 {
764     m_fullScreenClient.initialize(client);
765 }
766 #endif
767
768 #if ENABLE(NETSCAPE_PLUGIN_API)
769
770 RefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
771 {
772     String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
773     String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
774
775 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
776     HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
777     unsigned pluginArea = 0;
778     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
779 #else
780     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
781 #endif
782
783     bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
784
785     uint64_t pluginProcessToken;
786     uint32_t pluginLoadPolicy;
787     String unavailabilityDescription;
788     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)))
789         return nullptr;
790
791     PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
792     bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
793
794     if (isBlockedPlugin || !pluginProcessToken) {
795 #if ENABLE(PDFKIT_PLUGIN)
796         String path = parameters.url.path();
797         if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
798             auto pdfPlugin = PDFPlugin::create(frame);
799             return WTFMove(pdfPlugin);
800         }
801 #else
802         UNUSED_PARAM(frame);
803 #endif
804     }
805
806     if (isBlockedPlugin) {
807         bool replacementObscured = false;
808         auto* renderer = pluginElement->renderer();
809         if (is<RenderEmbeddedObject>(renderer)) {
810             auto& renderObject = downcast<RenderEmbeddedObject>(*renderer);
811             renderObject.setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
812             replacementObscured = renderObject.isReplacementObscured();
813             renderObject.setUnavailablePluginIndicatorIsHidden(replacementObscured);
814         }
815
816         send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
817         return nullptr;
818     }
819
820     if (!pluginProcessToken)
821         return nullptr;
822
823     bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
824     return PluginProxy::create(pluginProcessToken, isRestartedProcess);
825 }
826
827 #endif // ENABLE(NETSCAPE_PLUGIN_API)
828
829 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
830 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
831 {
832     return WebGLAllowCreation;
833 }
834
835 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
836 {
837     return WebGLAllowCreation;
838 }
839 #endif
840
841 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
842 {
843     Frame& frame = m_page->focusController().focusedOrMainFrame();
844
845     EditorState result;
846
847     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
848         if (!pluginView->getSelectionString().isNull()) {
849             result.selectionIsNone = false;
850             result.selectionIsRange = true;
851             result.isInPlugin = true;
852             return result;
853         }
854     }
855
856     const VisibleSelection& selection = frame.selection().selection();
857
858     result.selectionIsNone = selection.isNone();
859     result.selectionIsRange = selection.isRange();
860     result.isContentEditable = selection.isContentEditable();
861     result.isContentRichlyEditable = selection.isContentRichlyEditable();
862     result.isInPasswordField = selection.isInPasswordField();
863     result.hasComposition = frame.editor().hasComposition();
864     result.shouldIgnoreSelectionChanges = frame.editor().ignoreSelectionChanges();
865
866 #if PLATFORM(COCOA)
867     if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && result.isContentEditable) {
868         auto& postLayoutData = result.postLayoutData();
869         if (!selection.isNone()) {
870             Node* nodeToRemove;
871             if (auto* style = Editor::styleForSelectionStart(&frame, nodeToRemove)) {
872                 if (isFontWeightBold(style->fontCascade().weight()))
873                     postLayoutData.typingAttributes |= AttributeBold;
874                 if (isItalic(style->fontCascade().italic()))
875                     postLayoutData.typingAttributes |= AttributeItalics;
876
877                 RefPtr<EditingStyle> typingStyle = frame.selection().typingStyle();
878                 if (typingStyle && typingStyle->style()) {
879                     String value = typingStyle->style()->getPropertyValue(CSSPropertyWebkitTextDecorationsInEffect);
880                 if (value.contains("underline"))
881                     postLayoutData.typingAttributes |= AttributeUnderline;
882                 } else {
883                     if (style->textDecorationsInEffect() & TextDecorationUnderline)
884                         postLayoutData.typingAttributes |= AttributeUnderline;
885                 }
886
887                 if (style->visitedDependentColor(CSSPropertyColor).isValid())
888                     postLayoutData.textColor = style->visitedDependentColor(CSSPropertyColor);
889
890                 switch (style->textAlign()) {
891                 case RIGHT:
892                 case WEBKIT_RIGHT:
893                     postLayoutData.textAlignment = RightAlignment;
894                     break;
895                 case LEFT:
896                 case WEBKIT_LEFT:
897                     postLayoutData.textAlignment = LeftAlignment;
898                     break;
899                 case CENTER:
900                 case WEBKIT_CENTER:
901                     postLayoutData.textAlignment = CenterAlignment;
902                     break;
903                 case JUSTIFY:
904                     postLayoutData.textAlignment = JustifiedAlignment;
905                     break;
906                 case TASTART:
907                     postLayoutData.textAlignment = style->isLeftToRightDirection() ? LeftAlignment : RightAlignment;
908                     break;
909                 case TAEND:
910                     postLayoutData.textAlignment = style->isLeftToRightDirection() ? RightAlignment : LeftAlignment;
911                     break;
912                 }
913                 
914                 HTMLElement* enclosingListElement = enclosingList(selection.start().deprecatedNode());
915                 if (enclosingListElement) {
916                     if (is<HTMLUListElement>(*enclosingListElement))
917                         postLayoutData.enclosingListType = UnorderedList;
918                     else if (is<HTMLOListElement>(*enclosingListElement))
919                         postLayoutData.enclosingListType = OrderedList;
920                     else
921                         ASSERT_NOT_REACHED();
922                 } else
923                     postLayoutData.enclosingListType = NoList;
924
925                 if (nodeToRemove)
926                     nodeToRemove->remove();
927             }
928         }
929     }
930 #endif
931
932     platformEditorState(frame, result, shouldIncludePostLayoutData);
933
934     m_lastEditorStateWasContentEditable = result.isContentEditable ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
935
936     return result;
937 }
938
939 void WebPage::updateEditorStateAfterLayoutIfEditabilityChanged()
940 {
941     // FIXME: We should update EditorStateIsContentEditable to track whether the state is richly
942     // editable or plainttext-only.
943     if (m_lastEditorStateWasContentEditable == EditorStateIsContentEditable::Unset)
944         return;
945
946     Frame& frame = m_page->focusController().focusedOrMainFrame();
947     EditorStateIsContentEditable editorStateIsContentEditable = frame.selection().selection().isContentEditable() ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
948     if (m_lastEditorStateWasContentEditable != editorStateIsContentEditable)
949         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
950 }
951
952 String WebPage::renderTreeExternalRepresentation() const
953 {
954     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
955 }
956
957 String WebPage::renderTreeExternalRepresentationForPrinting() const
958 {
959     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
960 }
961
962 uint64_t WebPage::renderTreeSize() const
963 {
964     if (!m_page)
965         return 0;
966     return m_page->renderTreeSize();
967 }
968
969 void WebPage::setTracksRepaints(bool trackRepaints)
970 {
971     if (FrameView* view = mainFrameView())
972         view->setTracksRepaints(trackRepaints);
973 }
974
975 bool WebPage::isTrackingRepaints() const
976 {
977     if (FrameView* view = mainFrameView())
978         return view->isTrackingRepaints();
979
980     return false;
981 }
982
983 void WebPage::resetTrackedRepaints()
984 {
985     if (FrameView* view = mainFrameView())
986         view->resetTrackedRepaints();
987 }
988
989 Ref<API::Array> WebPage::trackedRepaintRects()
990 {
991     FrameView* view = mainFrameView();
992     if (!view)
993         return API::Array::create();
994
995     Vector<RefPtr<API::Object>> repaintRects;
996     repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
997
998     for (const auto& repaintRect : view->trackedRepaintRects())
999         repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
1000
1001     return API::Array::create(WTFMove(repaintRects));
1002 }
1003
1004 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
1005 {
1006     if (!frame.document()->isPluginDocument())
1007         return 0;
1008
1009     PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
1010
1011     if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
1012         return 0;
1013
1014     PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
1015     return pluginView;
1016 }
1017
1018 PluginView* WebPage::pluginViewForFrame(Frame* frame)
1019 {
1020     if (!frame->document()->isPluginDocument())
1021         return 0;
1022
1023     PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
1024     PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
1025     return pluginView;
1026 }
1027
1028 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
1029 {
1030     Frame& frame = m_page->focusController().focusedOrMainFrame();
1031
1032     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
1033         pluginView->handleEditingCommand(commandName, argument);
1034         return;
1035     }
1036     
1037     frame.editor().command(commandName).execute(argument);
1038 }
1039
1040 void WebPage::setEditable(bool editable)
1041 {
1042     m_page->setEditable(editable);
1043     m_page->setTabKeyCyclesThroughElements(!editable);
1044     Frame& frame = m_page->focusController().focusedOrMainFrame();
1045     if (editable) {
1046         frame.editor().applyEditingStyleToBodyElement();
1047         // If the page is made editable and the selection is empty, set it to something.
1048         if (frame.selection().isNone())
1049             frame.selection().setSelectionFromNone();
1050     }
1051 }
1052
1053 bool WebPage::isEditingCommandEnabled(const String& commandName)
1054 {
1055     Frame& frame = m_page->focusController().focusedOrMainFrame();
1056
1057     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1058         return pluginView->isEditingCommandEnabled(commandName);
1059     
1060     Editor::Command command = frame.editor().command(commandName);
1061     return command.isSupported() && command.isEnabled();
1062 }
1063     
1064 void WebPage::clearMainFrameName()
1065 {
1066     if (Frame* frame = mainFrame())
1067         frame->tree().clearName();
1068 }
1069
1070 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
1071 {
1072     m_drawingArea->setRootCompositingLayer(layer);
1073 }
1074
1075 void WebPage::exitAcceleratedCompositingMode()
1076 {
1077     m_drawingArea->setRootCompositingLayer(0);
1078 }
1079
1080 void WebPage::close()
1081 {
1082     if (m_isClosed)
1083         return;
1084
1085     m_isClosed = true;
1086
1087     // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1088     if (!mainWebFrame()->url().isEmpty())
1089         reportUsedFeatures();
1090
1091     if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
1092         WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1093
1094     if (m_inspector) {
1095         m_inspector->disconnectFromPage();
1096         m_inspector = nullptr;
1097     }
1098
1099     m_page->inspectorController().disconnectAllFrontends();
1100
1101 #if ENABLE(FULLSCREEN_API)
1102     m_fullScreenManager = nullptr;
1103 #endif
1104
1105     if (m_activePopupMenu) {
1106         m_activePopupMenu->disconnectFromPage();
1107         m_activePopupMenu = nullptr;
1108     }
1109
1110     if (m_activeOpenPanelResultListener) {
1111         m_activeOpenPanelResultListener->disconnectFromPage();
1112         m_activeOpenPanelResultListener = nullptr;
1113     }
1114
1115 #if ENABLE(INPUT_TYPE_COLOR)
1116     if (m_activeColorChooser) {
1117         m_activeColorChooser->disconnectFromPage();
1118         m_activeColorChooser = nullptr;
1119     }
1120 #endif
1121
1122 #if PLATFORM(GTK)
1123     if (m_printOperation) {
1124         m_printOperation->disconnectFromPage();
1125         m_printOperation = nullptr;
1126     }
1127 #endif
1128
1129 #if ENABLE(VIDEO) && USE(GSTREAMER)
1130     if (m_installMediaPluginsCallback) {
1131         m_installMediaPluginsCallback->invalidate();
1132         m_installMediaPluginsCallback = nullptr;
1133     }
1134 #endif
1135
1136     m_sandboxExtensionTracker.invalidate();
1137
1138 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1139     m_determinePrimarySnapshottedPlugInTimer.stop();
1140 #endif
1141
1142 #if ENABLE(CONTEXT_MENUS)
1143     m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1144 #endif
1145     m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
1146     m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1147     m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
1148     m_policyClient.initialize(0);
1149     m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
1150     m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1151 #if ENABLE(FULLSCREEN_API)
1152     m_fullScreenClient.initialize(0);
1153 #endif
1154
1155     m_printContext = nullptr;
1156     m_mainFrame->coreFrame()->loader().detachFromParent();
1157     m_drawingArea = nullptr;
1158
1159     DeferredPageDestructor::createDeferredPageDestructor(WTFMove(m_page), this);
1160
1161     bool isRunningModal = m_isRunningModal;
1162     m_isRunningModal = false;
1163
1164     // The WebPage can be destroyed by this call.
1165     WebProcess::singleton().removeWebPage(m_pageID);
1166
1167     WebProcess::singleton().updateActivePages();
1168
1169     if (isRunningModal)
1170         RunLoop::main().stop();
1171 }
1172
1173 void WebPage::tryClose()
1174 {
1175     SendStopResponsivenessTimer stopper;
1176
1177     if (!corePage()->userInputBridge().tryClosePage()) {
1178         WebProcess::singleton().parentProcessConnection()->send(Messages::WebProcessProxy::StopResponsivenessTimer(), 0);
1179         return;
1180     }
1181
1182     send(Messages::WebPageProxy::ClosePage(true));
1183 }
1184
1185 void WebPage::sendClose()
1186 {
1187     send(Messages::WebPageProxy::ClosePage(false));
1188 }
1189
1190 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
1191 {
1192     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1193     if (!frame)
1194         return;
1195
1196     frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url)), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1197 }
1198
1199 #if !PLATFORM(COCOA)
1200 void WebPage::platformDidReceiveLoadParameters(const LoadParameters& loadParameters)
1201 {
1202 }
1203 #endif
1204
1205 void WebPage::loadRequest(const LoadParameters& loadParameters)
1206 {
1207     SendStopResponsivenessTimer stopper;
1208
1209     m_pendingNavigationID = loadParameters.navigationID;
1210
1211     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), loadParameters.sandboxExtensionHandle);
1212
1213     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1214     // to all the client to set up any needed state.
1215     m_loaderClient->willLoadURLRequest(*this, loadParameters.request, WebProcess::singleton().transformHandlesToObjects(loadParameters.userData.object()).get());
1216
1217     platformDidReceiveLoadParameters(loadParameters);
1218
1219     // Initate the load in WebCore.
1220     FrameLoadRequest frameLoadRequest(m_mainFrame->coreFrame(), loadParameters.request, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1221     ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(loadParameters.shouldOpenExternalURLsPolicy);
1222     frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1223
1224     corePage()->userInputBridge().loadRequest(frameLoadRequest);
1225
1226     ASSERT(!m_pendingNavigationID);
1227 }
1228
1229 void WebPage::loadDataImpl(uint64_t navigationID, Ref<SharedBuffer>&& sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1230 {
1231     SendStopResponsivenessTimer stopper;
1232
1233     m_pendingNavigationID = navigationID;
1234
1235     ResourceRequest request(baseURL);
1236     ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1237     SubstituteData substituteData(WTFMove(sharedBuffer), unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1238
1239     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1240     // to all the client to set up any needed state.
1241     m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1242
1243     // Initate the load in WebCore.
1244     m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData));
1245 }
1246
1247 void WebPage::loadStringImpl(uint64_t navigationID, const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1248 {
1249     if (!htmlString.isNull() && htmlString.is8Bit()) {
1250         auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
1251         loadDataImpl(navigationID, WTFMove(sharedBuffer), MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, userData);
1252     } else {
1253         auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
1254         loadDataImpl(navigationID, WTFMove(sharedBuffer), MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, userData);
1255     }
1256 }
1257
1258 void WebPage::loadData(const LoadParameters& loadParameters)
1259 {
1260     platformDidReceiveLoadParameters(loadParameters);
1261
1262     auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1263     URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1264     loadDataImpl(loadParameters.navigationID, WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, URL(), loadParameters.userData);
1265 }
1266
1267 void WebPage::loadString(const LoadParameters& loadParameters)
1268 {
1269     platformDidReceiveLoadParameters(loadParameters);
1270
1271     URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1272     loadStringImpl(loadParameters.navigationID, loadParameters.string, loadParameters.MIMEType, baseURL, URL(), loadParameters.userData);
1273 }
1274
1275 void WebPage::loadAlternateHTMLString(const LoadParameters& loadParameters)
1276 {
1277     platformDidReceiveLoadParameters(loadParameters);
1278
1279     URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1280     URL unreachableURL = loadParameters.unreachableURLString.isEmpty() ? URL() : URL(URL(), loadParameters.unreachableURLString);
1281     URL provisionalLoadErrorURL = loadParameters.provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), loadParameters.provisionalLoadErrorURLString);
1282     m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1283     loadStringImpl(0, loadParameters.string, ASCIILiteral("text/html"), baseURL, unreachableURL, loadParameters.userData);
1284     m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1285 }
1286
1287 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1288 {
1289     Frame* mainFrame = m_mainFrame->coreFrame();
1290     Document* mainFrameDocument = mainFrame->document();
1291     if (!mainFrameDocument)
1292         return;
1293
1294     const int singleClick = 1;
1295     RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, true, true, currentTime(), nullptr, singleClick, screenPoint.x(), screenPoint.y(), documentPoint.x(), documentPoint.y(),
1296 #if ENABLE(POINTER_LOCK)
1297         0, 0,
1298 #endif
1299         false, false, false, false, 0, nullptr, 0, WebCore::NoTap, nullptr);
1300
1301     mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1302 }
1303
1304 void WebPage::stopLoadingFrame(uint64_t frameID)
1305 {
1306     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1307     if (!frame)
1308         return;
1309
1310     corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1311 }
1312
1313 void WebPage::stopLoading()
1314 {
1315     SendStopResponsivenessTimer stopper;
1316
1317     corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1318 }
1319
1320 bool WebPage::defersLoading() const
1321 {
1322     return m_page->defersLoading();
1323 }
1324
1325 void WebPage::setDefersLoading(bool defersLoading)
1326 {
1327     m_page->setDefersLoading(defersLoading);
1328 }
1329
1330 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, const SandboxExtension::Handle& sandboxExtensionHandle)
1331 {
1332     SendStopResponsivenessTimer stopper;
1333
1334     ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1335     m_pendingNavigationID = navigationID;
1336
1337     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1338     corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1339 }
1340
1341 void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID)
1342 {
1343     SendStopResponsivenessTimer stopper;
1344
1345     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1346     ASSERT(item);
1347     if (!item)
1348         return;
1349
1350     ASSERT(!m_pendingNavigationID);
1351     m_pendingNavigationID = navigationID;
1352
1353     m_page->goToItem(*item, FrameLoadType::Forward);
1354 }
1355
1356 void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID)
1357 {
1358     SendStopResponsivenessTimer stopper;
1359
1360     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1361     ASSERT(item);
1362     if (!item)
1363         return;
1364
1365     ASSERT(!m_pendingNavigationID);
1366     m_pendingNavigationID = navigationID;
1367
1368     m_page->goToItem(*item, FrameLoadType::Back);
1369 }
1370
1371 void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID)
1372 {
1373     SendStopResponsivenessTimer stopper;
1374
1375     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1376     ASSERT(item);
1377     if (!item)
1378         return;
1379
1380     ASSERT(!m_pendingNavigationID);
1381     m_pendingNavigationID = navigationID;
1382
1383     m_page->goToItem(*item, FrameLoadType::IndexedBackForward);
1384 }
1385
1386 void WebPage::tryRestoreScrollPosition()
1387 {
1388     m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1389 }
1390
1391 void WebPage::layoutIfNeeded()
1392 {
1393     if (m_mainFrame->coreFrame()->view())
1394         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1395 }
1396
1397 WebPage* WebPage::fromCorePage(Page* page)
1398 {
1399     return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1400 }
1401
1402 void WebPage::setSize(const WebCore::IntSize& viewSize)
1403 {
1404     if (m_viewSize == viewSize)
1405         return;
1406
1407     m_viewSize = viewSize;
1408     FrameView* view = m_page->mainFrame().view();
1409     view->resize(viewSize);
1410     m_drawingArea->setNeedsDisplay();
1411
1412 #if USE(COORDINATED_GRAPHICS)
1413     if (view->useFixedLayout())
1414         sendViewportAttributesChanged(m_page->viewportArguments());
1415 #endif
1416 }
1417
1418 #if USE(COORDINATED_GRAPHICS)
1419 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1420 {
1421     FrameView* view = m_page->mainFrame().view();
1422     ASSERT(view && view->useFixedLayout());
1423
1424     // Viewport properties have no impact on zero sized fixed viewports.
1425     if (m_viewSize.isEmpty())
1426         return;
1427
1428     // Recalculate the recommended layout size, when the available size (device pixel) changes.
1429     Settings& settings = m_page->settings();
1430
1431     int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1432
1433     // If unset  we use the viewport dimensions. This fits with the behavior of desktop browsers.
1434     int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1435     int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1436
1437     ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1438
1439     // If no layout was done yet set contentFixedOrigin to (0,0).
1440     IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1441
1442     // Put the width and height to the viewport width and height. In css units however.
1443     // Use FloatSize to avoid truncated values during scale.
1444     FloatSize contentFixedSize = m_viewSize;
1445
1446 #if ENABLE(CSS_DEVICE_ADAPTATION)
1447     // CSS viewport descriptors might be applied to already affected viewport size
1448     // if the page enables/disables stylesheets, so need to keep initial viewport size.
1449     view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1450 #endif
1451
1452     contentFixedSize.scale(1 / attr.initialScale);
1453     view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1454
1455     attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1456
1457     // This also takes care of the relayout.
1458     setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1459
1460 #if USE(COORDINATED_GRAPHICS_THREADED)
1461     m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1462 #else
1463     send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1464 #endif
1465 }
1466 #endif
1467
1468 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1469 {
1470     FrameView* frameView = m_page->mainFrame().view();
1471
1472     ScrollPosition scrollPosition = frameView->scrollPosition();
1473     ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1474
1475     // If the current scroll position in a direction is the max scroll position 
1476     // we don't want to scroll at all.
1477     IntSize newScrollOffset;
1478     if (scrollPosition.x() < maximumScrollPosition.x())
1479         newScrollOffset.setWidth(scrollOffset.width());
1480     if (scrollPosition.y() < maximumScrollPosition.y())
1481         newScrollOffset.setHeight(scrollOffset.height());
1482
1483     if (newScrollOffset.isZero())
1484         return;
1485
1486     frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1487 }
1488
1489 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1490 {
1491     GraphicsContextStateSaver stateSaver(graphicsContext);
1492     graphicsContext.clip(rect);
1493
1494     m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1495 }
1496
1497 double WebPage::textZoomFactor() const
1498 {
1499     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1500     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1501         if (pluginView->handlesPageScaleFactor())
1502             return pluginView->pageScaleFactor();
1503         return pageScaleFactor();
1504     }
1505
1506     Frame* frame = m_mainFrame->coreFrame();
1507     if (!frame)
1508         return 1;
1509     return frame->textZoomFactor();
1510 }
1511
1512 void WebPage::setTextZoomFactor(double zoomFactor)
1513 {
1514     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1515     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1516         if (pluginView->handlesPageScaleFactor())
1517             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1518         else
1519             scalePage(zoomFactor, IntPoint());
1520         return;
1521     }
1522
1523     Frame* frame = m_mainFrame->coreFrame();
1524     if (!frame)
1525         return;
1526     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1527 }
1528
1529 double WebPage::pageZoomFactor() const
1530 {
1531     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1532     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1533         if (pluginView->handlesPageScaleFactor())
1534             return pluginView->pageScaleFactor();
1535         return pageScaleFactor();
1536     }
1537
1538     Frame* frame = m_mainFrame->coreFrame();
1539     if (!frame)
1540         return 1;
1541     return frame->pageZoomFactor();
1542 }
1543
1544 void WebPage::setPageZoomFactor(double zoomFactor)
1545 {
1546     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1547     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1548         if (pluginView->handlesPageScaleFactor())
1549             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1550         else
1551             scalePage(zoomFactor, IntPoint());
1552         return;
1553     }
1554
1555     Frame* frame = m_mainFrame->coreFrame();
1556     if (!frame)
1557         return;
1558     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1559 }
1560
1561 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1562 {
1563     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1564     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1565         if (pluginView->handlesPageScaleFactor())
1566             pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1567         else
1568             scalePage(pageZoomFactor, IntPoint());
1569         return;
1570     }
1571
1572     Frame* frame = m_mainFrame->coreFrame();
1573     if (!frame)
1574         return;
1575     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1576 }
1577
1578 void WebPage::windowScreenDidChange(uint32_t displayID)
1579 {
1580     m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1581 }
1582
1583 void WebPage::scalePage(double scale, const IntPoint& origin)
1584 {
1585     double totalScale = scale * viewScaleFactor();
1586     bool willChangeScaleFactor = totalScale != totalScaleFactor();
1587
1588 #if PLATFORM(IOS)
1589     if (willChangeScaleFactor) {
1590         if (!m_inDynamicSizeUpdate)
1591             m_dynamicSizeUpdateHistory.clear();
1592         m_scaleWasSetByUIProcess = false;
1593     }
1594 #endif
1595     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1596     if (pluginView && pluginView->handlesPageScaleFactor()) {
1597         // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1598         // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1599         if (m_page->pageScaleFactor() != 1) {
1600             m_page->setPageScaleFactor(1, origin);
1601             for (auto* pluginView : m_pluginViews)
1602                 pluginView->pageScaleFactorDidChange();
1603         }
1604
1605         pluginView->setPageScaleFactor(totalScale, origin);
1606         return;
1607     }
1608
1609     m_page->setPageScaleFactor(totalScale, origin);
1610
1611     // We can't early return before setPageScaleFactor because the origin might be different.
1612     if (!willChangeScaleFactor)
1613         return;
1614
1615     for (auto* pluginView : m_pluginViews)
1616         pluginView->pageScaleFactorDidChange();
1617
1618 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1619     m_drawingArea->deviceOrPageScaleFactorChanged();
1620 #endif
1621
1622     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1623 }
1624
1625 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1626 {
1627     double totalScale = scale * viewScaleFactor();
1628     if (totalScale == totalScaleFactor())
1629         return;
1630
1631     IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1632     double scaleRatio = scale / pageScaleFactor();
1633     scrollPositionAtNewScale.scale(scaleRatio);
1634     scalePage(scale, scrollPositionAtNewScale);
1635 }
1636
1637 double WebPage::totalScaleFactor() const
1638 {
1639     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1640     if (pluginView && pluginView->handlesPageScaleFactor())
1641         return pluginView->pageScaleFactor();
1642
1643     return m_page->pageScaleFactor();
1644 }
1645
1646 double WebPage::pageScaleFactor() const
1647 {
1648     return totalScaleFactor() / viewScaleFactor();
1649 }
1650
1651 double WebPage::viewScaleFactor() const
1652 {
1653     return m_page->viewScaleFactor();
1654 }
1655
1656 void WebPage::scaleView(double scale)
1657 {
1658     if (viewScaleFactor() == scale)
1659         return;
1660
1661     float pageScale = pageScaleFactor();
1662
1663     IntPoint scrollPositionAtNewScale;
1664     if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1665         double scaleRatio = scale / viewScaleFactor();
1666         scrollPositionAtNewScale = mainFrameView->scrollPosition();
1667         scrollPositionAtNewScale.scale(scaleRatio);
1668     }
1669
1670     m_page->setViewScaleFactor(scale);
1671     scalePage(pageScale, scrollPositionAtNewScale);
1672 }
1673
1674 void WebPage::setDeviceScaleFactor(float scaleFactor)
1675 {
1676     if (scaleFactor == m_page->deviceScaleFactor())
1677         return;
1678
1679     m_page->setDeviceScaleFactor(scaleFactor);
1680
1681     // Tell all our plug-in views that the device scale factor changed.
1682 #if PLATFORM(MAC)
1683     for (auto* pluginView : m_pluginViews)
1684         pluginView->setDeviceScaleFactor(scaleFactor);
1685
1686     updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1687 #endif
1688
1689     if (findController().isShowingOverlay()) {
1690         // We must have updated layout to get the selection rects right.
1691         layoutIfNeeded();
1692         findController().deviceScaleFactorDidChange();
1693     }
1694
1695 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1696     m_drawingArea->deviceOrPageScaleFactorChanged();
1697 #endif
1698 }
1699
1700 float WebPage::deviceScaleFactor() const
1701 {
1702     return m_page->deviceScaleFactor();
1703 }
1704
1705 void WebPage::accessibilitySettingsDidChange()
1706 {
1707     m_page->accessibilitySettingsDidChange();
1708 }
1709
1710 void WebPage::setUseFixedLayout(bool fixed)
1711 {
1712     // Do not overwrite current settings if initially setting it to false.
1713     if (m_useFixedLayout == fixed)
1714         return;
1715     m_useFixedLayout = fixed;
1716
1717 #if !PLATFORM(IOS)
1718     m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1719 #endif
1720 #if USE(COORDINATED_GRAPHICS)
1721     m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1722     m_page->settings().setDelegatesPageScaling(fixed);
1723     m_page->settings().setScrollingCoordinatorEnabled(fixed);
1724 #endif
1725
1726 #if USE(COORDINATED_GRAPHICS) && ENABLE(SMOOTH_SCROLLING)
1727     // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1728     // Ensure we don't do animated scrolling in the WebProcess in that case.
1729     m_page->settings().setScrollAnimatorEnabled(!fixed);
1730 #endif
1731
1732     FrameView* view = mainFrameView();
1733     if (!view)
1734         return;
1735
1736 #if USE(COORDINATED_GRAPHICS)
1737     view->setDelegatesScrolling(fixed);
1738     view->setPaintsEntireContents(fixed);
1739 #endif
1740     view->setUseFixedLayout(fixed);
1741     if (!fixed)
1742         setFixedLayoutSize(IntSize());
1743
1744     send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1745 }
1746
1747 bool WebPage::setFixedLayoutSize(const IntSize& size)
1748 {
1749     FrameView* view = mainFrameView();
1750     if (!view || view->fixedLayoutSize() == size)
1751         return false;
1752
1753     view->setFixedLayoutSize(size);
1754
1755     send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1756     return true;
1757 }
1758
1759 IntSize WebPage::fixedLayoutSize() const
1760 {
1761     FrameView* view = mainFrameView();
1762     if (!view)
1763         return IntSize();
1764     return view->fixedLayoutSize();
1765 }
1766
1767 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
1768 {
1769 #if PLATFORM(IOS)
1770     if (m_viewportConfiguration.setViewportArguments(viewportArguments))
1771         viewportConfigurationChanged();
1772 #endif
1773
1774 #if USE(COORDINATED_GRAPHICS)
1775     FrameView* view = m_page->mainFrame().view();
1776     if (view && view->useFixedLayout())
1777         sendViewportAttributesChanged(viewportArguments);
1778 #if USE(COORDINATED_GRAPHICS_THREADED)
1779     else
1780         m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
1781 #endif
1782 #endif
1783
1784 #if !PLATFORM(IOS) && !USE(COORDINATED_GRAPHICS)
1785     UNUSED_PARAM(viewportArguments);
1786 #endif
1787 }
1788
1789 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1790 {
1791     if (!m_page)
1792         return;
1793     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1794 }
1795
1796 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1797 {
1798     m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1799 }
1800     
1801 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1802 {
1803     m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1804 }
1805     
1806 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1807 {
1808     m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1809 }
1810
1811 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1812 {
1813     if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1814         m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1815 }
1816
1817 void WebPage::setPaginationMode(uint32_t mode)
1818 {
1819     Pagination pagination = m_page->pagination();
1820     pagination.mode = static_cast<Pagination::Mode>(mode);
1821     m_page->setPagination(pagination);
1822 }
1823
1824 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1825 {
1826     Pagination pagination = m_page->pagination();
1827     pagination.behavesLikeColumns = behavesLikeColumns;
1828     m_page->setPagination(pagination);
1829 }
1830
1831 void WebPage::setPageLength(double pageLength)
1832 {
1833     Pagination pagination = m_page->pagination();
1834     pagination.pageLength = pageLength;
1835     m_page->setPagination(pagination);
1836 }
1837
1838 void WebPage::setGapBetweenPages(double gap)
1839 {
1840     Pagination pagination = m_page->pagination();
1841     pagination.gap = gap;
1842     m_page->setPagination(pagination);
1843 }
1844
1845 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
1846 {
1847     m_page->setPaginationLineGridEnabled(lineGridEnabled);
1848 }
1849
1850 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1851 {
1852     auto& webProcess = WebProcess::singleton();
1853     InjectedBundle* injectedBundle = webProcess.injectedBundle();
1854     if (!injectedBundle)
1855         return;
1856
1857     injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1858 }
1859
1860 #if !PLATFORM(IOS)
1861
1862 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
1863 {
1864     if (m_headerBanner)
1865         m_headerBanner->detachFromPage();
1866
1867     m_headerBanner = pageBanner;
1868
1869     if (m_headerBanner)
1870         m_headerBanner->addToPage(PageBanner::Header, this);
1871 }
1872
1873 PageBanner* WebPage::headerPageBanner()
1874 {
1875     return m_headerBanner.get();
1876 }
1877
1878 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
1879 {
1880     if (m_footerBanner)
1881         m_footerBanner->detachFromPage();
1882
1883     m_footerBanner = pageBanner;
1884
1885     if (m_footerBanner)
1886         m_footerBanner->addToPage(PageBanner::Footer, this);
1887 }
1888
1889 PageBanner* WebPage::footerPageBanner()
1890 {
1891     return m_footerBanner.get();
1892 }
1893
1894 void WebPage::hidePageBanners()
1895 {
1896     if (m_headerBanner)
1897         m_headerBanner->hide();
1898     if (m_footerBanner)
1899         m_footerBanner->hide();
1900 }
1901
1902 void WebPage::showPageBanners()
1903 {
1904     if (m_headerBanner)
1905         m_headerBanner->showIfHidden();
1906     if (m_footerBanner)
1907         m_footerBanner->showIfHidden();
1908 }
1909
1910 void WebPage::setHeaderBannerHeightForTesting(int height)
1911 {
1912 #if ENABLE(RUBBER_BANDING)
1913     corePage()->addHeaderWithHeight(height);
1914 #endif
1915 }
1916
1917 void WebPage::setFooterBannerHeightForTesting(int height)
1918 {
1919 #if ENABLE(RUBBER_BANDING)
1920     corePage()->addFooterWithHeight(height);
1921 #endif
1922 }
1923
1924 #endif // !PLATFORM(IOS)
1925
1926 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1927 {
1928     SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1929     snapshotOptions |= SnapshotOptionsShareable;
1930
1931     RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1932
1933     ShareableBitmap::Handle handle;
1934     if (image)
1935         image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
1936
1937     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1938 }
1939
1940 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1941 {
1942     IntRect snapshotRect = rect;
1943     IntSize bitmapSize = snapshotRect.size();
1944     if (options & SnapshotOptionsPrinting) {
1945         ASSERT(additionalScaleFactor == 1);
1946         Frame* coreFrame = m_mainFrame->coreFrame();
1947         if (!coreFrame)
1948             return nullptr;
1949         bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
1950     } else {
1951         double scaleFactor = additionalScaleFactor;
1952         if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1953             scaleFactor *= corePage()->deviceScaleFactor();
1954         bitmapSize.scale(scaleFactor);
1955     }
1956
1957     return snapshotAtSize(rect, bitmapSize, options);
1958 }
1959
1960 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
1961 {
1962     IntRect snapshotRect = rect;
1963     float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1964     float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1965     float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1966
1967     if (options & SnapshotOptionsPrinting) {
1968         PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
1969         return;
1970     }
1971
1972     Color documentBackgroundColor = frameView.documentBackgroundColor();
1973     Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
1974     graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
1975
1976     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1977         double deviceScaleFactor = frame.page()->deviceScaleFactor();
1978         graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
1979         scaleFactor /= deviceScaleFactor;
1980     }
1981
1982     graphicsContext.scale(scaleFactor);
1983     graphicsContext.translate(-snapshotRect.x(), -snapshotRect.y());
1984
1985     FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1986     if (options & SnapshotOptionsExcludeSelectionHighlighting)
1987         shouldPaintSelection = FrameView::ExcludeSelection;
1988
1989     FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1990     if (options & SnapshotOptionsInViewCoordinates)
1991         coordinateSpace = FrameView::ViewCoordinates;
1992
1993     frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
1994
1995     if (options & SnapshotOptionsPaintSelectionRectangle) {
1996         FloatRect selectionRectangle = frame.selection().selectionBounds();
1997         graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
1998         graphicsContext.strokeRect(selectionRectangle, 1);
1999     }
2000 }
2001
2002 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2003 {
2004     Frame* coreFrame = m_mainFrame->coreFrame();
2005     if (!coreFrame)
2006         return nullptr;
2007
2008     FrameView* frameView = coreFrame->view();
2009     if (!frameView)
2010         return nullptr;
2011
2012     auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
2013     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2014
2015     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2016
2017     return snapshot;
2018 }
2019
2020 #if USE(CF)
2021 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2022 {
2023     Frame* coreFrame = m_mainFrame->coreFrame();
2024     if (!coreFrame)
2025         return nullptr;
2026
2027     FrameView* frameView = coreFrame->view();
2028     if (!frameView)
2029         return nullptr;
2030
2031     auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2032
2033 #if USE(CG)
2034     auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2035     auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2036     auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2037
2038     CGPDFContextBeginPage(pdfContext.get(), nullptr);
2039
2040     GraphicsContext graphicsContext { pdfContext.get() };
2041     graphicsContext.scale({ 1, -1 });
2042     graphicsContext.translate(0, -bitmapSize.height());
2043     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2044
2045     CGPDFContextEndPage(pdfContext.get());
2046     CGPDFContextClose(pdfContext.get());
2047 #endif
2048
2049     return WTFMove(data);
2050 }
2051 #endif
2052
2053 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2054 {
2055     Frame* coreFrame = m_mainFrame->coreFrame();
2056     if (!coreFrame)
2057         return nullptr;
2058
2059     FrameView* frameView = coreFrame->view();
2060     if (!frameView)
2061         return nullptr;
2062
2063     if (!node.renderer())
2064         return nullptr;
2065
2066     LayoutRect topLevelRect;
2067     IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2068     if (snapshotRect.isEmpty())
2069         return nullptr;
2070
2071     double scaleFactor = 1;
2072     IntSize snapshotSize = snapshotRect.size();
2073     unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2074     if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2075         scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2076         snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2077     }
2078
2079     auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options));
2080
2081     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2082
2083     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2084         double deviceScaleFactor = corePage()->deviceScaleFactor();
2085         graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2086         scaleFactor /= deviceScaleFactor;
2087     }
2088
2089     graphicsContext->scale(scaleFactor);
2090     graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
2091
2092     Color savedBackgroundColor = frameView->baseBackgroundColor();
2093     frameView->setBaseBackgroundColor(Color::transparent);
2094     frameView->setNodeToDraw(&node);
2095
2096     frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2097
2098     frameView->setBaseBackgroundColor(savedBackgroundColor);
2099     frameView->setNodeToDraw(nullptr);
2100
2101     return snapshot;
2102 }
2103
2104 void WebPage::pageDidScroll()
2105 {
2106 #if PLATFORM(IOS)
2107     if (!m_inDynamicSizeUpdate)
2108         m_dynamicSizeUpdateHistory.clear();
2109 #endif
2110     m_uiClient->pageDidScroll(this);
2111
2112     m_pageScrolledHysteresis.impulse();
2113
2114     send(Messages::WebPageProxy::PageDidScroll());
2115 }
2116
2117 void WebPage::pageStoppedScrolling()
2118 {
2119     // Maintain the current history item's scroll position up-to-date.
2120     if (Frame* frame = m_mainFrame->coreFrame())
2121         frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2122 }
2123
2124 #if USE(COORDINATED_GRAPHICS)
2125 void WebPage::pageDidRequestScroll(const IntPoint& point)
2126 {
2127 #if USE(COORDINATED_GRAPHICS_THREADED)
2128     drawingArea()->scroll(IntRect(point, IntSize()), IntSize());
2129 #endif
2130 }
2131 #endif
2132
2133 #if ENABLE(CONTEXT_MENUS)
2134 WebContextMenu* WebPage::contextMenu()
2135 {
2136     if (!m_contextMenu)
2137         m_contextMenu = WebContextMenu::create(this);
2138     return m_contextMenu.get();
2139 }
2140
2141 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2142 {
2143     corePage()->contextMenuController().clearContextMenu();
2144
2145     // Simulate a mouse click to generate the correct menu.
2146     PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick, WebCore::NoTap);
2147     corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2148     bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2149     auto* menu = handled ? contextMenu() : nullptr;
2150     PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick, WebCore::NoTap);
2151     corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2152
2153     return menu;
2154 }
2155 #endif
2156
2157 // Events 
2158
2159 static const WebEvent* g_currentEvent = 0;
2160
2161 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2162 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2163 // platform events passed to the event handler code.
2164 const WebEvent* WebPage::currentEvent()
2165 {
2166     return g_currentEvent;
2167 }
2168
2169 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
2170 {
2171     auto* drawingArea = this->drawingArea();
2172     if (!drawingArea)
2173         return;
2174
2175     drawingArea->setLayerTreeStateIsFrozen(frozen);
2176 }
2177
2178 void WebPage::callVolatilityCompletionHandlers()
2179 {
2180     auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2181     for (auto& completionHandler : completionHandlers)
2182         completionHandler();
2183 }
2184
2185 void WebPage::layerVolatilityTimerFired()
2186 {
2187     Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2188     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2189     if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2190         m_layerVolatilityTimer.stop();
2191         RELEASE_LOG_IF_ALLOWED("%p - WebPage - Attempted to mark layers as volatile, success? %d", this, didSucceed);
2192         callVolatilityCompletionHandlers();
2193         return;
2194     }
2195
2196     RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.value() * 1000);
2197     m_layerVolatilityTimer.startRepeating(newInterval);
2198 }
2199
2200 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2201 {
2202     return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2203 }
2204
2205 void WebPage::markLayersVolatile(std::function<void ()> completionHandler)
2206 {
2207     RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2208
2209     if (m_layerVolatilityTimer.isActive())
2210         m_layerVolatilityTimer.stop();
2211
2212     if (completionHandler)
2213         m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2214
2215     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2216     if (didSucceed || m_isSuspendedUnderLock) {
2217         if (didSucceed)
2218             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2219         else {
2220             // 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.
2221             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2222         }
2223         callVolatilityCompletionHandlers();
2224         return;
2225     }
2226
2227     RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.value() * 1000);
2228     m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2229 }
2230
2231 void WebPage::cancelMarkLayersVolatile()
2232 {
2233     RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2234     m_layerVolatilityTimer.stop();
2235     m_markLayersAsVolatileCompletionHandlers.clear();
2236 }
2237
2238 class CurrentEvent {
2239 public:
2240     explicit CurrentEvent(const WebEvent& event)
2241         : m_previousCurrentEvent(g_currentEvent)
2242     {
2243         g_currentEvent = &event;
2244     }
2245
2246     ~CurrentEvent()
2247     {
2248         g_currentEvent = m_previousCurrentEvent;
2249     }
2250
2251 private:
2252     const WebEvent* m_previousCurrentEvent;
2253 };
2254
2255 #if ENABLE(CONTEXT_MENUS)
2256 static bool isContextClick(const PlatformMouseEvent& event)
2257 {
2258 #if PLATFORM(COCOA)
2259     return WebEventFactory::shouldBeHandledAsContextClick(event);
2260 #else
2261     return event.button() == WebCore::RightButton;
2262 #endif
2263 }
2264
2265 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2266 {
2267     IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2268     HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2269
2270     Frame* frame = &page->corePage()->mainFrame();
2271     if (result.innerNonSharedNode())
2272         frame = result.innerNonSharedNode()->document().frame();
2273
2274     bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2275     if (handled)
2276         page->contextMenu()->show();
2277
2278     return handled;
2279 }
2280
2281 void WebPage::contextMenuForKeyEvent()
2282 {
2283     corePage()->contextMenuController().clearContextMenu();
2284
2285     Frame& frame = m_page->focusController().focusedOrMainFrame();
2286     bool handled = frame.eventHandler().sendContextMenuEventForKey();
2287     if (handled)
2288         contextMenu()->show();
2289 }
2290 #endif
2291
2292 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
2293 {
2294     Frame& frame = page->corePage()->mainFrame();
2295     if (!frame.view())
2296         return false;
2297
2298     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2299
2300     switch (platformMouseEvent.type()) {
2301         case PlatformEvent::MousePressed: {
2302 #if ENABLE(CONTEXT_MENUS)
2303             if (isContextClick(platformMouseEvent))
2304                 page->corePage()->contextMenuController().clearContextMenu();
2305 #endif
2306
2307             bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2308 #if ENABLE(CONTEXT_MENUS)
2309             if (isContextClick(platformMouseEvent))
2310                 handled = handleContextMenuEvent(platformMouseEvent, page);
2311 #endif
2312             return handled;
2313         }
2314         case PlatformEvent::MouseReleased:
2315             return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2316
2317         case PlatformEvent::MouseMoved:
2318             if (onlyUpdateScrollbars)
2319                 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2320             return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2321
2322         case PlatformEvent::MouseForceChanged:
2323         case PlatformEvent::MouseForceDown:
2324         case PlatformEvent::MouseForceUp:
2325             return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2326
2327         default:
2328             ASSERT_NOT_REACHED();
2329             return false;
2330     }
2331 }
2332
2333 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2334 {
2335     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2336
2337     m_userActivityHysteresis.impulse();
2338
2339     bool shouldHandleEvent = true;
2340
2341 #if ENABLE(CONTEXT_MENUS)
2342     // Don't try to handle any pending mouse events if a context menu is showing.
2343     if (m_isShowingContextMenu)
2344         shouldHandleEvent = false;
2345 #endif
2346 #if ENABLE(DRAG_SUPPORT)
2347     if (m_isStartingDrag)
2348         shouldHandleEvent = false;
2349 #endif
2350
2351     if (!shouldHandleEvent) {
2352         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2353         return;
2354     }
2355
2356     bool handled = false;
2357
2358 #if !PLATFORM(IOS)
2359     if (!handled && m_headerBanner)
2360         handled = m_headerBanner->mouseEvent(mouseEvent);
2361     if (!handled && m_footerBanner)
2362         handled = m_footerBanner->mouseEvent(mouseEvent);
2363 #endif // !PLATFORM(IOS)
2364
2365     if (!handled) {
2366         CurrentEvent currentEvent(mouseEvent);
2367
2368         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2369         // button is currently pressed. It is possible that neither of those things will be true since on
2370         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2371         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2372         // efficient scrollbars-only version of the event.
2373         bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
2374         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
2375     }
2376
2377     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2378 }
2379
2380 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2381 {
2382     Frame& frame = page->mainFrame();
2383     if (!frame.view())
2384         return false;
2385
2386     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2387     return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2388 }
2389
2390 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2391 {
2392     m_userActivityHysteresis.impulse();
2393
2394     CurrentEvent currentEvent(wheelEvent);
2395
2396     bool handled = handleWheelEvent(wheelEvent, m_page.get());
2397
2398     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2399 }
2400
2401 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2402 {
2403     if (!page->mainFrame().view())
2404         return false;
2405
2406     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2407         return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2408     return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2409 }
2410
2411 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2412 {
2413     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2414
2415     m_userActivityHysteresis.impulse();
2416
2417     CurrentEvent currentEvent(keyboardEvent);
2418
2419     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2420     // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2421     if (!handled)
2422         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2423
2424     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2425 }
2426
2427 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
2428 {
2429     bool isEnabled = false;
2430     int32_t state = 0;
2431     Frame& frame = m_page->focusController().focusedOrMainFrame();
2432     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2433         isEnabled = pluginView->isEditingCommandEnabled(commandName);
2434     else {
2435         Editor::Command command = frame.editor().command(commandName);
2436         state = command.state();
2437         isEnabled = command.isSupported() && command.isEnabled();
2438     }
2439
2440     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2441 }
2442
2443 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2444 {
2445     executeEditingCommand(commandName, argument);
2446 }
2447
2448 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest)
2449 {
2450     for (const auto& itemState : itemStates) {
2451         auto historyItem = toHistoryItem(itemState.pageState);
2452         historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2453         static_cast<WebBackForwardListProxy*>(corePage()->backForward().client())->addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID);
2454     }
2455 }
2456
2457 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2458 {
2459     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes);
2460 }
2461
2462 #if ENABLE(TOUCH_EVENTS)
2463 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2464 {
2465     if (!page->mainFrame().view())
2466         return false;
2467
2468     return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2469 }
2470 #endif
2471
2472 #if ENABLE(IOS_TOUCH_EVENTS)
2473 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2474 {
2475     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2476
2477     m_lastInteractionLocation = touchEvent.position();
2478     CurrentEvent currentEvent(touchEvent);
2479     handled = handleTouchEvent(touchEvent, m_page.get());
2480 }
2481
2482 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2483 {
2484     EventDispatcher::TouchEventQueue queuedEvents;
2485     WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2486     dispatchAsynchronousTouchEvents(queuedEvents);
2487
2488     dispatchTouchEvent(touchEvent, handled);
2489 }
2490 #elif ENABLE(TOUCH_EVENTS)
2491 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2492 {
2493     CurrentEvent currentEvent(touchEvent);
2494
2495     bool handled = handleTouchEvent(touchEvent, m_page.get());
2496
2497     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2498 }
2499 #endif
2500
2501 #if ENABLE(MAC_GESTURE_EVENTS)
2502 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2503 {
2504     if (!page->mainFrame().view())
2505         return false;
2506
2507     return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2508 }
2509
2510 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2511 {
2512     CurrentEvent currentEvent(gestureEvent);
2513     bool handled = handleGestureEvent(gestureEvent, m_page.get());
2514     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2515 }
2516 #endif
2517
2518 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2519 {
2520     return page->userInputBridge().scrollRecursively(direction, granularity);
2521 }
2522
2523 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2524 {
2525     return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2526 }
2527
2528 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2529 {
2530     return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2531 }
2532
2533 void WebPage::centerSelectionInVisibleArea()
2534 {
2535     Frame& frame = m_page->focusController().focusedOrMainFrame();
2536     frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2537     findController().showFindIndicatorInSelection();
2538 }
2539
2540 bool WebPage::isControlledByAutomation() const
2541 {
2542     return m_page->isControlledByAutomation();
2543 }
2544
2545 void WebPage::setControlledByAutomation(bool controlled)
2546 {
2547     m_page->setControlledByAutomation(controlled);
2548 }
2549
2550 void WebPage::insertNewlineInQuotedContent()
2551 {
2552     Frame& frame = m_page->focusController().focusedOrMainFrame();
2553     if (frame.selection().isNone())
2554         return;
2555     frame.editor().insertParagraphSeparatorInQuotedContent();
2556 }
2557
2558 #if ENABLE(REMOTE_INSPECTOR)
2559 void WebPage::setAllowsRemoteInspection(bool allow)
2560 {
2561     m_page->setRemoteInspectionAllowed(allow);
2562 }
2563
2564 void WebPage::setRemoteInspectionNameOverride(const String& name)
2565 {
2566     m_page->setRemoteInspectionNameOverride(name);
2567 }
2568 #endif
2569
2570 void WebPage::setDrawsBackground(bool drawsBackground)
2571 {
2572     if (m_drawsBackground == drawsBackground)
2573         return;
2574
2575     m_drawsBackground = drawsBackground;
2576
2577     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2578         if (FrameView* view = coreFrame->view())
2579             view->setTransparent(!drawsBackground);
2580     }
2581
2582     m_drawingArea->pageBackgroundTransparencyChanged();
2583     m_drawingArea->setNeedsDisplay();
2584 }
2585
2586 #if HAVE(COREANIMATION_FENCES)
2587 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
2588 {
2589     m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
2590
2591     setTopContentInset(contentInset);
2592
2593     mach_port_deallocate(mach_task_self(), fencePort.port());
2594 }
2595 #endif
2596
2597 void WebPage::setTopContentInset(float contentInset)
2598 {
2599     if (contentInset == m_page->topContentInset())
2600         return;
2601
2602     m_page->setTopContentInset(contentInset);
2603
2604     for (auto* pluginView : m_pluginViews)
2605         pluginView->topContentInsetDidChange();
2606 }
2607
2608 void WebPage::viewWillStartLiveResize()
2609 {
2610     if (!m_page)
2611         return;
2612
2613     // FIXME: This should propagate to all ScrollableAreas.
2614     Frame& frame = m_page->focusController().focusedOrMainFrame();
2615     if (FrameView* view = frame.view())
2616         view->willStartLiveResize();
2617 }
2618
2619 void WebPage::viewWillEndLiveResize()
2620 {
2621     if (!m_page)
2622         return;
2623
2624     // FIXME: This should propagate to all ScrollableAreas.
2625     Frame& frame = m_page->focusController().focusedOrMainFrame();
2626     if (FrameView* view = frame.view())
2627         view->willEndLiveResize();
2628 }
2629
2630 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, uint64_t callbackID)
2631 {
2632     if (!m_page)
2633         return;
2634
2635     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2636
2637     Frame& frame = m_page->focusController().focusedOrMainFrame();
2638     frame.document()->setFocusedElement(0);
2639
2640     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2641         PlatformKeyboardEvent platformEvent(platform(event));
2642         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2643         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2644
2645         send(Messages::WebPageProxy::VoidCallback(callbackID));
2646         return;
2647     }
2648
2649     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
2650     send(Messages::WebPageProxy::VoidCallback(callbackID));
2651 }
2652
2653 void WebPage::setCanStartMediaTimerFired()
2654 {
2655     if (m_page)
2656         m_page->setCanStartMedia(true);
2657 }
2658
2659 void WebPage::updateIsInWindow(bool isInitialState)
2660 {
2661     bool isInWindow = m_activityState & WebCore::ActivityState::IsInWindow;
2662
2663     if (!isInWindow) {
2664         m_setCanStartMediaTimer.stop();
2665         m_page->setCanStartMedia(false);
2666         
2667         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2668         if (!isInitialState)
2669             WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2670     } else {
2671         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2672         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2673         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2674         if (m_mayStartMediaWhenInWindow)
2675             m_setCanStartMediaTimer.startOneShot(0_s);
2676
2677         WebProcess::singleton().pageDidEnterWindow(m_pageID);
2678     }
2679
2680     if (isInWindow)
2681         layoutIfNeeded();
2682 }
2683
2684 void WebPage::visibilityDidChange()
2685 {
2686     bool isVisible = m_activityState & ActivityState::IsVisible;
2687     if (!isVisible) {
2688         // We save the document / scroll state when backgrounding a tab so that we are able to restore it
2689         // if it gets terminated while in the background.
2690         if (auto* frame = m_mainFrame->coreFrame())
2691             frame->loader().history().saveDocumentAndScrollState();
2692     }
2693 }
2694
2695 void WebPage::setActivityState(ActivityState::Flags activityState, bool wantsDidUpdateActivityState, const Vector<uint64_t>& callbackIDs)
2696 {
2697     ActivityState::Flags changed = m_activityState ^ activityState;
2698     m_activityState = activityState;
2699
2700     if (changed)
2701         updateThrottleState();
2702
2703     m_page->setActivityState(activityState);
2704     for (auto* pluginView : m_pluginViews)
2705         pluginView->activityStateDidChange(changed);
2706
2707     m_drawingArea->activityStateDidChange(changed, wantsDidUpdateActivityState, callbackIDs);
2708     WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
2709
2710     if (changed & ActivityState::IsInWindow)
2711         updateIsInWindow();
2712
2713     if (changed & ActivityState::IsVisible)
2714         visibilityDidChange();
2715 }
2716
2717 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
2718 {
2719     m_layerHostingMode = layerHostingMode;
2720
2721     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2722
2723     for (auto* pluginView : m_pluginViews)
2724         pluginView->setLayerHostingMode(m_layerHostingMode);
2725 }
2726
2727 void WebPage::setSessionID(SessionID sessionID)
2728 {
2729     if (sessionID.isEphemeral())
2730         WebProcess::singleton().ensurePrivateBrowsingSession(sessionID);
2731     m_page->setSessionID(sessionID);
2732 }
2733
2734 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, const DownloadID& downloadID)
2735 {
2736     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2737     if (!frame)
2738         return;
2739     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID);
2740 }
2741
2742 void WebPage::didStartPageTransition()
2743 {
2744     m_drawingArea->setLayerTreeStateIsFrozen(true);
2745
2746 #if PLATFORM(MAC)
2747     bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
2748 #endif
2749     m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
2750     m_isAssistingNodeDueToUserInteraction = false;
2751     m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
2752 #if PLATFORM(MAC)
2753     if (hasPreviouslyFocusedDueToUserInteraction)
2754         send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
2755     if (m_needsHiddenContentEditableQuirk) {
2756         m_needsHiddenContentEditableQuirk = false;
2757         send(Messages::WebPageProxy::SetNeedsHiddenContentEditableQuirk(m_needsHiddenContentEditableQuirk));
2758     }
2759     if (m_needsPlainTextQuirk) {
2760         m_needsPlainTextQuirk = false;
2761         send(Messages::WebPageProxy::SetNeedsPlainTextQuirk(m_needsPlainTextQuirk));
2762     }
2763 #endif
2764 }
2765
2766 void WebPage::didCompletePageTransition()
2767 {
2768     m_drawingArea->setLayerTreeStateIsFrozen(false);
2769 }
2770
2771 void WebPage::show()
2772 {
2773     send(Messages::WebPageProxy::ShowPage());
2774 }
2775
2776 String WebPage::userAgent(const URL& webCoreURL) const
2777 {
2778     return userAgent(nullptr, webCoreURL);
2779 }
2780
2781 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2782 {
2783     if (frame) {
2784         String userAgent = m_loaderClient->userAgentForURL(*frame, webcoreURL);
2785         if (!userAgent.isEmpty())
2786             return userAgent;
2787     }
2788
2789     String userAgent = platformUserAgent(webcoreURL);
2790     if (!userAgent.isEmpty())
2791         return userAgent;
2792     return m_userAgent;
2793 }
2794     
2795 void WebPage::setUserAgent(const String& userAgent)
2796 {
2797     m_userAgent = userAgent;
2798 }
2799
2800 void WebPage::suspendActiveDOMObjectsAndAnimations()
2801 {
2802     m_page->suspendActiveDOMObjectsAndAnimations();
2803 }
2804
2805 void WebPage::resumeActiveDOMObjectsAndAnimations()
2806 {
2807     m_page->resumeActiveDOMObjectsAndAnimations();
2808 }
2809
2810 IntPoint WebPage::screenToRootView(const IntPoint& point)
2811 {
2812     IntPoint windowPoint;
2813     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2814     return windowPoint;
2815 }
2816     
2817 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2818 {
2819     IntRect screenRect;
2820     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2821     return screenRect;
2822 }
2823     
2824 #if PLATFORM(IOS)
2825 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2826 {
2827     IntPoint windowPoint;
2828     sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2829     return windowPoint;
2830 }
2831
2832 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2833 {
2834     IntRect screenRect;
2835     sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2836     return screenRect;
2837 }
2838 #endif
2839
2840 KeyboardUIMode WebPage::keyboardUIMode()
2841 {
2842     bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
2843     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2844 }
2845
2846 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2847 {
2848     // NOTE: We need to be careful when running scripts that the objects we depend on don't
2849     // disappear during script execution.
2850
2851     RefPtr<SerializedScriptValue> serializedResultValue;
2852     JSLockHolder lock(commonVM());
2853     bool hadException = true;
2854     ExceptionDetails details;
2855     if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true, &details)) {
2856         hadException = false;
2857         serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
2858             toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr);
2859     }
2860
2861     IPC::DataReference dataReference;
2862     if (serializedResultValue)
2863         dataReference = serializedResultValue->data();
2864     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
2865 }
2866
2867 void WebPage::getContentsAsString(uint64_t callbackID)
2868 {
2869     String resultString = m_mainFrame->contentsAsString();
2870     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2871 }
2872
2873 #if ENABLE(MHTML)
2874 void WebPage::getContentsAsMHTMLData(uint64_t callbackID)
2875 {
2876     auto buffer = MHTMLArchive::generateMHTMLData(m_page.get());
2877
2878     // FIXME: Use SharedBufferDataReference.
2879     IPC::DataReference dataReference;
2880     dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2881     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2882 }
2883 #endif
2884
2885 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2886 {
2887     String resultString = renderTreeExternalRepresentation();
2888     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2889 }
2890
2891 static Frame* frameWithSelection(Page* page)
2892 {
2893     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2894         if (frame->selection().isRange())
2895             return frame;
2896     }
2897
2898     return 0;
2899 }
2900
2901 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2902 {
2903 #if PLATFORM(COCOA)
2904     RetainPtr<CFDataRef> data;
2905     if (Frame* frame = frameWithSelection(m_page.get()))
2906         data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
2907 #endif
2908
2909     IPC::DataReference dataReference;
2910 #if PLATFORM(COCOA)
2911     if (data)
2912         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2913 #endif
2914     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2915 }
2916
2917 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2918 {
2919     WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
2920     String resultString = focusedOrMainFrame->selectionAsString();
2921     if (resultString.isEmpty())
2922         resultString = focusedOrMainFrame->contentsAsString();
2923     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2924 }
2925
2926 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2927 {
2928     String resultString;
2929     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2930        resultString = frame->source();
2931
2932     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2933 }
2934
2935 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2936 {
2937     RefPtr<SharedBuffer> buffer;
2938     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2939         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
2940             buffer = pluginView->liveResourceData();
2941         if (!buffer) {
2942             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
2943                 buffer = loader->mainResourceData();
2944         }
2945     }
2946
2947     // FIXME: Use SharedBufferDataReference.
2948     IPC::DataReference dataReference;
2949     if (buffer)
2950         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2951     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2952 }
2953
2954 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2955 {
2956     DocumentLoader* loader = frame->loader().documentLoader();
2957     if (!loader)
2958         return nullptr;
2959
2960     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2961     if (!subresource)
2962         return nullptr;
2963
2964     return &subresource->data();
2965 }
2966
2967 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2968 {
2969     RefPtr<SharedBuffer> buffer;
2970     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2971         URL resourceURL(URL(), resourceURLString);
2972         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2973         if (!buffer) {
2974             // Try to get the resource data from the cache.
2975             buffer = cachedResponseDataForURL(resourceURL);
2976         }
2977     }
2978
2979     // FIXME: Use SharedBufferDataReference.
2980     IPC::DataReference dataReference;
2981     if (buffer)
2982         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2983     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2984 }
2985
2986 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2987 {
2988 #if PLATFORM(COCOA)
2989     RetainPtr<CFDataRef> data;
2990     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2991         data = frame->webArchiveData(nullptr, nullptr);
2992 #else
2993     UNUSED_PARAM(frameID);
2994 #endif
2995
2996     IPC::DataReference dataReference;
2997 #if PLATFORM(COCOA)
2998     if (data)
2999         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
3000 #endif
3001     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3002 }
3003
3004 void WebPage::forceRepaintWithoutCallback()
3005 {
3006     m_drawingArea->forceRepaint();
3007 }
3008
3009 void WebPage::forceRepaint(uint64_t callbackID)
3010 {
3011     if (m_drawingArea->forceRepaintAsync(callbackID))
3012         return;
3013
3014     forceRepaintWithoutCallback();
3015     send(Messages::WebPageProxy::VoidCallback(callbackID));
3016 }
3017
3018 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3019 {
3020     WebPreferencesStore::removeTestRunnerOverrides();
3021     updatePreferences(store);
3022 }
3023
3024 void WebPage::updatePreferences(const WebPreferencesStore& store)
3025 {
3026     Settings& settings = m_page->settings();
3027
3028     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3029     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3030     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3031     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3032
3033     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3034
3035 #if PLATFORM(COCOA)
3036     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3037 #endif
3038
3039     // FIXME: This should be generated from macro expansion for all preferences,
3040     // but we currently don't match the naming of WebCore exactly so we are
3041     // handrolling the boolean and integer preferences until that is fixed.
3042
3043 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue, HumanReadableName, HumanReadableDescription) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
3044
3045     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
3046
3047 #undef INITIALIZE_SETTINGS
3048
3049     settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
3050     settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
3051     settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
3052     settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
3053     settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
3054     settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
3055     settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));    
3056     settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
3057     settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
3058     settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
3059     settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
3060     if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3061         setSessionID(SessionID::legacyPrivateSessionID());
3062     else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
3063         setSessionID(SessionID::defaultSessionID());
3064     settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
3065     settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3066     settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
3067     settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
3068     settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
3069     settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
3070     settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
3071     settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey()));
3072 #if ENABLE(WEB_ARCHIVE)
3073     settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
3074 #endif
3075     settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
3076     settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
3077     settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
3078     settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
3079     settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
3080     settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
3081     settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
3082     settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
3083     settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
3084     settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
3085     settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
3086     settings.setNeedsStorageAccessFromFileURLsQuirk(store.getBoolValueForKey(WebPreferencesKey::needsStorageAccessFromFileURLsQuirkKey()));
3087
3088     settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
3089     settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
3090     settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
3091     settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
3092     settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
3093     settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
3094     settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
3095     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3096     settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
3097
3098     settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
3099     settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
3100     settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
3101     settings.setDisplayListDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::displayListDrawingEnabledKey()));
3102     settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
3103     settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
3104     settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
3105     settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
3106     settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey()));
3107     settings.setUseGiantTiles(store.getBoolValueForKey(WebPreferencesKey::useGiantTilesKey()));
3108     settings.setSubpixelAntialiasedLayerTextEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelAntialiasedLayerTextEnabledKey()));
3109
3110     settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
3111     settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
3112 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
3113     RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey()));
3114 #endif
3115 #if ENABLE(WEB_ANIMATIONS)
3116     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled(store.getBoolValueForKey(WebPreferencesKey::webAnimationsEnabledKey()));
3117 #endif
3118     settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
3119     settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
3120     settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
3121     bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3122     settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3123     settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3124     settings.setRequiresUserGestureToLoadVideo(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureToLoadVideoKey()));
3125     settings.setMainContentUserGestureOverrideEnabled(store.getBoolValueForKey(WebPreferencesKey::mainContentUserGestureOverrideEnabledKey()));
3126     settings.setMediaUserGestureInheritsFromDocument(store.getBoolValueForKey(WebPreferencesKey::mediaUserGestureInheritsFromDocumentKey()));
3127     settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey()));
3128     settings.setAllowsInlineMediaPlaybackAfterFullscreen(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackAfterFullscreenKey()));
3129     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute(store.getBoolValueForKey(WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey()));
3130     settings.setInvisibleAutoplayNotPermitted(store.getBoolValueForKey(WebPreferencesKey::invisibleAutoplayNotPermittedKey()));
3131     settings.setMediaDataLoadsAutomatically(store.getBoolValueForKey(WebPreferencesKey::mediaDataLoadsAutomaticallyKey()));
3132 #if ENABLE(ATTACHMENT_ELEMENT)
3133     settings.setAttachmentElementEnabled(store.getBoolValueForKey(WebPreferencesKey::attachmentElementEnabledKey()));
3134 #endif
3135     settings.setAllowsPictureInPictureMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey()));
3136     settings.setMediaControlsScaleWithPageZoom(store.getBoolValueForKey(WebPreferencesKey::mediaControlsScaleWithPageZoomKey()));
3137     settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
3138     settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
3139     settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
3140 #if ENABLE(SMOOTH_SCROLLING)
3141     settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
3142 #endif
3143     settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
3144     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3145     settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
3146
3147     settings.setHttpEquivEnabled(store.getBoolValueForKey(WebPreferencesKey::httpEquivEnabledKey()));
3148
3149     settings.setSelectionPaintingWithoutSelectionGapsEnabled(store.getBoolValueForKey(WebPreferencesKey::selectionPaintingWithoutSelectionGapsEnabledKey()));
3150
3151     DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3152
3153 #if ENABLE(FULLSCREEN_API)
3154     settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
3155 #endif
3156
3157 #if USE(AVFOUNDATION)
3158     settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
3159     settings.setAVFoundationNSURLSessionEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationNSURLSessionEnabledKey()));
3160 #endif
3161
3162 #if USE(GSTREAMER)
3163     settings.setGStreamerEnabled(store.getBoolValueForKey(WebPreferencesKey::isGStreamerEnabledKey()));
3164 #endif
3165
3166 #if PLATFORM(COCOA)
3167     settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
3168 #endif
3169
3170 #if PLATFORM(IOS) && HAVE(AVKIT)
3171     settings.setAVKitEnabled(true);
3172 #endif
3173
3174 #if ENABLE(WEB_AUDIO)
3175     settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
3176 #endif
3177
3178 #if ENABLE(MEDIA_STREAM)
3179     RuntimeEnabledFeatures::sharedFeatures().setMediaDevicesEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaDevicesEnabledKey()));
3180     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
3181 #endif
3182
3183 #if ENABLE(WEB_RTC)
3184     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled(store.getBoolValueForKey(WebPreferencesKey::peerConnectionEnabledKey()));
3185     RuntimeEnabledFeatures::sharedFeatures().setWebRTCLegacyAPIEnabled(!store.getBoolValueForKey(WebPreferencesKey::webRTCLegacyAPIDisabledKey()));
3186 #endif
3187
3188 #if ENABLE(SERVICE_CONTROLS)
3189     settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
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     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
3282
3283     auto userInterfaceDirectionPolicyCandidate = static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey()));
3284     if (userInterfaceDirectionPolicyCandidate == WebCore::UserInterfaceDirectionPolicy::Content || userInterfaceDirectionPolicyCandidate == WebCore::UserInterfaceDirectionPolicy::System)
3285         settings.setUserInterfaceDirectionPolicy(userInterfaceDirectionPolicyCandidate);
3286     TextDirection systemLayoutDirectionCandidate = static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey()));
3287     if (systemLayoutDirectionCandidate == WebCore::LTR || systemLayoutDirectionCandidate == WebCore::RTL)
3288         settings.setSystemLayoutDirection(systemLayoutDirectionCandidate);
3289
3290 #if ENABLE(APPLE_PAY)
3291     settings.setApplePayEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3292     settings.setApplePayCapabilityDisclosureAllowed(store.getBoolValueForKey(WebPreferencesKey::applePayCapabilityDisclosureAllowedKey()));
3293 #endif
3294
3295 #if PLATFORM(IOS)
3296     settings.setUseImageDocumentForSubframePDF(true);
3297 #endif
3298
3299 #if ENABLE(DATA_DETECTION)
3300     settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3301 #endif
3302 #if ENABLE(GAMEPAD)
3303     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
3304 #endif
3305
3306 #if ENABLE(SERVICE_CONTROLS)
3307     settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
3308 #endif
3309
3310 #if ENABLE(FETCH_API)
3311     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled(store.getBoolValueForKey(WebPreferencesKey::fetchAPIEnabledKey()));
3312 #endif
3313
3314 #if ENABLE(DOWNLOAD_ATTRIBUTE)
3315     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled(store.getBoolValueForKey(WebPreferencesKey::downloadAttributeEnabledKey()));
3316 #endif
3317
3318     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled(store.getBoolValueForKey(WebPreferencesKey::shadowDOMEnabledKey()));
3319
3320     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3321
3322     // Experimental Features.
3323
3324     RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
3325
3326     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled(store.getBoolValueForKey(WebPreferencesKey::customElementsEnabledKey()));
3327
3328 #if ENABLE(WEBGL2)
3329     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled(store.getBoolValueForKey(WebPreferencesKey::webGL2EnabledKey()));
3330 #endif
3331
3332 #if ENABLE(WEBGPU)
3333     RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled(store.getBoolValueForKey(WebPreferencesKey::webGPUEnabledKey()));
3334 #endif
3335
3336     settings.setSpringTimingFunctionEnabled(store.getBoolValueForKey(WebPreferencesKey::springTimingFunctionEnabledKey()));
3337
3338     settings.setConstantPropertiesEnabled(store.getBoolValueForKey(WebPreferencesKey::constantPropertiesEnabledKey()));
3339
3340     settings.setViewportFitEnabled(store.getBoolValueForKey(WebPreferencesKey::viewportFitEnabledKey()));
3341
3342     settings.setVisualViewportEnabled(store.getBoolValueForKey(WebPreferencesKey::visualViewportEnabledKey()));
3343
3344     settings.setInputEventsEnabled(store.getBoolValueForKey(WebPreferencesKey::inputEventsEnabledKey()));
3345     RuntimeEnabledFeatures::sharedFeatures().setInputEventsEnabled(store.getBoolValueForKey(WebPreferencesKey::inputEventsEnabledKey()));
3346
3347     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::modernMediaControlsEnabledKey()));
3348
3349 #if ENABLE(ENCRYPTED_MEDIA)
3350     RuntimeEnabledFeatures::sharedFeatures().setEncryptedMediaAPIEnabled(store.getBoolValueForKey(WebPreferencesKey::encryptedMediaAPIEnabledKey()));
3351 #endif
3352
3353 #if ENABLE(INTERSECTION_OBSERVER)
3354     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(store.getBoolValueForKey(WebPreferencesKey::intersectionObserverEnabledKey()));
3355 #endif
3356
3357     RuntimeEnabledFeatures::sharedFeatures().setDisplayContentsEnabled(store.getBoolValueForKey(WebPreferencesKey::displayContentsEnabledKey()));
3358     RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(store.getBoolValueForKey(WebPreferencesKey::userTimingEnabledKey()));
3359     RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(store.getBoolValueForKey(WebPreferencesKey::resourceTimingEnabledKey()));
3360     RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(store.getBoolValueForKey(WebPreferencesKey::linkPreloadEnabledKey()));
3361     RuntimeEnabledFeatures::sharedFeatures().setMediaPreloadingEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaPreloadingEnabledKey()));
3362     RuntimeEnabledFeatures::sharedFeatures().setCredentialManagementEnabled(store.getBoolValueForKey(WebPreferencesKey::credentialManagementEnabledKey()));
3363     RuntimeEnabledFeatures::sharedFeatures().setIsSecureContextAttributeEnabled(store.getBoolValueForKey(WebPreferencesKey::isSecureContextAttributeEnabledKey()));
3364
3365     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3366     if (m_processSuppressionEnabled != processSuppressionEnabled) {
3367         m_processSuppressionEnabled = processSuppressionEnabled;
3368         updateThrottleState();
3369     }
3370
3371     settings.setSubresourceIntegrityEnabled(store.getBoolValueForKey(WebPreferencesKey::subresourceIntegrityEnabledKey()));
3372
3373     platformPreferencesDidChange(store);
3374
3375     if (m_drawingArea)
3376         m_drawingArea->updatePreferences(store);
3377
3378 #if PLATFORM(IOS)
3379     m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3380     m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3381     setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3382 #endif
3383     settings.setLargeImageAsyncDecodingEnabled(store.getBoolValueForKey(WebPreferencesKey::largeImageAsyncDecodingEnabledKey()));
3384     settings.setAnimatedImageAsyncDecodingEnabled(store.getBoolValueForKey(WebPreferencesKey::animatedImageAsyncDecodingEnabledKey()));
3385     settings.setShouldSuppressKeyboardInputDuringProvisionalNavigation(store.getBoolValueForKey(WebPreferencesKey::shouldSuppressKeyboardInputDuringProvisionalNavigationKey()));
3386     settings.setMediaContentTypesRequiringHardwareSupport(store.getStringValueForKey(WebPreferencesKey::mediaContentTypesRequiringHardwareSupportKey()));
3387 }
3388
3389 #if ENABLE(DATA_DETECTION)
3390 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3391 {
3392     DataDetectionResult dataDetectionResult;
3393     dataDetectionResult.results = detectionResults;
3394     send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3395 }
3396 #endif
3397
3398 #if PLATFORM(COCOA)
3399 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3400 {
3401     FrameView* frameView = corePage()->mainFrame().view();
3402     if (!frameView)
3403         return;
3404
3405     layerTransaction.setContentsSize(frameView->contentsSize());
3406     layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3407     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3408     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3409     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3410
3411     layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3412     layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3413     layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3414
3415 #if PLATFORM(IOS)
3416     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3417     layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3418     layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3419     layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3420     layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3421     layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3422     layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3423     layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3424     layerTransaction.setIsInStableState(m_isInStableState);
3425     layerTransaction.setAllowsUserScaling(allowsUserScaling());
3426 #endif
3427
3428 #if PLATFORM(MAC)
3429     layerTransaction.setScrollPosition(frameView->scrollPosition());
3430 #endif
3431 }
3432
3433 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3434 {
3435 #if PLATFORM(IOS)
3436     if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3437         Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3438         m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3439
3440         m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3441     }
3442 #else
3443     UNUSED_PARAM(timestamp);
3444 #endif
3445 }
3446 #endif
3447
3448 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3449 {
3450     if (m_isClosed)
3451         return nullptr;
3452     if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3453         m_inspector = WebInspector::create(this);
3454     return m_inspector.get();
3455 }
3456
3457 WebInspectorUI* WebPage::inspectorUI()
3458 {
3459     if (m_isClosed)
3460         return nullptr;
3461     if (!m_inspectorUI)
3462         m_inspectorUI = WebInspectorUI::create(*this);
3463     return m_inspectorUI.get();
3464 }
3465
3466 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3467 {
3468     if (m_isClosed)
3469         return nullptr;
3470     if (!m_remoteInspectorUI)
3471         m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3472     return m_remoteInspectorUI.get();
3473 }
3474
3475 #if (PLATFORM(IOS) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3476 WebPlaybackSessionManager& WebPage::playbackSessionManager()
3477 {
3478     if (!m_playbackSessionManager)
3479         m_playbackSessionManager = WebPlaybackSessionManager::create(*this);
3480     return *m_playbackSessionManager;
3481 }
3482
3483 WebVideoFullscreenManager& WebPage::videoFullscreenManager()
3484 {
3485     if (!m_videoFullscreenManager)
3486         m_videoFullscreenManager = WebVideoFullscreenManager::create(*this, playbackSessionManager());
3487     return *m_videoFullscreenManager;
3488 }
3489 #endif
3490
3491 #if PLATFORM(IOS)
3492 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3493 {
3494     m_page->setAllowsMediaDocumentInlinePlayback(allows);
3495 }
3496 #endif
3497
3498 #if ENABLE(FULLSCREEN_API)
3499 WebFullScreenManager* WebPage::fullScreenManager()
3500 {
3501     if (!m_fullScreenManager)
3502         m_fullScreenManager = WebFullScreenManager::create(this);
3503     return m_fullScreenManager.get();
3504 }
3505 #endif
3506
3507 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3508 {
3509     if (m_notificationPermissionRequestManager)<