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