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