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)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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.
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"
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"
88 #include "WebEventConversion.h"
89 #include "WebEventFactory.h"
91 #include "WebFrameLoaderClient.h"
92 #include "WebFullScreenManager.h"
93 #include "WebFullScreenManagerMessages.h"
94 #include "WebGamepadProvider.h"
95 #include "WebGeolocationClient.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 "WebPageMessages.h"
108 #include "WebPageOverlay.h"
109 #include "WebPageProxyMessages.h"
110 #include "WebPaymentCoordinator.h"
111 #include "WebPerformanceLoggingClient.h"
112 #include "WebPlugInClient.h"
113 #include "WebPluginInfoProvider.h"
114 #include "WebPopupMenu.h"
115 #include "WebPreferencesDefinitions.h"
116 #include "WebPreferencesKeys.h"
117 #include "WebPreferencesStore.h"
118 #include "WebProcess.h"
119 #include "WebProcessPoolMessages.h"
120 #include "WebProcessProxyMessages.h"
121 #include "WebProgressTrackerClient.h"
122 #include "WebSocketProvider.h"
123 #include "WebStorageNamespaceProvider.h"
124 #include "WebURLSchemeHandlerProxy.h"
125 #include "WebUndoStep.h"
126 #include "WebUserContentController.h"
127 #include "WebUserMediaClient.h"
128 #include "WebValidationMessageClient.h"
129 #include "WebsiteDataStoreParameters.h"
130 #include <JavaScriptCore/APICast.h>
131 #include <JavaScriptCore/JSCInlines.h>
132 #include <JavaScriptCore/JSCJSValue.h>
133 #include <JavaScriptCore/JSLock.h>
134 #include <JavaScriptCore/ProfilerDatabase.h>
135 #include <JavaScriptCore/SamplingProfiler.h>
136 #include <WebCore/ApplicationCacheStorage.h>
137 #include <WebCore/ArchiveResource.h>
138 #include <WebCore/BackForwardController.h>
139 #include <WebCore/Chrome.h>
140 #include <WebCore/CommonVM.h>
141 #include <WebCore/ContextMenuController.h>
142 #include <WebCore/DataTransfer.h>
143 #include <WebCore/DatabaseManager.h>
144 #include <WebCore/DeprecatedGlobalSettings.h>
145 #include <WebCore/DocumentFragment.h>
146 #include <WebCore/DocumentLoader.h>
147 #include <WebCore/DocumentMarkerController.h>
148 #include <WebCore/DragController.h>
149 #include <WebCore/DragData.h>
150 #include <WebCore/Editing.h>
151 #include <WebCore/Editor.h>
152 #include <WebCore/ElementIterator.h>
153 #include <WebCore/EventHandler.h>
154 #include <WebCore/EventNames.h>
155 #include <WebCore/File.h>
156 #include <WebCore/FocusController.h>
157 #include <WebCore/FontAttributeChanges.h>
158 #include <WebCore/FontAttributes.h>
159 #include <WebCore/FormState.h>
160 #include <WebCore/Frame.h>
161 #include <WebCore/FrameLoadRequest.h>
162 #include <WebCore/FrameLoaderTypes.h>
163 #include <WebCore/FrameView.h>
164 #include <WebCore/GraphicsContext3D.h>
165 #include <WebCore/HTMLAttachmentElement.h>
166 #include <WebCore/HTMLFormElement.h>
167 #include <WebCore/HTMLImageElement.h>
168 #include <WebCore/HTMLInputElement.h>
169 #include <WebCore/HTMLMenuElement.h>
170 #include <WebCore/HTMLMenuItemElement.h>
171 #include <WebCore/HTMLOListElement.h>
172 #include <WebCore/HTMLPlugInElement.h>
173 #include <WebCore/HTMLPlugInImageElement.h>
174 #include <WebCore/HTMLUListElement.h>
175 #include <WebCore/HistoryController.h>
176 #include <WebCore/HistoryItem.h>
177 #include <WebCore/HitTestResult.h>
178 #include <WebCore/InspectorController.h>
179 #include <WebCore/JSDOMExceptionHandling.h>
180 #include <WebCore/JSDOMWindow.h>
181 #include <WebCore/KeyboardEvent.h>
182 #include <WebCore/MIMETypeRegistry.h>
183 #include <WebCore/MouseEvent.h>
184 #include <WebCore/NotImplemented.h>
185 #include <WebCore/Page.h>
186 #include <WebCore/PageConfiguration.h>
187 #include <WebCore/PingLoader.h>
188 #include <WebCore/PlatformKeyboardEvent.h>
189 #include <WebCore/PluginDocument.h>
190 #include <WebCore/PrintContext.h>
191 #include <WebCore/PromisedAttachmentInfo.h>
192 #include <WebCore/Range.h>
193 #include <WebCore/RemoteDOMWindow.h>
194 #include <WebCore/RemoteFrame.h>
195 #include <WebCore/RenderLayer.h>
196 #include <WebCore/RenderTheme.h>
197 #include <WebCore/RenderTreeAsText.h>
198 #include <WebCore/RenderView.h>
199 #include <WebCore/ResourceRequest.h>
200 #include <WebCore/ResourceResponse.h>
201 #include <WebCore/RuntimeEnabledFeatures.h>
202 #include <WebCore/SchemeRegistry.h>
203 #include <WebCore/ScriptController.h>
204 #include <WebCore/SerializedScriptValue.h>
205 #include <WebCore/ServiceWorkerProvider.h>
206 #include <WebCore/Settings.h>
207 #include <WebCore/ShadowRoot.h>
208 #include <WebCore/SharedBuffer.h>
209 #include <WebCore/StyleProperties.h>
210 #include <WebCore/SubframeLoader.h>
211 #include <WebCore/SubstituteData.h>
212 #include <WebCore/TextIterator.h>
213 #include <WebCore/UserGestureIndicator.h>
214 #include <WebCore/UserInputBridge.h>
215 #include <WebCore/UserScript.h>
216 #include <WebCore/UserStyleSheet.h>
217 #include <WebCore/UserTypingGestureIndicator.h>
218 #include <WebCore/VisiblePosition.h>
219 #include <WebCore/VisibleUnits.h>
220 #include <WebCore/WebGLStateTracker.h>
221 #include <WebCore/markup.h>
222 #include <pal/SessionID.h>
223 #include <wtf/ProcessID.h>
224 #include <wtf/RunLoop.h>
225 #include <wtf/SetForScope.h>
226 #include <wtf/text/TextStream.h>
228 #if ENABLE(DATA_DETECTION)
229 #include "DataDetectionResult.h"
233 #include <WebCore/MHTMLArchive.h>
236 #if ENABLE(POINTER_LOCK)
237 #include <WebCore/PointerLockController.h>
241 #include "PDFPlugin.h"
242 #include "PlaybackSessionManager.h"
243 #include "RemoteLayerTreeTransaction.h"
244 #include "TouchBarMenuData.h"
245 #include "TouchBarMenuItemData.h"
246 #include "VideoFullscreenManager.h"
247 #include "WKStringCF.h"
248 #include <WebCore/LegacyWebArchive.h>
249 #include <wtf/MachSendRight.h>
253 #include "WebPrintOperationGtk.h"
254 #include "WebSelectionData.h"
258 #if PLATFORM(IOS_FAMILY)
259 #include "RemoteLayerTreeDrawingArea.h"
260 #include <CoreGraphics/CoreGraphics.h>
261 #include <WebCore/Icon.h>
262 #include <pal/spi/cocoa/CoreTextSPI.h>
266 #include <WebCore/LocalDefaultSystemAppearance.h>
267 #include <pal/spi/cf/CFUtilitiesSPI.h>
271 #include <wtf/RefCountedLeakCounter.h>
274 #if ENABLE(DATA_DETECTION)
275 #include <WebCore/DataDetection.h>
278 #if ENABLE(VIDEO) && USE(GSTREAMER)
279 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
282 #if ENABLE(WEB_AUTHN)
283 #include "WebAuthenticatorCoordinator.h"
284 #include <WebCore/AuthenticatorCoordinator.h>
289 using namespace WebCore;
291 static const Seconds pageScrollHysteresisDuration { 300_ms };
292 static const Seconds initialLayerVolatilityTimerInterval { 20_ms };
293 static const Seconds maximumLayerVolatilityTimerInterval { 2_s };
295 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
296 #define RELEASE_LOG_ERROR_IF_ALLOWED(...) RELEASE_LOG_ERROR_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
298 class SendStopResponsivenessTimer {
300 ~SendStopResponsivenessTimer()
302 WebProcess::singleton().parentProcessConnection()->send(Messages::WebProcessProxy::StopResponsivenessTimer(), 0);
306 class DeferredPageDestructor {
308 static void createDeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
310 new DeferredPageDestructor(WTFMove(page), webPage);
314 DeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
315 : m_page(WTFMove(page))
321 void tryDestruction()
323 if (m_page->insideNestedRunLoop()) {
324 m_page->whenUnnested([this] { tryDestruction(); });
333 std::unique_ptr<Page> m_page;
334 RefPtr<WebPage> m_webPage;
337 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
339 Ref<WebPage> WebPage::create(uint64_t pageID, WebPageCreationParameters&& parameters)
341 Ref<WebPage> page = adoptRef(*new WebPage(pageID, WTFMove(parameters)));
343 if (WebProcess::singleton().injectedBundle())
344 WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
349 WebPage::WebPage(uint64_t pageID, WebPageCreationParameters&& parameters)
351 , m_viewSize(parameters.viewSize)
352 , m_alwaysShowsHorizontalScroller { parameters.alwaysShowsHorizontalScroller }
353 , m_alwaysShowsVerticalScroller { parameters.alwaysShowsVerticalScroller }
354 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
355 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
357 , m_layerHostingMode(parameters.layerHostingMode)
359 , m_viewGestureGeometryCollector(makeUniqueRef<ViewGestureGeometryCollector>(*this))
360 #elif HAVE(ACCESSIBILITY) && PLATFORM(GTK)
361 , m_accessibilityObject(nullptr)
363 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
364 #if ENABLE(CONTEXT_MENUS)
365 , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
367 , m_editorClient { std::make_unique<API::InjectedBundle::EditorClient>() }
368 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
369 , m_loaderClient(std::make_unique<API::InjectedBundle::PageLoaderClient>())
370 , m_resourceLoadClient(std::make_unique<API::InjectedBundle::ResourceLoadClient>())
371 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
372 , m_findController(makeUniqueRef<FindController>(this))
373 , m_userContentController(WebUserContentController::getOrCreate(parameters.userContentControllerID))
374 #if ENABLE(GEOLOCATION)
375 , m_geolocationPermissionRequestManager(makeUniqueRef<GeolocationPermissionRequestManager>(*this))
377 #if ENABLE(MEDIA_STREAM)
378 , m_userMediaPermissionRequestManager { std::make_unique<UserMediaPermissionRequestManager>(*this) }
380 , m_pageScrolledHysteresis([this](PAL::HysteresisState state) { if (state == PAL::HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisDuration)
381 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
382 , m_canRunModal(parameters.canRunModal)
383 #if PLATFORM(IOS_FAMILY)
384 , m_forceAlwaysUserScalable(parameters.ignoresViewportScaleLimits)
385 , m_screenSize(parameters.screenSize)
386 , m_availableScreenSize(parameters.availableScreenSize)
387 , m_overrideScreenSize(parameters.overrideScreenSize)
389 , m_layerVolatilityTimer(*this, &WebPage::layerVolatilityTimerFired)
390 , m_activityState(parameters.activityState)
391 , m_processSuppressionEnabled(true)
392 , m_userActivity("Process suppression disabled for page.")
393 , m_userActivityHysteresis([this](PAL::HysteresisState) { updateUserActivity(); })
394 , m_userInterfaceLayoutDirection(parameters.userInterfaceLayoutDirection)
395 , m_overrideContentSecurityPolicy { parameters.overrideContentSecurityPolicy }
396 , m_cpuLimit(parameters.cpuLimit)
400 m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
402 #if PLATFORM(IOS_FAMILY)
403 DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(true);
406 PageConfiguration pageConfiguration(
407 makeUniqueRef<WebEditorClient>(this),
408 WebSocketProvider::create(),
409 makeUniqueRef<WebKit::LibWebRTCProvider>(),
410 WebProcess::singleton().cacheStorageProvider(),
411 WebBackForwardListProxy::create(*this)
413 pageConfiguration.chromeClient = new WebChromeClient(*this);
414 #if ENABLE(CONTEXT_MENUS)
415 pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
417 #if ENABLE(DRAG_SUPPORT)
418 pageConfiguration.dragClient = new WebDragClient(this);
420 pageConfiguration.inspectorClient = new WebInspectorClient(this);
421 #if USE(AUTOCORRECTION_PANEL)
422 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
425 pageConfiguration.plugInClient = new WebPlugInClient(*this);
426 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
427 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
428 pageConfiguration.diagnosticLoggingClient = std::make_unique<WebDiagnosticLoggingClient>(*this);
429 pageConfiguration.performanceLoggingClient = std::make_unique<WebPerformanceLoggingClient>(*this);
431 pageConfiguration.webGLStateTracker = std::make_unique<WebGLStateTracker>([this](bool isUsingHighPerformanceWebGL) {
432 send(Messages::WebPageProxy::SetIsUsingHighPerformanceWebGL(isUsingHighPerformanceWebGL));
436 pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(*this);
439 pageConfiguration.applicationCacheStorage = &WebProcess::singleton().applicationCacheStorage();
440 pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
441 pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
442 pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
443 pageConfiguration.userContentProvider = m_userContentController.ptr();
444 pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
446 #if ENABLE(APPLE_PAY)
447 pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinator(*this);
450 #if ENABLE(WEB_AUTHN)
451 pageConfiguration.authenticatorCoordinatorClient = std::make_unique<WebAuthenticatorCoordinator>(*this);
454 #if ENABLE(APPLICATION_MANIFEST)
455 pageConfiguration.applicationManifest = parameters.applicationManifest;
458 m_page = std::make_unique<Page>(WTFMove(pageConfiguration));
459 updatePreferences(parameters.store);
461 m_drawingArea = DrawingArea::create(*this, parameters);
462 m_drawingArea->setPaintingEnabled(false);
463 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
465 #if ENABLE(ASYNC_SCROLLING)
466 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
467 if (!m_drawingArea->supportsAsyncScrolling())
468 m_useAsyncScrolling = false;
469 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
472 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
473 m_drawingArea->updatePreferences(parameters.store);
475 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
477 #if ENABLE(GEOLOCATION)
478 WebCore::provideGeolocationTo(m_page.get(), *new WebGeolocationClient(*this));
480 #if ENABLE(NOTIFICATIONS)
481 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
483 #if ENABLE(MEDIA_STREAM)
484 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
487 m_page->setControlledByAutomation(parameters.controlledByAutomation);
489 #if ENABLE(REMOTE_INSPECTOR)
490 m_page->setRemoteInspectionAllowed(parameters.allowsRemoteInspection);
491 m_page->setRemoteInspectionNameOverride(parameters.remoteInspectionNameOverride);
494 m_page->setCanStartMedia(false);
495 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
497 m_page->setGroupName(m_pageGroup->identifier());
498 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
499 m_page->setUserInterfaceLayoutDirection(m_userInterfaceLayoutDirection);
500 #if PLATFORM(IOS_FAMILY)
501 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
504 platformInitialize();
506 setUseFixedLayout(parameters.useFixedLayout);
508 setDrawsBackground(parameters.drawsBackground);
510 setUnderlayColor(parameters.underlayColor);
512 setPaginationMode(parameters.paginationMode);
513 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
514 setPageLength(parameters.pageLength);
515 setGapBetweenPages(parameters.gapBetweenPages);
516 setPaginationLineGridEnabled(parameters.paginationLineGridEnabled);
518 setUseSystemAppearance(parameters.useSystemAppearance);
519 setUseDarkAppearance(parameters.useDarkAppearance);
521 // If the page is created off-screen, its visibilityState should be prerender.
522 m_page->setActivityState(m_activityState);
524 m_page->setIsPrerender();
526 updateIsInWindow(true);
528 setViewLayoutSize(parameters.viewLayoutSize);
529 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
530 setViewportSizeForCSSViewportUnits(parameters.viewportSizeForCSSViewportUnits);
532 setScrollPinningBehavior(parameters.scrollPinningBehavior);
533 if (parameters.scrollbarOverlayStyle)
534 m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
536 m_scrollbarOverlayStyle = std::optional<ScrollbarOverlayStyle>();
538 setTopContentInset(parameters.topContentInset);
540 m_userAgent = parameters.userAgent;
542 if (!parameters.itemStates.isEmpty())
543 restoreSessionInternal(parameters.itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
545 if (parameters.sessionID.isValid())
546 setSessionID(parameters.sessionID);
548 m_drawingArea->setPaintingEnabled(true);
550 setMediaVolume(parameters.mediaVolume);
552 setMuted(parameters.muted);
554 // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
555 m_page->addLayoutMilestones(DidFirstLayout | DidFirstVisuallyNonEmptyLayout);
557 auto& webProcess = WebProcess::singleton();
558 webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
560 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
561 webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
562 webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
563 webProcess.addMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID, *this);
564 #if ENABLE(FULLSCREEN_API)
565 webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
569 webPageCounter.increment();
572 #if ENABLE(ASYNC_SCROLLING)
573 if (m_useAsyncScrolling)
574 webProcess.eventDispatcher().addScrollingTreeForPage(this);
577 for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
578 m_mimeTypesWithCustomContentProviders.add(mimeType);
581 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
582 if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
583 m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
585 m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
587 if (parameters.viewScaleFactor != 1)
588 scaleView(parameters.viewScaleFactor);
590 m_page->addLayoutMilestones(parameters.observedLayoutMilestones);
593 m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
594 setSmartInsertDeleteEnabled(parameters.smartInsertDeleteEnabled);
597 #if ENABLE(SERVICE_WORKER)
598 if (parameters.hasRegisteredServiceWorkers)
599 ServiceWorkerProvider::singleton().setMayHaveRegisteredServiceWorkers();
602 m_needsFontAttributes = parameters.needsFontAttributes;
605 if (!parameters.iceCandidateFilteringEnabled)
606 disableICECandidateFiltering();
608 if (parameters.enumeratingAllNetworkInterfacesEnabled)
609 enableEnumeratingAllNetworkInterfaces();
613 for (auto iterator : parameters.urlSchemeHandlers)
614 registerURLSchemeHandler(iterator.value, iterator.key);
616 m_userContentController->addUserContentWorlds(parameters.userContentWorlds);
617 m_userContentController->addUserScripts(WTFMove(parameters.userScripts), InjectUserScriptImmediately::No);
618 m_userContentController->addUserStyleSheets(parameters.userStyleSheets);
619 m_userContentController->addUserScriptMessageHandlers(parameters.messageHandlers);
620 #if ENABLE(CONTENT_EXTENSIONS)
621 m_userContentController->addContentRuleLists(parameters.contentRuleLists);
624 #if PLATFORM(IOS_FAMILY)
625 setViewportConfigurationViewLayoutSize(parameters.viewportConfigurationViewLayoutSize, parameters.viewportConfigurationLayoutSizeScaleFactor);
626 setMaximumUnobscuredSize(parameters.maximumUnobscuredSize);
631 void WebPage::disableICECandidateFiltering()
633 m_page->disableICECandidateFiltering();
636 void WebPage::enableICECandidateFiltering()
638 m_page->enableICECandidateFiltering();
642 void WebPage::disableEnumeratingAllNetworkInterfaces()
644 m_page->libWebRTCProvider().disableEnumeratingAllNetworkInterfaces();
647 void WebPage::enableEnumeratingAllNetworkInterfaces()
649 m_page->libWebRTCProvider().enableEnumeratingAllNetworkInterfaces();
654 void WebPage::reinitializeWebPage(WebPageCreationParameters&& parameters)
656 ASSERT(m_drawingArea);
658 if (m_shouldResetDrawingArea) {
659 // Make sure we destroy the previous drawing area before constructing the new one as DrawingArea registers / unregisters
660 // itself as an IPC::MesssageReceiver in its constructor / destructor.
661 m_drawingArea = nullptr;
662 m_shouldResetDrawingArea = false;
664 m_drawingArea = DrawingArea::create(*this, parameters);
665 m_drawingArea->setPaintingEnabled(false);
666 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
667 m_drawingArea->updatePreferences(parameters.store);
668 m_drawingArea->setPaintingEnabled(true);
671 if (m_activityState != parameters.activityState)
672 setActivityState(parameters.activityState, ActivityStateChangeAsynchronous, Vector<CallbackID>());
673 if (m_layerHostingMode != parameters.layerHostingMode)
674 setLayerHostingMode(parameters.layerHostingMode);
677 void WebPage::updateThrottleState()
679 bool isActive = m_activityState.containsAny({ ActivityState::IsLoading, ActivityState::IsAudible, ActivityState::IsCapturingMedia, ActivityState::WindowIsActive });
680 bool isVisuallyIdle = m_activityState.contains(ActivityState::IsVisuallyIdle);
681 bool pageSuppressed = m_processSuppressionEnabled && !isActive && isVisuallyIdle;
683 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
684 if (!pageSuppressed) {
685 // App nap must be manually enabled when not running the NSApplication run loop.
686 static std::once_flag onceKey;
687 std::call_once(onceKey, [] {
688 __CFRunLoopSetOptionsReason(__CFRunLoopOptionsEnableAppNap, CFSTR("Finished checkin as application - enable app nap"));
692 // The UserActivity keeps the processes runnable. So if the page should be suppressed, stop the activity.
693 // If the page should not be supressed, start it.
695 m_userActivityHysteresis.stop();
697 m_userActivityHysteresis.start();
700 void WebPage::updateUserActivity()
702 if (m_userActivityHysteresis.state() == PAL::HysteresisState::Started)
703 m_userActivity.start();
705 m_userActivity.stop();
712 auto& webProcess = WebProcess::singleton();
713 #if ENABLE(ASYNC_SCROLLING)
714 if (m_useAsyncScrolling)
715 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
720 m_sandboxExtensionTracker.invalidate();
722 for (auto* pluginView : m_pluginViews)
723 pluginView->webPageDestroyed();
725 #if !PLATFORM(IOS_FAMILY)
727 m_headerBanner->detachFromPage();
729 m_footerBanner->detachFromPage();
730 #endif // !PLATFORM(IOS_FAMILY)
732 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
734 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
735 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
736 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
737 webProcess.removeMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID);
738 #if ENABLE(FULLSCREEN_API)
739 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
743 webPageCounter.decrement();
746 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
747 if (m_playbackSessionManager)
748 m_playbackSessionManager->invalidate();
750 if (m_videoFullscreenManager)
751 m_videoFullscreenManager->invalidate();
755 IPC::Connection* WebPage::messageSenderConnection()
757 return WebProcess::singleton().parentProcessConnection();
760 uint64_t WebPage::messageSenderDestinationID()
765 #if ENABLE(CONTEXT_MENUS)
766 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>&& contextMenuClient)
768 if (!contextMenuClient) {
769 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
773 m_contextMenuClient = WTFMove(contextMenuClient);
777 void WebPage::setInjectedBundleEditorClient(std::unique_ptr<API::InjectedBundle::EditorClient>&& editorClient)
780 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
784 m_editorClient = WTFMove(editorClient);
787 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>&& formClient)
790 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
794 m_formClient = WTFMove(formClient);
797 void WebPage::setInjectedBundlePageLoaderClient(std::unique_ptr<API::InjectedBundle::PageLoaderClient>&& loaderClient)
800 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
804 m_loaderClient = WTFMove(loaderClient);
806 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
807 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
808 // for backwards compatibility.
809 if (auto milestones = m_loaderClient->layoutMilestones())
810 listenForLayoutMilestones(milestones);
813 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
815 m_policyClient.initialize(client);
818 void WebPage::setInjectedBundleResourceLoadClient(std::unique_ptr<API::InjectedBundle::ResourceLoadClient>&& client)
820 if (!m_resourceLoadClient)
821 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
823 m_resourceLoadClient = WTFMove(client);
826 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>&& uiClient)
829 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
833 m_uiClient = WTFMove(uiClient);
836 #if ENABLE(FULLSCREEN_API)
837 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
839 m_fullScreenClient.initialize(client);
843 #if ENABLE(NETSCAPE_PLUGIN_API)
844 RefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
846 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
847 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
849 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
850 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
851 unsigned pluginArea = 0;
852 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
854 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
857 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
859 uint64_t pluginProcessToken;
860 uint32_t pluginLoadPolicy;
861 String unavailabilityDescription;
863 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)))
866 PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
867 bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
869 if (isUnsupported || isBlockedPlugin || !pluginProcessToken) {
870 #if ENABLE(PDFKIT_PLUGIN)
871 String path = parameters.url.path();
872 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWithIgnoringASCIICase(".pdf") || path.endsWithIgnoringASCIICase(".ps")))))
873 return PDFPlugin::create(*frame);
878 pluginElement->setReplacement(RenderEmbeddedObject::UnsupportedPlugin, unavailabilityDescription);
882 if (isBlockedPlugin) {
883 bool isReplacementObscured = pluginElement->setReplacement(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
884 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, isReplacementObscured));
888 if (!pluginProcessToken)
891 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
892 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
894 #endif // ENABLE(NETSCAPE_PLUGIN_API)
896 #if ENABLE(WEBGL) && !PLATFORM(MAC)
897 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const URL&)
899 return WebGLAllowCreation;
902 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const URL&)
904 return WebGLAllowCreation;
908 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
910 Frame& frame = m_page->focusController().focusedOrMainFrame();
914 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
915 if (!pluginView->getSelectionString().isNull()) {
916 result.selectionIsNone = false;
917 result.selectionIsRange = true;
918 result.isInPlugin = true;
923 const VisibleSelection& selection = frame.selection().selection();
924 const Editor& editor = frame.editor();
926 result.selectionIsNone = selection.isNone();
927 result.selectionIsRange = selection.isRange();
928 result.isContentEditable = selection.isContentEditable();
929 result.isContentRichlyEditable = selection.isContentRichlyEditable();
930 result.isInPasswordField = selection.isInPasswordField();
931 result.hasComposition = editor.hasComposition();
932 result.shouldIgnoreSelectionChanges = editor.ignoreSelectionChanges();
934 if (auto* document = frame.document())
935 result.originIdentifierForPasteboard = document->originIdentifierForPasteboard();
937 bool canIncludePostLayoutData = frame.view() && !frame.view()->needsLayout();
938 if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && canIncludePostLayoutData) {
939 auto& postLayoutData = result.postLayoutData();
940 postLayoutData.canCut = editor.canCut();
941 postLayoutData.canCopy = editor.canCopy();
942 postLayoutData.canPaste = editor.canPaste();
944 if (m_needsFontAttributes)
945 postLayoutData.fontAttributes = editor.fontAttributesAtSelectionStart();
948 if (result.isContentEditable && !selection.isNone()) {
949 if (auto editingStyle = EditingStyle::styleAtSelectionStart(selection)) {
950 if (editingStyle->hasStyle(CSSPropertyFontWeight, "bold"))
951 postLayoutData.typingAttributes |= AttributeBold;
953 if (editingStyle->hasStyle(CSSPropertyFontStyle, "italic") || editingStyle->hasStyle(CSSPropertyFontStyle, "oblique"))
954 postLayoutData.typingAttributes |= AttributeItalics;
956 if (editingStyle->hasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline"))
957 postLayoutData.typingAttributes |= AttributeUnderline;
959 if (auto* styleProperties = editingStyle->style()) {
960 bool isLeftToRight = styleProperties->propertyAsValueID(CSSPropertyDirection) == CSSValueLtr;
961 switch (styleProperties->propertyAsValueID(CSSPropertyTextAlign)) {
963 case CSSValueWebkitRight:
964 postLayoutData.textAlignment = RightAlignment;
967 case CSSValueWebkitLeft:
968 postLayoutData.textAlignment = LeftAlignment;
971 case CSSValueWebkitCenter:
972 postLayoutData.textAlignment = CenterAlignment;
974 case CSSValueJustify:
975 postLayoutData.textAlignment = JustifiedAlignment;
978 postLayoutData.textAlignment = isLeftToRight ? LeftAlignment : RightAlignment;
981 postLayoutData.textAlignment = isLeftToRight ? RightAlignment : LeftAlignment;
986 if (auto textColor = styleProperties->propertyAsColor(CSSPropertyColor))
987 postLayoutData.textColor = *textColor;
991 if (auto* enclosingListElement = enclosingList(selection.start().containerNode())) {
992 if (is<HTMLUListElement>(*enclosingListElement))
993 postLayoutData.enclosingListType = UnorderedList;
994 else if (is<HTMLOListElement>(*enclosingListElement))
995 postLayoutData.enclosingListType = OrderedList;
997 ASSERT_NOT_REACHED();
1003 platformEditorState(frame, result, shouldIncludePostLayoutData);
1005 m_lastEditorStateWasContentEditable = result.isContentEditable ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1010 void WebPage::changeFontAttributes(WebCore::FontAttributeChanges&& changes)
1012 auto& frame = m_page->focusController().focusedOrMainFrame();
1013 if (frame.selection().selection().isContentEditable())
1014 frame.editor().applyStyleToSelection(changes.createEditingStyle(), changes.editAction(), Editor::ColorFilterMode::InvertColor);
1017 void WebPage::changeFont(WebCore::FontChanges&& changes)
1019 auto& frame = m_page->focusController().focusedOrMainFrame();
1020 if (frame.selection().selection().isContentEditable())
1021 frame.editor().applyStyleToSelection(changes.createEditingStyle(), EditAction::SetFont, Editor::ColorFilterMode::InvertColor);
1024 void WebPage::executeEditCommandWithCallback(const String& commandName, const String& argument, CallbackID callbackID)
1026 executeEditCommand(commandName, argument);
1027 send(Messages::WebPageProxy::VoidCallback(callbackID));
1030 void WebPage::updateEditorStateAfterLayoutIfEditabilityChanged()
1032 // FIXME: We should update EditorStateIsContentEditable to track whether the state is richly
1033 // editable or plainttext-only.
1034 if (m_lastEditorStateWasContentEditable == EditorStateIsContentEditable::Unset)
1037 Frame& frame = m_page->focusController().focusedOrMainFrame();
1038 EditorStateIsContentEditable editorStateIsContentEditable = frame.selection().selection().isContentEditable() ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1039 if (m_lastEditorStateWasContentEditable != editorStateIsContentEditable)
1040 sendPartialEditorStateAndSchedulePostLayoutUpdate();
1043 String WebPage::renderTreeExternalRepresentation() const
1045 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
1048 String WebPage::renderTreeExternalRepresentationForPrinting() const
1050 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
1053 uint64_t WebPage::renderTreeSize() const
1057 return m_page->renderTreeSize();
1060 void WebPage::setTracksRepaints(bool trackRepaints)
1062 if (FrameView* view = mainFrameView())
1063 view->setTracksRepaints(trackRepaints);
1066 bool WebPage::isTrackingRepaints() const
1068 if (FrameView* view = mainFrameView())
1069 return view->isTrackingRepaints();
1074 void WebPage::resetTrackedRepaints()
1076 if (FrameView* view = mainFrameView())
1077 view->resetTrackedRepaints();
1080 Ref<API::Array> WebPage::trackedRepaintRects()
1082 FrameView* view = mainFrameView();
1084 return API::Array::create();
1086 Vector<RefPtr<API::Object>> repaintRects;
1087 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
1089 for (const auto& repaintRect : view->trackedRepaintRects())
1090 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
1092 return API::Array::create(WTFMove(repaintRects));
1095 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
1097 if (!is<PluginDocument>(frame.document()))
1100 auto& pluginDocument = downcast<PluginDocument>(*frame.document());
1101 if (pluginDocument.focusedElement() != pluginDocument.pluginElement())
1104 return pluginViewForFrame(&frame);
1107 PluginView* WebPage::pluginViewForFrame(Frame* frame)
1109 if (!frame || !is<PluginDocument>(frame->document()))
1112 auto& document = downcast<PluginDocument>(*frame->document());
1113 return static_cast<PluginView*>(document.pluginWidget());
1116 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
1118 Frame& frame = m_page->focusController().focusedOrMainFrame();
1120 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
1121 pluginView->handleEditingCommand(commandName, argument);
1125 frame.editor().command(commandName).execute(argument);
1128 void WebPage::setEditable(bool editable)
1130 m_page->setEditable(editable);
1131 m_page->setTabKeyCyclesThroughElements(!editable);
1132 Frame& frame = m_page->focusController().focusedOrMainFrame();
1134 frame.editor().applyEditingStyleToBodyElement();
1135 // If the page is made editable and the selection is empty, set it to something.
1136 if (frame.selection().isNone())
1137 frame.selection().setSelectionFromNone();
1141 bool WebPage::isEditingCommandEnabled(const String& commandName)
1143 Frame& frame = m_page->focusController().focusedOrMainFrame();
1145 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1146 return pluginView->isEditingCommandEnabled(commandName);
1148 Editor::Command command = frame.editor().command(commandName);
1149 return command.isSupported() && command.isEnabled();
1152 void WebPage::clearMainFrameName()
1154 if (Frame* frame = mainFrame())
1155 frame->tree().clearName();
1158 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
1160 m_drawingArea->setRootCompositingLayer(layer);
1163 void WebPage::exitAcceleratedCompositingMode()
1165 m_drawingArea->setRootCompositingLayer(0);
1168 void WebPage::close()
1173 WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::RemoveStorageAccessForAllFramesOnPage(sessionID(), m_pageID), 0);
1177 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1178 if (!mainWebFrame()->url().isEmpty())
1179 reportUsedFeatures();
1181 if (WebProcess::singleton().injectedBundle())
1182 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1185 m_inspector->disconnectFromPage();
1186 m_inspector = nullptr;
1189 m_page->inspectorController().disconnectAllFrontends();
1191 #if ENABLE(MEDIA_STREAM)
1192 m_userMediaPermissionRequestManager = nullptr;
1195 #if ENABLE(FULLSCREEN_API)
1196 m_fullScreenManager = nullptr;
1199 if (m_activePopupMenu) {
1200 m_activePopupMenu->disconnectFromPage();
1201 m_activePopupMenu = nullptr;
1204 if (m_activeOpenPanelResultListener) {
1205 m_activeOpenPanelResultListener->disconnectFromPage();
1206 m_activeOpenPanelResultListener = nullptr;
1209 #if ENABLE(INPUT_TYPE_COLOR)
1210 if (m_activeColorChooser) {
1211 m_activeColorChooser->disconnectFromPage();
1212 m_activeColorChooser = nullptr;
1217 if (m_printOperation) {
1218 m_printOperation->disconnectFromPage();
1219 m_printOperation = nullptr;
1223 #if ENABLE(VIDEO) && USE(GSTREAMER)
1224 if (m_installMediaPluginsCallback) {
1225 m_installMediaPluginsCallback->invalidate();
1226 m_installMediaPluginsCallback = nullptr;
1230 m_sandboxExtensionTracker.invalidate();
1232 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1233 m_determinePrimarySnapshottedPlugInTimer.stop();
1236 #if ENABLE(CONTEXT_MENUS)
1237 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1239 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
1240 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1241 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
1242 m_policyClient.initialize(0);
1243 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
1244 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1245 #if ENABLE(FULLSCREEN_API)
1246 m_fullScreenClient.initialize(0);
1249 m_printContext = nullptr;
1250 m_mainFrame->coreFrame()->loader().detachFromParent();
1251 m_drawingArea = nullptr;
1253 DeferredPageDestructor::createDeferredPageDestructor(WTFMove(m_page), this);
1255 bool isRunningModal = m_isRunningModal;
1256 m_isRunningModal = false;
1258 // The WebPage can be destroyed by this call.
1259 WebProcess::singleton().removeWebPage(m_pageID);
1261 WebProcess::singleton().updateActivePages();
1264 RunLoop::main().stop();
1267 void WebPage::tryClose()
1269 SendStopResponsivenessTimer stopper;
1271 if (!corePage()->userInputBridge().tryClosePage())
1274 send(Messages::WebPageProxy::ClosePage(true));
1277 void WebPage::sendClose()
1279 send(Messages::WebPageProxy::ClosePage(false));
1282 void WebPage::loadURLInFrame(WebCore::URL&& url, uint64_t frameID)
1284 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1288 frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(url), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1291 #if !PLATFORM(COCOA)
1292 void WebPage::platformDidReceiveLoadParameters(const LoadParameters& loadParameters)
1297 void WebPage::loadRequest(LoadParameters&& loadParameters)
1299 SendStopResponsivenessTimer stopper;
1301 m_pendingNavigationID = loadParameters.navigationID;
1303 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), WTFMove(loadParameters.sandboxExtensionHandle));
1305 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1306 // to all the client to set up any needed state.
1307 m_loaderClient->willLoadURLRequest(*this, loadParameters.request, WebProcess::singleton().transformHandlesToObjects(loadParameters.userData.object()).get());
1309 platformDidReceiveLoadParameters(loadParameters);
1311 // Initate the load in WebCore.
1312 FrameLoadRequest frameLoadRequest { *m_mainFrame->coreFrame(), loadParameters.request, ShouldOpenExternalURLsPolicy::ShouldNotAllow };
1313 ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(loadParameters.shouldOpenExternalURLsPolicy);
1314 frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1315 frameLoadRequest.setShouldTreatAsContinuingLoad(loadParameters.shouldTreatAsContinuingLoad);
1316 frameLoadRequest.setLockHistory(loadParameters.lockHistory);
1317 frameLoadRequest.setlockBackForwardList(loadParameters.lockBackForwardList);
1318 frameLoadRequest.setClientRedirectSourceForHistory(loadParameters.clientRedirectSourceForHistory);
1320 corePage()->userInputBridge().loadRequest(WTFMove(frameLoadRequest));
1322 ASSERT(!m_pendingNavigationID);
1325 void WebPage::loadDataImpl(uint64_t navigationID, Ref<SharedBuffer>&& sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1327 SendStopResponsivenessTimer stopper;
1329 m_pendingNavigationID = navigationID;
1331 ResourceRequest request(baseURL);
1332 ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1333 SubstituteData substituteData(WTFMove(sharedBuffer), unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1335 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1336 // to all the client to set up any needed state.
1337 m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1339 // Initate the load in WebCore.
1340 m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(*m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData));
1343 void WebPage::loadData(LoadParameters&& loadParameters)
1345 platformDidReceiveLoadParameters(loadParameters);
1347 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1348 URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1349 loadDataImpl(loadParameters.navigationID, WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, URL(), loadParameters.userData);
1352 void WebPage::loadAlternateHTML(const LoadParameters& loadParameters)
1354 platformDidReceiveLoadParameters(loadParameters);
1356 URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1357 URL unreachableURL = loadParameters.unreachableURLString.isEmpty() ? URL() : URL(URL(), loadParameters.unreachableURLString);
1358 URL provisionalLoadErrorURL = loadParameters.provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), loadParameters.provisionalLoadErrorURLString);
1359 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1360 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1361 loadDataImpl(loadParameters.navigationID, WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, unreachableURL, loadParameters.userData);
1362 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1365 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1367 Frame* mainFrame = m_mainFrame->coreFrame();
1368 Document* mainFrameDocument = mainFrame->document();
1369 if (!mainFrameDocument)
1372 const int singleClick = 1;
1373 // FIXME: Set modifier keys.
1374 // FIXME: This should probably set IsSimulated::Yes.
1375 RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes, Event::IsComposed::Yes,
1376 MonotonicTime::now(), nullptr, singleClick, screenPoint, documentPoint, { }, { }, 0, 0, nullptr, 0, WebCore::NoTap, nullptr);
1378 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1381 void WebPage::stopLoadingFrame(uint64_t frameID)
1383 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1387 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1390 void WebPage::stopLoading()
1392 SendStopResponsivenessTimer stopper;
1394 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1397 bool WebPage::defersLoading() const
1399 return m_page->defersLoading();
1402 void WebPage::setDefersLoading(bool defersLoading)
1404 m_page->setDefersLoading(defersLoading);
1407 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, SandboxExtension::Handle&& sandboxExtensionHandle)
1409 SendStopResponsivenessTimer stopper;
1411 ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1412 m_pendingNavigationID = navigationID;
1414 m_sandboxExtensionTracker.beginReload(m_mainFrame.get(), WTFMove(sandboxExtensionHandle));
1415 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1417 if (m_pendingNavigationID) {
1418 // This can happen if FrameLoader::reload() returns early because the document URL is empty.
1419 // The reload does nothing so we need to reset the pending navigation. See webkit.org/b/153210.
1420 m_pendingNavigationID = 0;
1424 void WebPage::goToBackForwardItem(uint64_t navigationID, const BackForwardItemIdentifier& backForwardItemID, FrameLoadType backForwardType, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad)
1426 SendStopResponsivenessTimer stopper;
1428 ASSERT(isBackForwardLoadType(backForwardType));
1430 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1435 LOG(Loading, "In WebProcess pid %i, WebPage %" PRIu64 " is navigating to back/forward URL %s", getCurrentProcessID(), m_pageID, item->url().string().utf8().data());
1437 ASSERT(!m_pendingNavigationID);
1438 m_pendingNavigationID = navigationID;
1440 m_page->goToItem(*item, backForwardType, shouldTreatAsContinuingLoad);
1443 void WebPage::tryRestoreScrollPosition()
1445 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1448 void WebPage::layoutIfNeeded()
1450 if (m_mainFrame->coreFrame()->view())
1451 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1454 WebPage* WebPage::fromCorePage(Page* page)
1456 return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1459 void WebPage::setSize(const WebCore::IntSize& viewSize)
1461 if (m_viewSize == viewSize)
1464 m_viewSize = viewSize;
1465 FrameView* view = m_page->mainFrame().view();
1466 view->resize(viewSize);
1467 m_drawingArea->setNeedsDisplay();
1469 #if USE(COORDINATED_GRAPHICS)
1470 if (view->useFixedLayout())
1471 sendViewportAttributesChanged(m_page->viewportArguments());
1475 #if USE(COORDINATED_GRAPHICS)
1476 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1478 FrameView* view = m_page->mainFrame().view();
1479 ASSERT(view && view->useFixedLayout());
1481 // Viewport properties have no impact on zero sized fixed viewports.
1482 if (m_viewSize.isEmpty())
1485 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1486 Settings& settings = m_page->settings();
1488 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1490 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1491 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1492 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1494 ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1496 // If no layout was done yet set contentFixedOrigin to (0,0).
1497 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1499 // Put the width and height to the viewport width and height. In css units however.
1500 // Use FloatSize to avoid truncated values during scale.
1501 FloatSize contentFixedSize = m_viewSize;
1503 #if ENABLE(CSS_DEVICE_ADAPTATION)
1504 // CSS viewport descriptors might be applied to already affected viewport size
1505 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1506 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1509 contentFixedSize.scale(1 / attr.initialScale);
1510 view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1512 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1514 // This also takes care of the relayout.
1515 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1517 #if USE(COORDINATED_GRAPHICS_THREADED)
1518 m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1520 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1525 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1527 FrameView* frameView = m_page->mainFrame().view();
1529 ScrollPosition scrollPosition = frameView->scrollPosition();
1530 ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1532 // If the current scroll position in a direction is the max scroll position
1533 // we don't want to scroll at all.
1534 IntSize newScrollOffset;
1535 if (scrollPosition.x() < maximumScrollPosition.x())
1536 newScrollOffset.setWidth(scrollOffset.width());
1537 if (scrollPosition.y() < maximumScrollPosition.y())
1538 newScrollOffset.setHeight(scrollOffset.height());
1540 if (newScrollOffset.isZero())
1543 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1546 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1549 auto* document = m_mainFrame->coreFrame()->document();
1550 LocalDefaultSystemAppearance localAppearance(document ? document->useDarkAppearance() : false);
1553 GraphicsContextStateSaver stateSaver(graphicsContext);
1554 graphicsContext.clip(rect);
1556 m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1559 double WebPage::textZoomFactor() const
1561 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1562 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1563 if (pluginView->handlesPageScaleFactor())
1564 return pluginView->pageScaleFactor();
1565 return pageScaleFactor();
1568 Frame* frame = m_mainFrame->coreFrame();
1571 return frame->textZoomFactor();
1574 void WebPage::setTextZoomFactor(double zoomFactor)
1576 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1577 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1578 if (pluginView->handlesPageScaleFactor())
1579 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1581 scalePage(zoomFactor, IntPoint());
1585 Frame* frame = m_mainFrame->coreFrame();
1588 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1591 double WebPage::pageZoomFactor() const
1593 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1594 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1595 if (pluginView->handlesPageScaleFactor())
1596 return pluginView->pageScaleFactor();
1597 return pageScaleFactor();
1600 Frame* frame = m_mainFrame->coreFrame();
1603 return frame->pageZoomFactor();
1606 void WebPage::setPageZoomFactor(double zoomFactor)
1608 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1609 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1610 if (pluginView->handlesPageScaleFactor())
1611 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1613 scalePage(zoomFactor, IntPoint());
1617 Frame* frame = m_mainFrame->coreFrame();
1620 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1623 static void dumpHistoryItem(HistoryItem& item, size_t indent, bool isCurrentItem, StringBuilder& stringBuilder, const String& directoryName)
1626 stringBuilder.appendLiteral("curr-> ");
1628 for (size_t i = 0; i < indent; ++i)
1629 stringBuilder.append(' ');
1632 auto url = item.url();
1633 if (url.protocolIs("file")) {
1634 size_t start = url.string().find(directoryName);
1635 if (start == WTF::notFound)
1638 start += directoryName.length();
1639 stringBuilder.appendLiteral("(file test):");
1640 stringBuilder.append(url.string().substring(start));
1642 stringBuilder.append(url);
1644 auto& target = item.target();
1645 if (target.length()) {
1646 stringBuilder.appendLiteral(" (in frame \"");
1647 stringBuilder.append(target);
1648 stringBuilder.appendLiteral("\")");
1651 if (item.isTargetItem())
1652 stringBuilder.appendLiteral(" **nav target**");
1654 stringBuilder.append('\n');
1656 Vector<Ref<HistoryItem>> children;
1657 children.reserveInitialCapacity(item.children().size());
1658 for (auto& child : item.children())
1659 children.uncheckedAppend(child.copyRef());
1660 std::stable_sort(children.begin(), children.end(), [] (auto& a, auto& b) {
1661 return codePointCompare(a->target(), b->target()) < 0;
1663 for (auto& child : children)
1664 dumpHistoryItem(child, indent + 4, false, stringBuilder, directoryName);
1667 String WebPage::dumpHistoryForTesting(const String& directory)
1672 auto& list = m_page->backForward();
1674 StringBuilder builder;
1675 int begin = -list.backCount();
1676 if (list.itemAtIndex(begin)->url() == blankURL())
1678 for (int i = begin; i <= static_cast<int>(list.forwardCount()); ++i)
1679 dumpHistoryItem(*list.itemAtIndex(i), 8, !i, builder, directory);
1680 return builder.toString();
1683 void WebPage::clearHistory()
1688 static_cast<WebBackForwardListProxy&>(m_page->backForward().client()).clear();
1691 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1693 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1694 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1695 if (pluginView->handlesPageScaleFactor())
1696 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1698 scalePage(pageZoomFactor, IntPoint());
1702 Frame* frame = m_mainFrame->coreFrame();
1705 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1708 void WebPage::windowScreenDidChange(uint32_t displayID)
1710 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1713 void WebPage::scalePage(double scale, const IntPoint& origin)
1715 double totalScale = scale * viewScaleFactor();
1716 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1718 #if PLATFORM(IOS_FAMILY)
1719 if (willChangeScaleFactor) {
1720 if (!m_inDynamicSizeUpdate)
1721 m_dynamicSizeUpdateHistory.clear();
1722 m_scaleWasSetByUIProcess = false;
1725 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1726 if (pluginView && pluginView->handlesPageScaleFactor()) {
1727 // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1728 // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1729 if (m_page->pageScaleFactor() != 1) {
1730 m_page->setPageScaleFactor(1, origin);
1731 for (auto* pluginView : m_pluginViews)
1732 pluginView->pageScaleFactorDidChange();
1735 pluginView->setPageScaleFactor(totalScale, origin);
1739 m_page->setPageScaleFactor(totalScale, origin);
1741 // We can't early return before setPageScaleFactor because the origin might be different.
1742 if (!willChangeScaleFactor)
1745 for (auto* pluginView : m_pluginViews)
1746 pluginView->pageScaleFactorDidChange();
1748 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1749 m_drawingArea->deviceOrPageScaleFactorChanged();
1752 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1755 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1757 double totalScale = scale * viewScaleFactor();
1758 if (totalScale == totalScaleFactor())
1761 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1762 double scaleRatio = scale / pageScaleFactor();
1763 scrollPositionAtNewScale.scale(scaleRatio);
1764 scalePage(scale, scrollPositionAtNewScale);
1767 double WebPage::totalScaleFactor() const
1769 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1770 if (pluginView && pluginView->handlesPageScaleFactor())
1771 return pluginView->pageScaleFactor();
1773 return m_page->pageScaleFactor();
1776 double WebPage::pageScaleFactor() const
1778 return totalScaleFactor() / viewScaleFactor();
1781 double WebPage::viewScaleFactor() const
1783 return m_page->viewScaleFactor();
1786 void WebPage::scaleView(double scale)
1788 if (viewScaleFactor() == scale)
1791 float pageScale = pageScaleFactor();
1793 IntPoint scrollPositionAtNewScale;
1794 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1795 double scaleRatio = scale / viewScaleFactor();
1796 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1797 scrollPositionAtNewScale.scale(scaleRatio);
1800 m_page->setViewScaleFactor(scale);
1801 scalePage(pageScale, scrollPositionAtNewScale);
1804 void WebPage::setDeviceScaleFactor(float scaleFactor)
1806 if (scaleFactor == m_page->deviceScaleFactor())
1809 m_page->setDeviceScaleFactor(scaleFactor);
1811 // Tell all our plug-in views that the device scale factor changed.
1813 for (auto* pluginView : m_pluginViews)
1814 pluginView->setDeviceScaleFactor(scaleFactor);
1816 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1819 if (findController().isShowingOverlay()) {
1820 // We must have updated layout to get the selection rects right.
1822 findController().deviceScaleFactorDidChange();
1825 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1826 m_drawingArea->deviceOrPageScaleFactorChanged();
1830 float WebPage::deviceScaleFactor() const
1832 return m_page->deviceScaleFactor();
1835 void WebPage::accessibilitySettingsDidChange()
1837 m_page->accessibilitySettingsDidChange();
1840 #if ENABLE(ACCESSIBILITY_EVENTS)
1841 void WebPage::updateAccessibilityEventsEnabled(bool enabled)
1843 m_page->settings().setAccessibilityEventsEnabled(enabled);
1847 void WebPage::setUseFixedLayout(bool fixed)
1849 // Do not overwrite current settings if initially setting it to false.
1850 if (m_useFixedLayout == fixed)
1852 m_useFixedLayout = fixed;
1854 #if !PLATFORM(IOS_FAMILY)
1855 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1858 FrameView* view = mainFrameView();
1862 view->setUseFixedLayout(fixed);
1864 setFixedLayoutSize(IntSize());
1866 send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1869 bool WebPage::setFixedLayoutSize(const IntSize& size)
1871 FrameView* view = mainFrameView();
1872 if (!view || view->fixedLayoutSize() == size)
1875 LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " setFixedLayoutSize " << size);
1876 view->setFixedLayoutSize(size);
1878 send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1882 IntSize WebPage::fixedLayoutSize() const
1884 FrameView* view = mainFrameView();
1887 return view->fixedLayoutSize();
1890 void WebPage::disabledAdaptationsDidChange(const OptionSet<DisabledAdaptations>& disabledAdaptations)
1892 #if PLATFORM(IOS_FAMILY)
1893 if (m_viewportConfiguration.setDisabledAdaptations(disabledAdaptations))
1894 viewportConfigurationChanged();
1896 UNUSED_PARAM(disabledAdaptations);
1900 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
1902 #if PLATFORM(IOS_FAMILY)
1903 if (!m_page->settings().shouldIgnoreMetaViewport() && m_viewportConfiguration.setViewportArguments(viewportArguments))
1904 viewportConfigurationChanged();
1907 #if USE(COORDINATED_GRAPHICS)
1908 FrameView* view = m_page->mainFrame().view();
1909 if (view && view->useFixedLayout())
1910 sendViewportAttributesChanged(viewportArguments);
1911 #if USE(COORDINATED_GRAPHICS_THREADED)
1913 m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
1917 #if !PLATFORM(IOS_FAMILY) && !USE(COORDINATED_GRAPHICS)
1918 UNUSED_PARAM(viewportArguments);
1922 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1926 m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1929 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1931 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1934 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1936 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1939 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1941 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1944 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1946 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1947 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1950 void WebPage::setPaginationMode(uint32_t mode)
1952 Pagination pagination = m_page->pagination();
1953 pagination.mode = static_cast<Pagination::Mode>(mode);
1954 m_page->setPagination(pagination);
1957 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1959 Pagination pagination = m_page->pagination();
1960 pagination.behavesLikeColumns = behavesLikeColumns;
1961 m_page->setPagination(pagination);
1964 void WebPage::setPageLength(double pageLength)
1966 Pagination pagination = m_page->pagination();
1967 pagination.pageLength = pageLength;
1968 m_page->setPagination(pagination);
1971 void WebPage::setGapBetweenPages(double gap)
1973 Pagination pagination = m_page->pagination();
1974 pagination.gap = gap;
1975 m_page->setPagination(pagination);
1978 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
1980 m_page->setPaginationLineGridEnabled(lineGridEnabled);
1983 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1985 auto& webProcess = WebProcess::singleton();
1986 InjectedBundle* injectedBundle = webProcess.injectedBundle();
1987 if (!injectedBundle)
1990 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1993 #if !PLATFORM(IOS_FAMILY)
1995 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
1998 m_headerBanner->detachFromPage();
2000 m_headerBanner = pageBanner;
2003 m_headerBanner->addToPage(PageBanner::Header, this);
2006 PageBanner* WebPage::headerPageBanner()
2008 return m_headerBanner.get();
2011 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
2014 m_footerBanner->detachFromPage();
2016 m_footerBanner = pageBanner;
2019 m_footerBanner->addToPage(PageBanner::Footer, this);
2022 PageBanner* WebPage::footerPageBanner()
2024 return m_footerBanner.get();
2027 void WebPage::hidePageBanners()
2030 m_headerBanner->hide();
2032 m_footerBanner->hide();
2035 void WebPage::showPageBanners()
2038 m_headerBanner->showIfHidden();
2040 m_footerBanner->showIfHidden();
2043 void WebPage::setHeaderBannerHeightForTesting(int height)
2045 #if ENABLE(RUBBER_BANDING)
2046 corePage()->addHeaderWithHeight(height);
2050 void WebPage::setFooterBannerHeightForTesting(int height)
2052 #if ENABLE(RUBBER_BANDING)
2053 corePage()->addFooterWithHeight(height);
2057 #endif // !PLATFORM(IOS_FAMILY)
2059 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
2061 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
2062 snapshotOptions |= SnapshotOptionsShareable;
2064 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
2066 ShareableBitmap::Handle handle;
2068 image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
2070 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
2073 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
2075 IntRect snapshotRect = rect;
2076 IntSize bitmapSize = snapshotRect.size();
2077 if (options & SnapshotOptionsPrinting) {
2078 ASSERT(additionalScaleFactor == 1);
2079 Frame* coreFrame = m_mainFrame->coreFrame();
2082 bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
2084 double scaleFactor = additionalScaleFactor;
2085 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
2086 scaleFactor *= corePage()->deviceScaleFactor();
2087 bitmapSize.scale(scaleFactor);
2090 return snapshotAtSize(rect, bitmapSize, options);
2093 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
2095 IntRect snapshotRect = rect;
2096 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
2097 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
2098 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
2100 if (options & SnapshotOptionsPrinting) {
2101 PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
2105 Color documentBackgroundColor = frameView.documentBackgroundColor();
2106 Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
2107 graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
2109 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2110 double deviceScaleFactor = frame.page()->deviceScaleFactor();
2111 graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
2112 scaleFactor /= deviceScaleFactor;
2115 graphicsContext.scale(scaleFactor);
2116 graphicsContext.translate(-snapshotRect.location());
2118 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
2119 if (options & SnapshotOptionsExcludeSelectionHighlighting)
2120 shouldPaintSelection = FrameView::ExcludeSelection;
2122 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
2123 if (options & SnapshotOptionsInViewCoordinates)
2124 coordinateSpace = FrameView::ViewCoordinates;
2126 frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
2128 if (options & SnapshotOptionsPaintSelectionRectangle) {
2129 FloatRect selectionRectangle = frame.selection().selectionBounds();
2130 graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
2131 graphicsContext.strokeRect(selectionRectangle, 1);
2135 static ShareableBitmap::Configuration snapshotOptionsToBitmapConfiguration(SnapshotOptions options, WebPage& page)
2137 ShareableBitmap::Configuration configuration;
2139 if (options & SnapshotOptionsUseScreenColorSpace)
2140 configuration.colorSpace.cgColorSpace = screenColorSpace(page.corePage()->mainFrame().view());
2142 return configuration;
2145 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2147 Frame* coreFrame = m_mainFrame->coreFrame();
2151 FrameView* frameView = coreFrame->view();
2155 auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2158 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2160 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2166 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2168 Frame* coreFrame = m_mainFrame->coreFrame();
2172 FrameView* frameView = coreFrame->view();
2176 auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2179 auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2180 auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2181 auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2183 CGPDFContextBeginPage(pdfContext.get(), nullptr);
2185 GraphicsContext graphicsContext { pdfContext.get() };
2186 graphicsContext.scale({ 1, -1 });
2187 graphicsContext.translate(0, -bitmapSize.height());
2188 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2190 CGPDFContextEndPage(pdfContext.get());
2191 CGPDFContextClose(pdfContext.get());
2194 return WTFMove(data);
2198 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2200 Frame* coreFrame = m_mainFrame->coreFrame();
2204 FrameView* frameView = coreFrame->view();
2208 if (!node.renderer())
2211 LayoutRect topLevelRect;
2212 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2213 if (snapshotRect.isEmpty())
2216 double scaleFactor = 1;
2217 IntSize snapshotSize = snapshotRect.size();
2218 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2219 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2220 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2221 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2224 auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2227 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2229 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2230 double deviceScaleFactor = corePage()->deviceScaleFactor();
2231 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2232 scaleFactor /= deviceScaleFactor;
2235 graphicsContext->scale(scaleFactor);
2236 graphicsContext->translate(-snapshotRect.location());
2238 Color savedBackgroundColor = frameView->baseBackgroundColor();
2239 frameView->setBaseBackgroundColor(Color::transparent);
2240 frameView->setNodeToDraw(&node);
2242 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2244 frameView->setBaseBackgroundColor(savedBackgroundColor);
2245 frameView->setNodeToDraw(nullptr);
2250 void WebPage::pageDidScroll()
2252 #if PLATFORM(IOS_FAMILY)
2253 if (!m_inDynamicSizeUpdate)
2254 m_dynamicSizeUpdateHistory.clear();
2256 m_uiClient->pageDidScroll(this);
2258 m_pageScrolledHysteresis.impulse();
2260 send(Messages::WebPageProxy::PageDidScroll());
2263 void WebPage::pageStoppedScrolling()
2265 // Maintain the current history item's scroll position up-to-date.
2266 if (Frame* frame = m_mainFrame->coreFrame())
2267 frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2270 #if ENABLE(CONTEXT_MENUS)
2271 WebContextMenu* WebPage::contextMenu()
2274 m_contextMenu = WebContextMenu::create(this);
2275 return m_contextMenu.get();
2278 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2280 corePage()->contextMenuController().clearContextMenu();
2282 // Simulate a mouse click to generate the correct menu.
2283 PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2284 corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2285 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2286 auto* menu = handled ? contextMenu() : nullptr;
2287 PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2288 corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2296 static const WebEvent* g_currentEvent = 0;
2298 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2299 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2300 // platform events passed to the event handler code.
2301 const WebEvent* WebPage::currentEvent()
2303 return g_currentEvent;
2306 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
2308 auto* drawingArea = this->drawingArea();
2312 drawingArea->setLayerTreeStateIsFrozen(frozen || m_isSuspended);
2315 void WebPage::callVolatilityCompletionHandlers(bool succeeded)
2317 auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2318 for (auto& completionHandler : completionHandlers)
2319 completionHandler(succeeded);
2322 void WebPage::layerVolatilityTimerFired()
2324 Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2325 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2326 if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2327 m_layerVolatilityTimer.stop();
2329 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Succeeded in marking layers as volatile", this);
2331 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Failed to mark layers as volatile within %gms", this, maximumLayerVolatilityTimerInterval.milliseconds());
2332 callVolatilityCompletionHandlers(didSucceed);
2336 RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.milliseconds());
2337 m_layerVolatilityTimer.startRepeating(newInterval);
2340 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2342 return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2345 void WebPage::markLayersVolatile(WTF::Function<void (bool)>&& completionHandler)
2347 RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2349 if (m_layerVolatilityTimer.isActive())
2350 m_layerVolatilityTimer.stop();
2352 if (completionHandler)
2353 m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2355 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2356 if (didSucceed || m_isSuspendedUnderLock) {
2358 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2360 // 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.
2361 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2363 callVolatilityCompletionHandlers(didSucceed);
2367 RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.milliseconds());
2368 m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2371 void WebPage::cancelMarkLayersVolatile()
2373 RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2374 m_layerVolatilityTimer.stop();
2375 m_markLayersAsVolatileCompletionHandlers.clear();
2378 class CurrentEvent {
2380 explicit CurrentEvent(const WebEvent& event)
2381 : m_previousCurrentEvent(g_currentEvent)
2383 g_currentEvent = &event;
2388 g_currentEvent = m_previousCurrentEvent;
2392 const WebEvent* m_previousCurrentEvent;
2395 #if ENABLE(CONTEXT_MENUS)
2396 static bool isContextClick(const PlatformMouseEvent& event)
2399 return WebEventFactory::shouldBeHandledAsContextClick(event);
2401 return event.button() == WebCore::RightButton;
2405 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2407 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2408 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2410 Frame* frame = &page->corePage()->mainFrame();
2411 if (result.innerNonSharedNode())
2412 frame = result.innerNonSharedNode()->document().frame();
2414 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2416 page->contextMenu()->show();
2421 void WebPage::contextMenuForKeyEvent()
2423 corePage()->contextMenuController().clearContextMenu();
2425 Frame& frame = m_page->focusController().focusedOrMainFrame();
2426 bool handled = frame.eventHandler().sendContextMenuEventForKey();
2428 contextMenu()->show();
2432 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2434 Frame& frame = page->corePage()->mainFrame();
2438 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2440 switch (platformMouseEvent.type()) {
2441 case PlatformEvent::MousePressed: {
2442 #if ENABLE(CONTEXT_MENUS)
2443 if (isContextClick(platformMouseEvent))
2444 page->corePage()->contextMenuController().clearContextMenu();
2447 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2448 #if ENABLE(CONTEXT_MENUS)
2449 if (isContextClick(platformMouseEvent))
2450 handled = handleContextMenuEvent(platformMouseEvent, page);
2454 case PlatformEvent::MouseReleased:
2455 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2457 case PlatformEvent::MouseMoved:
2459 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2460 // button is currently pressed. It is possible that neither of those things will be true since on
2461 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2462 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2463 // efficient scrollbars-only version of the event.
2464 if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2465 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2467 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2469 case PlatformEvent::MouseForceChanged:
2470 case PlatformEvent::MouseForceDown:
2471 case PlatformEvent::MouseForceUp:
2472 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2475 ASSERT_NOT_REACHED();
2480 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2482 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2484 m_userActivityHysteresis.impulse();
2486 bool shouldHandleEvent = true;
2488 #if ENABLE(CONTEXT_MENUS)
2489 // Don't try to handle any pending mouse events if a context menu is showing.
2490 if (m_isShowingContextMenu)
2491 shouldHandleEvent = false;
2493 #if ENABLE(DRAG_SUPPORT)
2494 if (m_isStartingDrag)
2495 shouldHandleEvent = false;
2498 if (!shouldHandleEvent) {
2499 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2503 bool handled = false;
2505 #if !PLATFORM(IOS_FAMILY)
2506 if (!handled && m_headerBanner)
2507 handled = m_headerBanner->mouseEvent(mouseEvent);
2508 if (!handled && m_footerBanner)
2509 handled = m_footerBanner->mouseEvent(mouseEvent);
2510 #endif // !PLATFORM(IOS_FAMILY)
2513 CurrentEvent currentEvent(mouseEvent);
2514 handled = handleMouseEvent(mouseEvent, this);
2517 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2520 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2522 Frame& frame = page->mainFrame();
2526 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2527 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2530 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2532 m_userActivityHysteresis.impulse();
2534 CurrentEvent currentEvent(wheelEvent);
2536 bool handled = handleWheelEvent(wheelEvent, m_page.get());
2538 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2541 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2543 if (!page->mainFrame().view())
2546 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2547 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2548 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2551 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2553 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2555 m_userActivityHysteresis.impulse();
2557 CurrentEvent currentEvent(keyboardEvent);
2559 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2560 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2562 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2564 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2567 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2569 bool isEnabled = false;
2571 Frame& frame = m_page->focusController().focusedOrMainFrame();
2572 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2573 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2575 Editor::Command command = frame.editor().command(commandName);
2576 state = command.state();
2577 isEnabled = command.isSupported() && command.isEnabled();
2580 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2583 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2585 executeEditingCommand(commandName, argument);
2588 void WebPage::setNeedsFontAttributes(bool needsFontAttributes)
2590 if (m_needsFontAttributes == needsFontAttributes)
2593 m_needsFontAttributes = needsFontAttributes;
2595 if (m_needsFontAttributes)
2596 sendPartialEditorStateAndSchedulePostLayoutUpdate();
2599 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest, WebBackForwardListProxy::OverwriteExistingItem overwrite)
2601 for (const auto& itemState : itemStates) {
2602 auto historyItem = toHistoryItem(itemState);
2603 historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2604 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, overwrite);
2608 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2610 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes, WebBackForwardListProxy::OverwriteExistingItem::No);
2613 void WebPage::updateBackForwardListForReattach(const Vector<WebKit::BackForwardListItemState>& itemStates)
2615 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2618 void WebPage::setCurrentHistoryItemForReattach(WebKit::BackForwardListItemState&& itemState)
2620 auto historyItem = toHistoryItem(itemState);
2621 auto& historyItemRef = historyItem.get();
2622 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2623 corePage()->mainFrame().loader().history().setCurrentItem(historyItemRef);
2626 void WebPage::requestFontAttributesAtSelectionStart(CallbackID callbackID)
2628 auto attributes = m_page->focusController().focusedOrMainFrame().editor().fontAttributesAtSelectionStart();
2629 send(Messages::WebPageProxy::FontAttributesCallback(attributes, callbackID));
2632 #if ENABLE(TOUCH_EVENTS)
2633 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2635 if (!page->mainFrame().view())
2638 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2642 #if ENABLE(IOS_TOUCH_EVENTS)
2643 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2645 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2647 m_lastInteractionLocation = touchEvent.position();
2648 CurrentEvent currentEvent(touchEvent);
2649 handled = handleTouchEvent(touchEvent, m_page.get());
2650 updatePotentialTapSecurityOrigin(touchEvent, handled);
2653 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2655 EventDispatcher::TouchEventQueue queuedEvents;
2656 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2657 dispatchAsynchronousTouchEvents(queuedEvents);
2659 dispatchTouchEvent(touchEvent, handled);
2662 void WebPage::updatePotentialTapSecurityOrigin(const WebTouchEvent& touchEvent, bool wasHandled)
2667 if (!touchEvent.isPotentialTap())
2670 if (touchEvent.type() != WebEvent::TouchStart)
2673 auto& mainFrame = m_page->mainFrame();
2674 auto document = mainFrame.document();
2678 if (!document->handlingTouchEvent())
2681 Frame* touchEventTargetFrame = &mainFrame;
2682 while (auto subframe = touchEventTargetFrame->eventHandler().touchEventTargetSubframe())
2683 touchEventTargetFrame = subframe;
2685 auto& touches = touchEventTargetFrame->eventHandler().touches();
2686 if (touches.isEmpty())
2689 ASSERT(touches.size() == 1);
2691 if (auto targetDocument = touchEventTargetFrame->document())
2692 m_potentialTapSecurityOrigin = &targetDocument->securityOrigin();
2694 #elif ENABLE(TOUCH_EVENTS)
2695 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2697 CurrentEvent currentEvent(touchEvent);
2699 bool handled = handleTouchEvent(touchEvent, m_page.get());
2701 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2705 #if ENABLE(MAC_GESTURE_EVENTS)
2706 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2708 if (!page->mainFrame().view())
2711 return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2714 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2716 CurrentEvent currentEvent(gestureEvent);
2717 bool handled = handleGestureEvent(gestureEvent, m_page.get());
2718 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2722 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2724 return page->userInputBridge().scrollRecursively(direction, granularity);
2727 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2729 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2732 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2734 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2737 void WebPage::centerSelectionInVisibleArea()
2739 Frame& frame = m_page->focusController().focusedOrMainFrame();
2740 frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2741 findController().showFindIndicatorInSelection();
2744 bool WebPage::isControlledByAutomation() const
2746 return m_page->isControlledByAutomation();
2749 void WebPage::setControlledByAutomation(bool controlled)
2751 m_page->setControlledByAutomation(controlled);
2754 void WebPage::insertNewlineInQuotedContent()
2756 Frame& frame = m_page->focusController().focusedOrMainFrame();
2757 if (frame.selection().isNone())
2759 frame.editor().insertParagraphSeparatorInQuotedContent();
2762 #if ENABLE(REMOTE_INSPECTOR)
2763 void WebPage::setAllowsRemoteInspection(bool allow)
2765 m_page->setRemoteInspectionAllowed(allow);
2768 void WebPage::setRemoteInspectionNameOverride(const String& name)
2770 m_page->setRemoteInspectionNameOverride(name);
2774 void WebPage::setDrawsBackground(bool drawsBackground)
2776 if (m_drawsBackground == drawsBackground)
2779 m_drawsBackground = drawsBackground;
2781 if (FrameView* frameView = mainFrameView()) {
2782 Color backgroundColor = drawsBackground ? Color::white : Color::transparent;
2783 bool isTransparent = !drawsBackground;
2784 frameView->updateBackgroundRecursively(backgroundColor, isTransparent);
2787 m_drawingArea->pageBackgroundTransparencyChanged();
2788 m_drawingArea->setNeedsDisplay();
2792 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
2794 if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
2795 LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
2799 m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
2801 setTopContentInset(contentInset);
2803 deallocateSendRightSafely(fencePort.port());
2807 void WebPage::setTopContentInset(float contentInset)
2809 if (contentInset == m_page->topContentInset())
2812 m_page->setTopContentInset(contentInset);
2814 for (auto* pluginView : m_pluginViews)
2815 pluginView->topContentInsetDidChange();
2818 void WebPage::viewWillStartLiveResize()
2823 // FIXME: This should propagate to all ScrollableAreas.
2824 Frame& frame = m_page->focusController().focusedOrMainFrame();
2825 if (FrameView* view = frame.view())
2826 view->willStartLiveResize();
2829 void WebPage::viewWillEndLiveResize()
2834 // FIXME: This should propagate to all ScrollableAreas.
2835 Frame& frame = m_page->focusController().focusedOrMainFrame();
2836 if (FrameView* view = frame.view())
2837 view->willEndLiveResize();
2840 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
2845 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2847 Frame& frame = m_page->focusController().focusedOrMainFrame();
2848 frame.document()->setFocusedElement(0);
2850 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2851 PlatformKeyboardEvent platformEvent(platform(event));
2852 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2853 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
2855 send(Messages::WebPageProxy::VoidCallback(callbackID));
2859 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
2860 send(Messages::WebPageProxy::VoidCallback(callbackID));
2863 void WebPage::setCanStartMediaTimerFired()
2866 m_page->setCanStartMedia(true);
2869 void WebPage::updateIsInWindow(bool isInitialState)
2871 bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
2874 m_setCanStartMediaTimer.stop();
2875 m_page->setCanStartMedia(false);
2877 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2878 if (!isInitialState)
2879 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2881 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2882 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2883 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2884 if (m_mayStartMediaWhenInWindow)
2885 m_setCanStartMediaTimer.startOneShot(0_s);
2887 WebProcess::singleton().pageDidEnterWindow(m_pageID);
2894 void WebPage::visibilityDidChange()
2896 bool isVisible = m_activityState.contains(ActivityState::IsVisible);
2898 // We save the document / scroll state when backgrounding a tab so that we are able to restore it
2899 // if it gets terminated while in the background.
2900 if (auto* frame = m_mainFrame->coreFrame())
2901 frame->loader().history().saveDocumentAndScrollState();
2905 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
2907 LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
2909 auto changed = m_activityState ^ activityState;
2910 m_activityState = activityState;
2913 updateThrottleState();
2916 SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
2917 m_page->setActivityState(activityState);
2920 for (auto* pluginView : m_pluginViews)
2921 pluginView->activityStateDidChange(changed);
2923 m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
2924 WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
2926 if (changed & ActivityState::IsInWindow)
2929 if (changed & ActivityState::IsVisible)
2930 visibilityDidChange();
2933 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
2935 m_layerHostingMode = layerHostingMode;
2937 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2939 for (auto* pluginView : m_pluginViews)
2940 pluginView->setLayerHostingMode(m_layerHostingMode);
2943 void WebPage::setSessionID(PAL::SessionID sessionID)
2945 if (sessionID.isEphemeral())
2946 WebProcess::singleton().addWebsiteDataStore(WebsiteDataStoreParameters::privateSessionParameters(sessionID));
2947 m_page->setSessionID(sessionID);
2950 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, std::optional<WebsitePoliciesData>&& websitePolicies)
2952 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2955 if (policyAction == PolicyAction::Suspend) {
2956 ASSERT(frame == m_mainFrame);
2957 setIsSuspended(true);
2959 WebProcess::singleton().sendPrewarmInformation(mainWebFrame()->url());
2961 frame->didReceivePolicyDecision(listenerID, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
2964 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
2966 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2969 frame->continueWillSubmitForm(listenerID);
2972 void WebPage::didStartPageTransition()
2974 setLayerTreeStateIsFrozen(true);
2977 bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
2979 m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
2980 m_isAssistingNodeDueToUserInteraction = false;
2981 m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
2983 if (hasPreviouslyFocusedDueToUserInteraction)
2984 send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
2985 if (m_needsHiddenContentEditableQuirk) {
2986 m_needsHiddenContentEditableQuirk = false;
2987 send(Messages::WebPageProxy::SetNeedsHiddenContentEditableQuirk(m_needsHiddenContentEditableQuirk));
2989 if (m_needsPlainTextQuirk) {
2990 m_needsPlainTextQuirk = false;
2991 send(Messages::WebPageProxy::SetNeedsPlainTextQuirk(m_needsPlainTextQuirk));
2996 void WebPage::didCompletePageTransition()
2998 // FIXME: Layer tree freezing should be managed entirely in the UI process side.
2999 setLayerTreeStateIsFrozen(false);
3001 bool isInitialEmptyDocument = !m_mainFrame;
3002 send(Messages::WebPageProxy::DidCompletePageTransition(isInitialEmptyDocument));
3005 void WebPage::show()
3007 send(Messages::WebPageProxy::ShowPage());
3010 String WebPage::userAgent(const URL& webCoreURL) const
3012 return userAgent(nullptr, webCoreURL);
3015 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
3018 String userAgent = m_loaderClient->userAgentForURL(*frame, webcoreURL);
3019 if (!userAgent.isEmpty())
3023 String userAgent = platformUserAgent(webcoreURL);
3024 if (!userAgent.isEmpty())
3029 void WebPage::setUserAgent(const String& userAgent)
3031 if (m_userAgent == userAgent)
3034 m_userAgent = userAgent;
3037 m_page->userAgentChanged();
3040 void WebPage::suspendActiveDOMObjectsAndAnimations()
3042 m_page->suspendActiveDOMObjectsAndAnimations();
3045 void WebPage::resumeActiveDOMObjectsAndAnimations()
3047 m_page->resumeActiveDOMObjectsAndAnimations();
3050 IntPoint WebPage::screenToRootView(const IntPoint& point)
3052 IntPoint windowPoint;
3053 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
3057 IntRect WebPage::rootViewToScreen(const IntRect& rect)
3060 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
3064 #if PLATFORM(IOS_FAMILY)
3065 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
3067 IntPoint windowPoint;
3068 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
3072 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
3075 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
3080 KeyboardUIMode WebPage::keyboardUIMode()
3082 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
3083 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
3086 void WebPage::runJavaScript(const String& script, bool forceUserGesture, std::optional<String> worldName, CallbackID callbackID)
3088 // NOTE: We need to be careful when running scripts that the objects we depend on don't
3089 // disappear during script execution.
3091 RefPtr<SerializedScriptValue> serializedResultValue;
3092 JSLockHolder lock(commonVM());
3093 bool hadException = true;
3094 ExceptionDetails details;
3095 auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
3097 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
3098 hadException = false;
3099 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
3100 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
3104 IPC::DataReference dataReference;
3105 if (serializedResultValue)
3106 dataReference = serializedResultValue->data();
3107 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
3110 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
3112 runJavaScript(script, forceUserGesture, std::nullopt, callbackID);
3115 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
3117 runJavaScript(script, forceUserGesture, worldName, callbackID);
3120 void WebPage::getContentsAsString(CallbackID callbackID)
3122 String resultString = m_mainFrame->contentsAsString();
3123 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3127 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
3129 send(Messages::WebPageProxy::DataCallback({ MHTMLArchive::generateMHTMLData(m_page.get()) }, callbackID));
3133 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3135 String resultString = renderTreeExternalRepresentation();
3136 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3139 static Frame* frameWithSelection(Page* page)
3141 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3142 if (frame->selection().isRange())
3149 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3152 RetainPtr<CFDataRef> data;
3153 if (Frame* frame = frameWithSelection(m_page.get()))
3154 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3157 IPC::SharedBufferDataReference dataReference;
3160 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3162 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3165 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3167 WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3168 String resultString = focusedOrMainFrame->selectionAsString();
3169 if (resultString.isEmpty())
3170 resultString = focusedOrMainFrame->contentsAsString();
3171 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3174 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3176 String resultString;
3177 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3178 resultString = frame->source();
3180 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3183 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3185 RefPtr<SharedBuffer> buffer;
3186 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3187 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3188 buffer = pluginView->liveResourceData();
3190 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3191 buffer = loader->mainResourceData();
3195 IPC::SharedBufferDataReference dataReference;
3197 dataReference = { *buffer };
3198 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3201 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3203 DocumentLoader* loader = frame->loader().documentLoader();
3207 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3211 return &subresource->data();
3214 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3216 RefPtr<SharedBuffer> buffer;
3217 if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3218 URL resourceURL(URL(), resourceURLString);
3219 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3222 IPC::SharedBufferDataReference dataReference;
3224 dataReference = { *buffer };
3225 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3228 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3231 RetainPtr<CFDataRef> data;
3232 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3233 data = frame->webArchiveData(nullptr, nullptr);
3235 UNUSED_PARAM(frameID);
3238 IPC::SharedBufferDataReference dataReference;
3241 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3243 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3246 void WebPage::forceRepaintWithoutCallback()
3248 m_drawingArea->forceRepaint();
3251 void WebPage::forceRepaint(CallbackID callbackID)
3253 if (m_drawingArea->forceRepaintAsync(callbackID))
3256 forceRepaintWithoutCallback();
3257 send(Messages::WebPageProxy::VoidCallback(callbackID));
3260 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3262 WebPreferencesStore::removeTestRunnerOverrides();
3263 updatePreferences(store);
3266 void WebPage::updatePreferences(const WebPreferencesStore& store)
3268 updatePreferencesGenerated(store);
3270 Settings& settings = m_page->settings();
3272 bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3273 settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3274 settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3275 settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3276 settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3277 settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3278 settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3279 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3280 settings.setFrameFlattening(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()) ? WebCore::FrameFlattening::FullyEnabled : WebCore::FrameFlattening::Disabled);
3281 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3282 #if ENABLE(DATA_DETECTION)
3283 settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3286 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3288 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3289 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3290 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3291 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3293 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3294 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3296 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3297 setSessionID(PAL::SessionID::legacyPrivateSessionID());
3298 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3299 setSessionID(PAL::SessionID::defaultSessionID());
3301 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3302 if (m_processSuppressionEnabled != processSuppressionEnabled) {
3303 m_processSuppressionEnabled = processSuppressionEnabled;
3304 updateThrottleState();
3308 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3310 #if ENABLE(PAYMENT_REQUEST)
3311 settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3314 // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3315 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3317 #if PLATFORM(IOS_FAMILY)
3318 m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3319 m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3320 setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3322 settings.setUseImageDocumentForSubframePDF(true);
3324 DeprecatedGlobalSettings::setAVKitEnabled(true);
3328 #if ENABLE(SERVICE_WORKER)
3329 if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3330 ASSERT(parentProcessHasServiceWorkerEntitlement());
3331 if (!parentProcessHasServiceWorkerEntitlement())
3332 RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3336 settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3339 m_drawingArea->updatePreferences(store);
3342 #if ENABLE(DATA_DETECTION)
3343 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3345 DataDetectionResult dataDetectionResult;
3346 dataDetectionResult.results = detectionResults;
3347 send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3352 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3354 FrameView* frameView = corePage()->mainFrame().view();
3358 layerTransaction.setContentsSize(frameView->contentsSize());
3359 layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3360 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3361 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3362 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3364 layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3365 layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3366 layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3368 #if PLATFORM(IOS_FAMILY)
3369 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3370 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3371 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3372 layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3373 layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3374 layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3375 layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3376 layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3377 layerTransaction.setIsInStableState(m_isInStableState);
3378 layerTransaction.setAllowsUserScaling(allowsUserScaling());
3379 if (m_pendingDynamicViewportSizeUpdateID) {
3380 layerTransaction.setDynamicViewportSizeUpdateID(*m_pendingDynamicViewportSizeUpdateID);
3381 m_pendingDynamicViewportSizeUpdateID = std::nullopt;
3383 if (m_lastTransactionPageScaleFactor != layerTransaction.pageScaleFactor()) {
3384 m_lastTransactionPageScaleFactor = layerTransaction.pageScaleFactor();
3385 m_lastTransactionIDWithScaleChange = layerTransaction.transactionID();
3389 layerTransaction.setScrollPosition(frameView->scrollPosition());
3391 if (m_hasPendingEditorStateUpdate) {
3392 layerTransaction.setEditorState(editorState());
3393 m_hasPendingEditorStateUpdate = false;
3397 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3399 #if PLATFORM(IOS_FAMILY)
3400 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3401 Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3402 m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3404 m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3407 UNUSED_PARAM(timestamp);
3412 void WebPage::willDisplayPage()
3414 m_page->willDisplayPage();
3417 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3421 if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3422 m_inspector = WebInspector::create(this);
3423 return m_inspector.get();
3426 WebInspectorUI* WebPage::inspectorUI()
3431 m_inspectorUI = WebInspectorUI::create(*this);
3432 return m_inspectorUI.get();
3435 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3439 if (!m_remoteInspectorUI)
3440 m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3441 return m_remoteInspectorUI.get();
3444 void WebPage::inspectorFrontendCountChanged(unsigned count)
3446 send(Messages::WebPageProxy::DidChangeInspectorFrontendCount(count));
3449 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3450 PlaybackSessionManager& WebPage::playbackSessionManager()
3452 if (!m_playbackSessionManager)
3453 m_playbackSessionManager = PlaybackSessionManager::create(*this);
3454 return *m_playbackSessionManager;
3457 VideoFullscreenManager& WebPage::videoFullscreenManager()
3459 if (!m_videoFullscreenManager)
3460 m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3461 return *m_videoFullscreenManager;
3464 void WebPage::videoControlsManagerDidChange()
3466 #if ENABLE(FULLSCREEN_API)
3467 if (auto* manager = fullScreenManager())
3468 manager->videoControlsManagerDidChange();
3474 #if PLATFORM(IOS_FAMILY)
3475 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3477 m_page->setAllowsMediaDocumentInlinePlayback(allows);
3481 #if ENABLE(FULLSCREEN_API)
3482 WebFullScreenManager* WebPage::fullScreenManager()
3484 if (!m_fullScreenManager)
3485 m_fullScreenManager = WebFullScreenManager::create(this);
3486 return m_fullScreenManager.get();
3490 void WebPage::addConsoleMessage(uint64_t frameID, MessageSource messageSource, MessageLevel messageLevel, const String& message, uint64_t requestID)
3492 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3493 frame->addConsoleMessage(messageSource, messageLevel, message, requestID);
3496 void WebPage::sendCSPViolationReport(uint64_t frameID, const WebCore::URL& reportURL, IPC::FormDataReference&& reportData)
3498 auto report = reportData.takeData();
3501 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3502 PingLoader::sendViolationReport(*frame->coreFrame(), reportURL, report.releaseNonNull(), ViolationReportType::ContentSecurityPolicy);
3505 void WebPage::enqueueSecurityPolicyViolationEvent(uint64_t frameID, SecurityPolicyViolationEvent::Init&& eventInit)
3507 auto* frame = WebProcess::singleton().webFrame(frameID);
3510 auto* coreFrame = frame->coreFrame();
3513 if (auto* document = coreFrame->document())
3514 document->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
3517 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3519 if (m_notificationPermissionRequestManager)
3520 return m_notificationPermissionRequestManager.get();
3522 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3523 return m_notificationPermissionRequestManager.get();
3526 #if ENABLE(DRAG_SUPPORT)
3529 void WebPage::performDragControllerAction(DragControllerAction action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3532 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3536 DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3538 case DragControllerAction::Entered: {
3539 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3540 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }));