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