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