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