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