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