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