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