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