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