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