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