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 if (!m_drawingArea) {
657 m_drawingArea = DrawingArea::create(*this, parameters);
658 m_drawingArea->setPaintingEnabled(false);
659 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
660 m_drawingArea->updatePreferences(parameters.store);
661 m_drawingArea->setPaintingEnabled(true);
664 if (m_activityState != parameters.activityState)
665 setActivityState(parameters.activityState, ActivityStateChangeAsynchronous, Vector<CallbackID>());
666 if (m_layerHostingMode != parameters.layerHostingMode)
667 setLayerHostingMode(parameters.layerHostingMode);
670 void WebPage::updateThrottleState()
672 bool isActive = m_activityState.containsAny({ ActivityState::IsLoading, ActivityState::IsAudible, ActivityState::IsCapturingMedia, ActivityState::WindowIsActive });
673 bool isVisuallyIdle = m_activityState.contains(ActivityState::IsVisuallyIdle);
674 bool pageSuppressed = m_processSuppressionEnabled && !isActive && isVisuallyIdle;
676 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
677 if (!pageSuppressed) {
678 // App nap must be manually enabled when not running the NSApplication run loop.
679 static std::once_flag onceKey;
680 std::call_once(onceKey, [] {
681 __CFRunLoopSetOptionsReason(__CFRunLoopOptionsEnableAppNap, CFSTR("Finished checkin as application - enable app nap"));
685 // The UserActivity keeps the processes runnable. So if the page should be suppressed, stop the activity.
686 // If the page should not be supressed, start it.
688 m_userActivityHysteresis.stop();
690 m_userActivityHysteresis.start();
693 void WebPage::updateUserActivity()
695 if (m_userActivityHysteresis.state() == PAL::HysteresisState::Started)
696 m_userActivity.start();
698 m_userActivity.stop();
705 auto& webProcess = WebProcess::singleton();
706 #if ENABLE(ASYNC_SCROLLING)
707 if (m_useAsyncScrolling)
708 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
713 m_sandboxExtensionTracker.invalidate();
715 for (auto* pluginView : m_pluginViews)
716 pluginView->webPageDestroyed();
718 #if !PLATFORM(IOS_FAMILY)
720 m_headerBanner->detachFromPage();
722 m_footerBanner->detachFromPage();
723 #endif // !PLATFORM(IOS_FAMILY)
725 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
727 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
728 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
729 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
730 webProcess.removeMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID);
731 #if ENABLE(FULLSCREEN_API)
732 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
736 webPageCounter.decrement();
739 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
740 if (m_playbackSessionManager)
741 m_playbackSessionManager->invalidate();
743 if (m_videoFullscreenManager)
744 m_videoFullscreenManager->invalidate();
748 IPC::Connection* WebPage::messageSenderConnection()
750 return WebProcess::singleton().parentProcessConnection();
753 uint64_t WebPage::messageSenderDestinationID()
758 #if ENABLE(CONTEXT_MENUS)
759 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>&& contextMenuClient)
761 if (!contextMenuClient) {
762 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
766 m_contextMenuClient = WTFMove(contextMenuClient);
770 void WebPage::setInjectedBundleEditorClient(std::unique_ptr<API::InjectedBundle::EditorClient>&& editorClient)
773 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
777 m_editorClient = WTFMove(editorClient);
780 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>&& formClient)
783 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
787 m_formClient = WTFMove(formClient);
790 void WebPage::setInjectedBundlePageLoaderClient(std::unique_ptr<API::InjectedBundle::PageLoaderClient>&& loaderClient)
793 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
797 m_loaderClient = WTFMove(loaderClient);
799 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
800 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
801 // for backwards compatibility.
802 if (auto milestones = m_loaderClient->layoutMilestones())
803 listenForLayoutMilestones(milestones);
806 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
808 m_policyClient.initialize(client);
811 void WebPage::setInjectedBundleResourceLoadClient(std::unique_ptr<API::InjectedBundle::ResourceLoadClient>&& client)
813 if (!m_resourceLoadClient)
814 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
816 m_resourceLoadClient = WTFMove(client);
819 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>&& uiClient)
822 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
826 m_uiClient = WTFMove(uiClient);
829 #if ENABLE(FULLSCREEN_API)
830 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
832 m_fullScreenClient.initialize(client);
836 #if ENABLE(NETSCAPE_PLUGIN_API)
837 RefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
839 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
840 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
842 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
843 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
844 unsigned pluginArea = 0;
845 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
847 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
850 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
852 uint64_t pluginProcessToken;
853 uint32_t pluginLoadPolicy;
854 String unavailabilityDescription;
856 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)))
859 PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
860 bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
862 if (isUnsupported || isBlockedPlugin || !pluginProcessToken) {
863 #if ENABLE(PDFKIT_PLUGIN)
864 String path = parameters.url.path();
865 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWithIgnoringASCIICase(".pdf") || path.endsWithIgnoringASCIICase(".ps")))))
866 return PDFPlugin::create(*frame);
871 pluginElement->setReplacement(RenderEmbeddedObject::UnsupportedPlugin, unavailabilityDescription);
875 if (isBlockedPlugin) {
876 bool isReplacementObscured = pluginElement->setReplacement(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
877 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, isReplacementObscured));
881 if (!pluginProcessToken)
884 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
885 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
887 #endif // ENABLE(NETSCAPE_PLUGIN_API)
889 #if ENABLE(WEBGL) && !PLATFORM(MAC)
890 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const URL&)
892 return WebGLAllowCreation;
895 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const URL&)
897 return WebGLAllowCreation;
901 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
903 Frame& frame = m_page->focusController().focusedOrMainFrame();
907 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
908 if (!pluginView->getSelectionString().isNull()) {
909 result.selectionIsNone = false;
910 result.selectionIsRange = true;
911 result.isInPlugin = true;
916 const VisibleSelection& selection = frame.selection().selection();
917 const Editor& editor = frame.editor();
919 result.selectionIsNone = selection.isNone();
920 result.selectionIsRange = selection.isRange();
921 result.isContentEditable = selection.isContentEditable();
922 result.isContentRichlyEditable = selection.isContentRichlyEditable();
923 result.isInPasswordField = selection.isInPasswordField();
924 result.hasComposition = editor.hasComposition();
925 result.shouldIgnoreSelectionChanges = editor.ignoreSelectionChanges();
927 if (auto* document = frame.document())
928 result.originIdentifierForPasteboard = document->originIdentifierForPasteboard();
930 bool canIncludePostLayoutData = frame.view() && !frame.view()->needsLayout();
931 if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && canIncludePostLayoutData) {
932 auto& postLayoutData = result.postLayoutData();
933 postLayoutData.canCut = editor.canCut();
934 postLayoutData.canCopy = editor.canCopy();
935 postLayoutData.canPaste = editor.canPaste();
937 if (m_needsFontAttributes)
938 postLayoutData.fontAttributes = editor.fontAttributesAtSelectionStart();
941 if (result.isContentEditable && !selection.isNone()) {
942 if (auto editingStyle = EditingStyle::styleAtSelectionStart(selection)) {
943 if (editingStyle->hasStyle(CSSPropertyFontWeight, "bold"))
944 postLayoutData.typingAttributes |= AttributeBold;
946 if (editingStyle->hasStyle(CSSPropertyFontStyle, "italic") || editingStyle->hasStyle(CSSPropertyFontStyle, "oblique"))
947 postLayoutData.typingAttributes |= AttributeItalics;
949 if (editingStyle->hasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline"))
950 postLayoutData.typingAttributes |= AttributeUnderline;
952 if (auto* styleProperties = editingStyle->style()) {
953 bool isLeftToRight = styleProperties->propertyAsValueID(CSSPropertyDirection) == CSSValueLtr;
954 switch (styleProperties->propertyAsValueID(CSSPropertyTextAlign)) {
956 case CSSValueWebkitRight:
957 postLayoutData.textAlignment = RightAlignment;
960 case CSSValueWebkitLeft:
961 postLayoutData.textAlignment = LeftAlignment;
964 case CSSValueWebkitCenter:
965 postLayoutData.textAlignment = CenterAlignment;
967 case CSSValueJustify:
968 postLayoutData.textAlignment = JustifiedAlignment;
971 postLayoutData.textAlignment = isLeftToRight ? LeftAlignment : RightAlignment;
974 postLayoutData.textAlignment = isLeftToRight ? RightAlignment : LeftAlignment;
979 if (auto textColor = styleProperties->propertyAsColor(CSSPropertyColor))
980 postLayoutData.textColor = *textColor;
984 if (auto* enclosingListElement = enclosingList(selection.start().containerNode())) {
985 if (is<HTMLUListElement>(*enclosingListElement))
986 postLayoutData.enclosingListType = UnorderedList;
987 else if (is<HTMLOListElement>(*enclosingListElement))
988 postLayoutData.enclosingListType = OrderedList;
990 ASSERT_NOT_REACHED();
996 platformEditorState(frame, result, shouldIncludePostLayoutData);
998 m_lastEditorStateWasContentEditable = result.isContentEditable ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1003 void WebPage::changeFontAttributes(WebCore::FontAttributeChanges&& changes)
1005 auto& frame = m_page->focusController().focusedOrMainFrame();
1006 if (frame.selection().selection().isContentEditable())
1007 frame.editor().applyStyleToSelection(changes.createEditingStyle(), changes.editAction(), Editor::ColorFilterMode::InvertColor);
1010 void WebPage::changeFont(WebCore::FontChanges&& changes)
1012 auto& frame = m_page->focusController().focusedOrMainFrame();
1013 if (frame.selection().selection().isContentEditable())
1014 frame.editor().applyStyleToSelection(changes.createEditingStyle(), EditAction::SetFont, Editor::ColorFilterMode::InvertColor);
1017 void WebPage::executeEditCommandWithCallback(const String& commandName, const String& argument, CallbackID callbackID)
1019 executeEditCommand(commandName, argument);
1020 send(Messages::WebPageProxy::VoidCallback(callbackID));
1023 void WebPage::updateEditorStateAfterLayoutIfEditabilityChanged()
1025 // FIXME: We should update EditorStateIsContentEditable to track whether the state is richly
1026 // editable or plainttext-only.
1027 if (m_lastEditorStateWasContentEditable == EditorStateIsContentEditable::Unset)
1030 Frame& frame = m_page->focusController().focusedOrMainFrame();
1031 EditorStateIsContentEditable editorStateIsContentEditable = frame.selection().selection().isContentEditable() ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1032 if (m_lastEditorStateWasContentEditable != editorStateIsContentEditable)
1033 sendPartialEditorStateAndSchedulePostLayoutUpdate();
1036 String WebPage::renderTreeExternalRepresentation() const
1038 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
1041 String WebPage::renderTreeExternalRepresentationForPrinting() const
1043 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
1046 uint64_t WebPage::renderTreeSize() const
1050 return m_page->renderTreeSize();
1053 void WebPage::setTracksRepaints(bool trackRepaints)
1055 if (FrameView* view = mainFrameView())
1056 view->setTracksRepaints(trackRepaints);
1059 bool WebPage::isTrackingRepaints() const
1061 if (FrameView* view = mainFrameView())
1062 return view->isTrackingRepaints();
1067 void WebPage::resetTrackedRepaints()
1069 if (FrameView* view = mainFrameView())
1070 view->resetTrackedRepaints();
1073 Ref<API::Array> WebPage::trackedRepaintRects()
1075 FrameView* view = mainFrameView();
1077 return API::Array::create();
1079 Vector<RefPtr<API::Object>> repaintRects;
1080 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
1082 for (const auto& repaintRect : view->trackedRepaintRects())
1083 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
1085 return API::Array::create(WTFMove(repaintRects));
1088 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
1090 if (!is<PluginDocument>(frame.document()))
1093 auto& pluginDocument = downcast<PluginDocument>(*frame.document());
1094 if (pluginDocument.focusedElement() != pluginDocument.pluginElement())
1097 return pluginViewForFrame(&frame);
1100 PluginView* WebPage::pluginViewForFrame(Frame* frame)
1102 if (!frame || !is<PluginDocument>(frame->document()))
1105 auto& document = downcast<PluginDocument>(*frame->document());
1106 return static_cast<PluginView*>(document.pluginWidget());
1109 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
1111 Frame& frame = m_page->focusController().focusedOrMainFrame();
1113 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
1114 pluginView->handleEditingCommand(commandName, argument);
1118 frame.editor().command(commandName).execute(argument);
1121 void WebPage::setEditable(bool editable)
1123 m_page->setEditable(editable);
1124 m_page->setTabKeyCyclesThroughElements(!editable);
1125 Frame& frame = m_page->focusController().focusedOrMainFrame();
1127 frame.editor().applyEditingStyleToBodyElement();
1128 // If the page is made editable and the selection is empty, set it to something.
1129 if (frame.selection().isNone())
1130 frame.selection().setSelectionFromNone();
1134 bool WebPage::isEditingCommandEnabled(const String& commandName)
1136 Frame& frame = m_page->focusController().focusedOrMainFrame();
1138 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1139 return pluginView->isEditingCommandEnabled(commandName);
1141 Editor::Command command = frame.editor().command(commandName);
1142 return command.isSupported() && command.isEnabled();
1145 void WebPage::clearMainFrameName()
1147 if (Frame* frame = mainFrame())
1148 frame->tree().clearName();
1151 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
1153 m_drawingArea->setRootCompositingLayer(layer);
1156 void WebPage::exitAcceleratedCompositingMode()
1159 m_drawingArea->setRootCompositingLayer(0);
1162 void WebPage::close()
1167 WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::RemoveStorageAccessForAllFramesOnPage(sessionID(), m_pageID), 0);
1171 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1172 if (!mainWebFrame()->url().isEmpty())
1173 reportUsedFeatures();
1175 if (WebProcess::singleton().injectedBundle())
1176 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1179 m_inspector->disconnectFromPage();
1180 m_inspector = nullptr;
1183 m_page->inspectorController().disconnectAllFrontends();
1185 #if ENABLE(MEDIA_STREAM)
1186 m_userMediaPermissionRequestManager = nullptr;
1189 #if ENABLE(FULLSCREEN_API)
1190 m_fullScreenManager = nullptr;
1193 if (m_activePopupMenu) {
1194 m_activePopupMenu->disconnectFromPage();
1195 m_activePopupMenu = nullptr;
1198 if (m_activeOpenPanelResultListener) {
1199 m_activeOpenPanelResultListener->disconnectFromPage();
1200 m_activeOpenPanelResultListener = nullptr;
1203 #if ENABLE(INPUT_TYPE_COLOR)
1204 if (m_activeColorChooser) {
1205 m_activeColorChooser->disconnectFromPage();
1206 m_activeColorChooser = nullptr;
1211 if (m_printOperation) {
1212 m_printOperation->disconnectFromPage();
1213 m_printOperation = nullptr;
1217 #if ENABLE(VIDEO) && USE(GSTREAMER)
1218 if (m_installMediaPluginsCallback) {
1219 m_installMediaPluginsCallback->invalidate();
1220 m_installMediaPluginsCallback = nullptr;
1224 m_sandboxExtensionTracker.invalidate();
1226 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1227 m_determinePrimarySnapshottedPlugInTimer.stop();
1230 #if ENABLE(CONTEXT_MENUS)
1231 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1233 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
1234 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1235 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
1236 m_policyClient.initialize(0);
1237 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
1238 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1239 #if ENABLE(FULLSCREEN_API)
1240 m_fullScreenClient.initialize(0);
1243 m_printContext = nullptr;
1244 m_mainFrame->coreFrame()->loader().detachFromParent();
1245 m_drawingArea = nullptr;
1247 DeferredPageDestructor::createDeferredPageDestructor(WTFMove(m_page), this);
1249 bool isRunningModal = m_isRunningModal;
1250 m_isRunningModal = false;
1252 // The WebPage can be destroyed by this call.
1253 WebProcess::singleton().removeWebPage(m_pageID);
1255 WebProcess::singleton().updateActivePages();
1258 RunLoop::main().stop();
1261 void WebPage::tryClose()
1263 SendStopResponsivenessTimer stopper;
1265 if (!corePage()->userInputBridge().tryClosePage())
1268 send(Messages::WebPageProxy::ClosePage(true));
1271 void WebPage::sendClose()
1273 send(Messages::WebPageProxy::ClosePage(false));
1276 void WebPage::loadURLInFrame(WebCore::URL&& url, uint64_t frameID)
1278 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1282 frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(url), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1285 #if !PLATFORM(COCOA)
1286 void WebPage::platformDidReceiveLoadParameters(const LoadParameters& loadParameters)
1291 void WebPage::loadRequest(LoadParameters&& loadParameters)
1293 SendStopResponsivenessTimer stopper;
1295 m_pendingNavigationID = loadParameters.navigationID;
1297 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), WTFMove(loadParameters.sandboxExtensionHandle));
1299 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1300 // to all the client to set up any needed state.
1301 m_loaderClient->willLoadURLRequest(*this, loadParameters.request, WebProcess::singleton().transformHandlesToObjects(loadParameters.userData.object()).get());
1303 platformDidReceiveLoadParameters(loadParameters);
1305 // Initate the load in WebCore.
1306 FrameLoadRequest frameLoadRequest { *m_mainFrame->coreFrame(), loadParameters.request, ShouldOpenExternalURLsPolicy::ShouldNotAllow };
1307 ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(loadParameters.shouldOpenExternalURLsPolicy);
1308 frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1309 frameLoadRequest.setShouldTreatAsContinuingLoad(loadParameters.shouldTreatAsContinuingLoad);
1310 frameLoadRequest.setLockHistory(loadParameters.lockHistory);
1311 frameLoadRequest.setlockBackForwardList(loadParameters.lockBackForwardList);
1312 frameLoadRequest.setClientRedirectSourceForHistory(loadParameters.clientRedirectSourceForHistory);
1314 corePage()->userInputBridge().loadRequest(WTFMove(frameLoadRequest));
1316 ASSERT(!m_pendingNavigationID);
1319 void WebPage::loadDataImpl(uint64_t navigationID, Ref<SharedBuffer>&& sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1321 SendStopResponsivenessTimer stopper;
1323 m_pendingNavigationID = navigationID;
1325 ResourceRequest request(baseURL);
1326 ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1327 SubstituteData substituteData(WTFMove(sharedBuffer), unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1329 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1330 // to all the client to set up any needed state.
1331 m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1333 // Initate the load in WebCore.
1334 m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(*m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData));
1337 void WebPage::loadData(LoadParameters&& loadParameters)
1339 platformDidReceiveLoadParameters(loadParameters);
1341 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1342 URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1343 loadDataImpl(loadParameters.navigationID, WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, URL(), loadParameters.userData);
1346 void WebPage::loadAlternateHTML(const LoadParameters& loadParameters)
1348 platformDidReceiveLoadParameters(loadParameters);
1350 URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1351 URL unreachableURL = loadParameters.unreachableURLString.isEmpty() ? URL() : URL(URL(), loadParameters.unreachableURLString);
1352 URL provisionalLoadErrorURL = loadParameters.provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), loadParameters.provisionalLoadErrorURLString);
1353 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1354 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1355 loadDataImpl(loadParameters.navigationID, WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, unreachableURL, loadParameters.userData);
1356 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1359 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1361 Frame* mainFrame = m_mainFrame->coreFrame();
1362 Document* mainFrameDocument = mainFrame->document();
1363 if (!mainFrameDocument)
1366 const int singleClick = 1;
1367 // FIXME: Set modifier keys.
1368 // FIXME: This should probably set IsSimulated::Yes.
1369 RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes, Event::IsComposed::Yes,
1370 MonotonicTime::now(), nullptr, singleClick, screenPoint, documentPoint, { }, { }, 0, 0, nullptr, 0, WebCore::NoTap, nullptr);
1372 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1375 void WebPage::stopLoadingFrame(uint64_t frameID)
1377 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1381 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1384 void WebPage::stopLoading()
1386 SendStopResponsivenessTimer stopper;
1388 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1391 bool WebPage::defersLoading() const
1393 return m_page->defersLoading();
1396 void WebPage::setDefersLoading(bool defersLoading)
1398 m_page->setDefersLoading(defersLoading);
1401 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, SandboxExtension::Handle&& sandboxExtensionHandle)
1403 SendStopResponsivenessTimer stopper;
1405 ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1406 m_pendingNavigationID = navigationID;
1408 m_sandboxExtensionTracker.beginReload(m_mainFrame.get(), WTFMove(sandboxExtensionHandle));
1409 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1411 if (m_pendingNavigationID) {
1412 // This can happen if FrameLoader::reload() returns early because the document URL is empty.
1413 // The reload does nothing so we need to reset the pending navigation. See webkit.org/b/153210.
1414 m_pendingNavigationID = 0;
1418 void WebPage::goToBackForwardItem(uint64_t navigationID, const BackForwardItemIdentifier& backForwardItemID, FrameLoadType backForwardType, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad)
1420 SendStopResponsivenessTimer stopper;
1422 ASSERT(isBackForwardLoadType(backForwardType));
1424 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1429 LOG(Loading, "In WebProcess pid %i, WebPage %" PRIu64 " is navigating to back/forward URL %s", getCurrentProcessID(), m_pageID, item->url().string().utf8().data());
1431 ASSERT(!m_pendingNavigationID);
1432 m_pendingNavigationID = navigationID;
1434 m_page->goToItem(*item, backForwardType, shouldTreatAsContinuingLoad);
1437 void WebPage::tryRestoreScrollPosition()
1439 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1442 void WebPage::layoutIfNeeded()
1444 if (m_mainFrame->coreFrame()->view())
1445 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1448 WebPage* WebPage::fromCorePage(Page* page)
1450 return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1453 void WebPage::setSize(const WebCore::IntSize& viewSize)
1455 if (m_viewSize == viewSize)
1458 m_viewSize = viewSize;
1459 FrameView* view = m_page->mainFrame().view();
1460 view->resize(viewSize);
1461 m_drawingArea->setNeedsDisplay();
1463 #if USE(COORDINATED_GRAPHICS)
1464 if (view->useFixedLayout())
1465 sendViewportAttributesChanged(m_page->viewportArguments());
1469 #if USE(COORDINATED_GRAPHICS)
1470 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1472 FrameView* view = m_page->mainFrame().view();
1473 ASSERT(view && view->useFixedLayout());
1475 // Viewport properties have no impact on zero sized fixed viewports.
1476 if (m_viewSize.isEmpty())
1479 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1480 Settings& settings = m_page->settings();
1482 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1484 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1485 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1486 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1488 ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1490 // If no layout was done yet set contentFixedOrigin to (0,0).
1491 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1493 // Put the width and height to the viewport width and height. In css units however.
1494 // Use FloatSize to avoid truncated values during scale.
1495 FloatSize contentFixedSize = m_viewSize;
1497 #if ENABLE(CSS_DEVICE_ADAPTATION)
1498 // CSS viewport descriptors might be applied to already affected viewport size
1499 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1500 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1503 contentFixedSize.scale(1 / attr.initialScale);
1504 view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1506 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1508 // This also takes care of the relayout.
1509 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1511 #if USE(COORDINATED_GRAPHICS_THREADED)
1512 m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1514 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1519 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1521 FrameView* frameView = m_page->mainFrame().view();
1523 ScrollPosition scrollPosition = frameView->scrollPosition();
1524 ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1526 // If the current scroll position in a direction is the max scroll position
1527 // we don't want to scroll at all.
1528 IntSize newScrollOffset;
1529 if (scrollPosition.x() < maximumScrollPosition.x())
1530 newScrollOffset.setWidth(scrollOffset.width());
1531 if (scrollPosition.y() < maximumScrollPosition.y())
1532 newScrollOffset.setHeight(scrollOffset.height());
1534 if (newScrollOffset.isZero())
1537 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1540 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1543 auto* document = m_mainFrame->coreFrame()->document();
1544 LocalDefaultSystemAppearance localAppearance(document ? document->useDarkAppearance() : false);
1547 GraphicsContextStateSaver stateSaver(graphicsContext);
1548 graphicsContext.clip(rect);
1550 m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1553 double WebPage::textZoomFactor() const
1555 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1556 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1557 if (pluginView->handlesPageScaleFactor())
1558 return pluginView->pageScaleFactor();
1559 return pageScaleFactor();
1562 Frame* frame = m_mainFrame->coreFrame();
1565 return frame->textZoomFactor();
1568 void WebPage::setTextZoomFactor(double zoomFactor)
1570 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1571 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1572 if (pluginView->handlesPageScaleFactor())
1573 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1575 scalePage(zoomFactor, IntPoint());
1579 Frame* frame = m_mainFrame->coreFrame();
1582 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1585 double WebPage::pageZoomFactor() const
1587 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1588 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1589 if (pluginView->handlesPageScaleFactor())
1590 return pluginView->pageScaleFactor();
1591 return pageScaleFactor();
1594 Frame* frame = m_mainFrame->coreFrame();
1597 return frame->pageZoomFactor();
1600 void WebPage::setPageZoomFactor(double zoomFactor)
1602 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1603 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1604 if (pluginView->handlesPageScaleFactor())
1605 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1607 scalePage(zoomFactor, IntPoint());
1611 Frame* frame = m_mainFrame->coreFrame();
1614 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1617 static void dumpHistoryItem(HistoryItem& item, size_t indent, bool isCurrentItem, StringBuilder& stringBuilder, const String& directoryName)
1620 stringBuilder.appendLiteral("curr-> ");
1622 for (size_t i = 0; i < indent; ++i)
1623 stringBuilder.append(' ');
1626 auto url = item.url();
1627 if (url.protocolIs("file")) {
1628 size_t start = url.string().find(directoryName);
1629 if (start == WTF::notFound)
1632 start += directoryName.length();
1633 stringBuilder.appendLiteral("(file test):");
1634 stringBuilder.append(url.string().substring(start));
1636 stringBuilder.append(url);
1638 auto& target = item.target();
1639 if (target.length()) {
1640 stringBuilder.appendLiteral(" (in frame \"");
1641 stringBuilder.append(target);
1642 stringBuilder.appendLiteral("\")");
1645 if (item.isTargetItem())
1646 stringBuilder.appendLiteral(" **nav target**");
1648 stringBuilder.append('\n');
1650 Vector<Ref<HistoryItem>> children;
1651 children.reserveInitialCapacity(item.children().size());
1652 for (auto& child : item.children())
1653 children.uncheckedAppend(child.copyRef());
1654 std::stable_sort(children.begin(), children.end(), [] (auto& a, auto& b) {
1655 return codePointCompare(a->target(), b->target()) < 0;
1657 for (auto& child : children)
1658 dumpHistoryItem(child, indent + 4, false, stringBuilder, directoryName);
1661 String WebPage::dumpHistoryForTesting(const String& directory)
1666 auto& list = m_page->backForward();
1668 StringBuilder builder;
1669 int begin = -list.backCount();
1670 if (list.itemAtIndex(begin)->url() == blankURL())
1672 for (int i = begin; i <= static_cast<int>(list.forwardCount()); ++i)
1673 dumpHistoryItem(*list.itemAtIndex(i), 8, !i, builder, directory);
1674 return builder.toString();
1677 void WebPage::clearHistory()
1682 static_cast<WebBackForwardListProxy&>(m_page->backForward().client()).clear();
1685 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1687 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1688 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1689 if (pluginView->handlesPageScaleFactor())
1690 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1692 scalePage(pageZoomFactor, IntPoint());
1696 Frame* frame = m_mainFrame->coreFrame();
1699 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1702 void WebPage::windowScreenDidChange(uint32_t displayID)
1704 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1707 void WebPage::scalePage(double scale, const IntPoint& origin)
1709 double totalScale = scale * viewScaleFactor();
1710 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1712 #if PLATFORM(IOS_FAMILY)
1713 if (willChangeScaleFactor) {
1714 if (!m_inDynamicSizeUpdate)
1715 m_dynamicSizeUpdateHistory.clear();
1716 m_scaleWasSetByUIProcess = false;
1719 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1720 if (pluginView && pluginView->handlesPageScaleFactor()) {
1721 // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1722 // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1723 if (m_page->pageScaleFactor() != 1) {
1724 m_page->setPageScaleFactor(1, origin);
1725 for (auto* pluginView : m_pluginViews)
1726 pluginView->pageScaleFactorDidChange();
1729 pluginView->setPageScaleFactor(totalScale, origin);
1733 m_page->setPageScaleFactor(totalScale, origin);
1735 // We can't early return before setPageScaleFactor because the origin might be different.
1736 if (!willChangeScaleFactor)
1739 for (auto* pluginView : m_pluginViews)
1740 pluginView->pageScaleFactorDidChange();
1742 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1743 m_drawingArea->deviceOrPageScaleFactorChanged();
1746 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1749 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1751 double totalScale = scale * viewScaleFactor();
1752 if (totalScale == totalScaleFactor())
1755 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1756 double scaleRatio = scale / pageScaleFactor();
1757 scrollPositionAtNewScale.scale(scaleRatio);
1758 scalePage(scale, scrollPositionAtNewScale);
1761 double WebPage::totalScaleFactor() const
1763 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1764 if (pluginView && pluginView->handlesPageScaleFactor())
1765 return pluginView->pageScaleFactor();
1767 return m_page->pageScaleFactor();
1770 double WebPage::pageScaleFactor() const
1772 return totalScaleFactor() / viewScaleFactor();
1775 double WebPage::viewScaleFactor() const
1777 return m_page->viewScaleFactor();
1780 void WebPage::scaleView(double scale)
1782 if (viewScaleFactor() == scale)
1785 float pageScale = pageScaleFactor();
1787 IntPoint scrollPositionAtNewScale;
1788 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1789 double scaleRatio = scale / viewScaleFactor();
1790 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1791 scrollPositionAtNewScale.scale(scaleRatio);
1794 m_page->setViewScaleFactor(scale);
1795 scalePage(pageScale, scrollPositionAtNewScale);
1798 void WebPage::setDeviceScaleFactor(float scaleFactor)
1800 if (scaleFactor == m_page->deviceScaleFactor())
1803 m_page->setDeviceScaleFactor(scaleFactor);
1805 // Tell all our plug-in views that the device scale factor changed.
1807 for (auto* pluginView : m_pluginViews)
1808 pluginView->setDeviceScaleFactor(scaleFactor);
1810 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1813 if (findController().isShowingOverlay()) {
1814 // We must have updated layout to get the selection rects right.
1816 findController().deviceScaleFactorDidChange();
1819 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1820 m_drawingArea->deviceOrPageScaleFactorChanged();
1824 float WebPage::deviceScaleFactor() const
1826 return m_page->deviceScaleFactor();
1829 void WebPage::accessibilitySettingsDidChange()
1831 m_page->accessibilitySettingsDidChange();
1834 #if ENABLE(ACCESSIBILITY_EVENTS)
1835 void WebPage::updateAccessibilityEventsEnabled(bool enabled)
1837 m_page->settings().setAccessibilityEventsEnabled(enabled);
1841 void WebPage::setUseFixedLayout(bool fixed)
1843 // Do not overwrite current settings if initially setting it to false.
1844 if (m_useFixedLayout == fixed)
1846 m_useFixedLayout = fixed;
1848 #if !PLATFORM(IOS_FAMILY)
1849 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1852 FrameView* view = mainFrameView();
1856 view->setUseFixedLayout(fixed);
1858 setFixedLayoutSize(IntSize());
1860 send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1863 bool WebPage::setFixedLayoutSize(const IntSize& size)
1865 FrameView* view = mainFrameView();
1866 if (!view || view->fixedLayoutSize() == size)
1869 LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " setFixedLayoutSize " << size);
1870 view->setFixedLayoutSize(size);
1872 send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1876 IntSize WebPage::fixedLayoutSize() const
1878 FrameView* view = mainFrameView();
1881 return view->fixedLayoutSize();
1884 void WebPage::disabledAdaptationsDidChange(const OptionSet<DisabledAdaptations>& disabledAdaptations)
1886 #if PLATFORM(IOS_FAMILY)
1887 if (m_viewportConfiguration.setDisabledAdaptations(disabledAdaptations))
1888 viewportConfigurationChanged();
1890 UNUSED_PARAM(disabledAdaptations);
1894 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
1896 #if PLATFORM(IOS_FAMILY)
1897 if (!m_page->settings().shouldIgnoreMetaViewport() && m_viewportConfiguration.setViewportArguments(viewportArguments))
1898 viewportConfigurationChanged();
1901 #if USE(COORDINATED_GRAPHICS)
1902 FrameView* view = m_page->mainFrame().view();
1903 if (view && view->useFixedLayout())
1904 sendViewportAttributesChanged(viewportArguments);
1905 #if USE(COORDINATED_GRAPHICS_THREADED)
1907 m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
1911 #if !PLATFORM(IOS_FAMILY) && !USE(COORDINATED_GRAPHICS)
1912 UNUSED_PARAM(viewportArguments);
1916 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1920 m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1923 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1925 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1928 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1930 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1933 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1935 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1938 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1940 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1941 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1944 void WebPage::setPaginationMode(uint32_t mode)
1946 Pagination pagination = m_page->pagination();
1947 pagination.mode = static_cast<Pagination::Mode>(mode);
1948 m_page->setPagination(pagination);
1951 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1953 Pagination pagination = m_page->pagination();
1954 pagination.behavesLikeColumns = behavesLikeColumns;
1955 m_page->setPagination(pagination);
1958 void WebPage::setPageLength(double pageLength)
1960 Pagination pagination = m_page->pagination();
1961 pagination.pageLength = pageLength;
1962 m_page->setPagination(pagination);
1965 void WebPage::setGapBetweenPages(double gap)
1967 Pagination pagination = m_page->pagination();
1968 pagination.gap = gap;
1969 m_page->setPagination(pagination);
1972 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
1974 m_page->setPaginationLineGridEnabled(lineGridEnabled);
1977 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1979 auto& webProcess = WebProcess::singleton();
1980 InjectedBundle* injectedBundle = webProcess.injectedBundle();
1981 if (!injectedBundle)
1984 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1987 #if !PLATFORM(IOS_FAMILY)
1989 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
1992 m_headerBanner->detachFromPage();
1994 m_headerBanner = pageBanner;
1997 m_headerBanner->addToPage(PageBanner::Header, this);
2000 PageBanner* WebPage::headerPageBanner()
2002 return m_headerBanner.get();
2005 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
2008 m_footerBanner->detachFromPage();
2010 m_footerBanner = pageBanner;
2013 m_footerBanner->addToPage(PageBanner::Footer, this);
2016 PageBanner* WebPage::footerPageBanner()
2018 return m_footerBanner.get();
2021 void WebPage::hidePageBanners()
2024 m_headerBanner->hide();
2026 m_footerBanner->hide();
2029 void WebPage::showPageBanners()
2032 m_headerBanner->showIfHidden();
2034 m_footerBanner->showIfHidden();
2037 void WebPage::setHeaderBannerHeightForTesting(int height)
2039 #if ENABLE(RUBBER_BANDING)
2040 corePage()->addHeaderWithHeight(height);
2044 void WebPage::setFooterBannerHeightForTesting(int height)
2046 #if ENABLE(RUBBER_BANDING)
2047 corePage()->addFooterWithHeight(height);
2051 #endif // !PLATFORM(IOS_FAMILY)
2053 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
2055 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
2056 snapshotOptions |= SnapshotOptionsShareable;
2058 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
2060 ShareableBitmap::Handle handle;
2062 image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
2064 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
2067 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
2069 IntRect snapshotRect = rect;
2070 IntSize bitmapSize = snapshotRect.size();
2071 if (options & SnapshotOptionsPrinting) {
2072 ASSERT(additionalScaleFactor == 1);
2073 Frame* coreFrame = m_mainFrame->coreFrame();
2076 bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
2078 double scaleFactor = additionalScaleFactor;
2079 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
2080 scaleFactor *= corePage()->deviceScaleFactor();
2081 bitmapSize.scale(scaleFactor);
2084 return snapshotAtSize(rect, bitmapSize, options);
2087 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
2089 IntRect snapshotRect = rect;
2090 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
2091 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
2092 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
2094 if (options & SnapshotOptionsPrinting) {
2095 PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
2099 Color documentBackgroundColor = frameView.documentBackgroundColor();
2100 Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
2101 graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
2103 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2104 double deviceScaleFactor = frame.page()->deviceScaleFactor();
2105 graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
2106 scaleFactor /= deviceScaleFactor;
2109 graphicsContext.scale(scaleFactor);
2110 graphicsContext.translate(-snapshotRect.location());
2112 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
2113 if (options & SnapshotOptionsExcludeSelectionHighlighting)
2114 shouldPaintSelection = FrameView::ExcludeSelection;
2116 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
2117 if (options & SnapshotOptionsInViewCoordinates)
2118 coordinateSpace = FrameView::ViewCoordinates;
2120 frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
2122 if (options & SnapshotOptionsPaintSelectionRectangle) {
2123 FloatRect selectionRectangle = frame.selection().selectionBounds();
2124 graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
2125 graphicsContext.strokeRect(selectionRectangle, 1);
2129 static ShareableBitmap::Configuration snapshotOptionsToBitmapConfiguration(SnapshotOptions options, WebPage& page)
2131 ShareableBitmap::Configuration configuration;
2133 if (options & SnapshotOptionsUseScreenColorSpace)
2134 configuration.colorSpace.cgColorSpace = screenColorSpace(page.corePage()->mainFrame().view());
2136 return configuration;
2139 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2141 Frame* coreFrame = m_mainFrame->coreFrame();
2145 FrameView* frameView = coreFrame->view();
2149 auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2152 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2154 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2160 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2162 Frame* coreFrame = m_mainFrame->coreFrame();
2166 FrameView* frameView = coreFrame->view();
2170 auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2173 auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2174 auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2175 auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2177 CGPDFContextBeginPage(pdfContext.get(), nullptr);
2179 GraphicsContext graphicsContext { pdfContext.get() };
2180 graphicsContext.scale({ 1, -1 });
2181 graphicsContext.translate(0, -bitmapSize.height());
2182 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2184 CGPDFContextEndPage(pdfContext.get());
2185 CGPDFContextClose(pdfContext.get());
2188 return WTFMove(data);
2192 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2194 Frame* coreFrame = m_mainFrame->coreFrame();
2198 FrameView* frameView = coreFrame->view();
2202 if (!node.renderer())
2205 LayoutRect topLevelRect;
2206 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2207 if (snapshotRect.isEmpty())
2210 double scaleFactor = 1;
2211 IntSize snapshotSize = snapshotRect.size();
2212 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2213 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2214 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2215 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2218 auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2221 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2223 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2224 double deviceScaleFactor = corePage()->deviceScaleFactor();
2225 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2226 scaleFactor /= deviceScaleFactor;
2229 graphicsContext->scale(scaleFactor);
2230 graphicsContext->translate(-snapshotRect.location());
2232 Color savedBackgroundColor = frameView->baseBackgroundColor();
2233 frameView->setBaseBackgroundColor(Color::transparent);
2234 frameView->setNodeToDraw(&node);
2236 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2238 frameView->setBaseBackgroundColor(savedBackgroundColor);
2239 frameView->setNodeToDraw(nullptr);
2244 void WebPage::pageDidScroll()
2246 #if PLATFORM(IOS_FAMILY)
2247 if (!m_inDynamicSizeUpdate)
2248 m_dynamicSizeUpdateHistory.clear();
2250 m_uiClient->pageDidScroll(this);
2252 m_pageScrolledHysteresis.impulse();
2254 send(Messages::WebPageProxy::PageDidScroll());
2257 void WebPage::pageStoppedScrolling()
2259 // Maintain the current history item's scroll position up-to-date.
2260 if (Frame* frame = m_mainFrame->coreFrame())
2261 frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2264 #if ENABLE(CONTEXT_MENUS)
2265 WebContextMenu* WebPage::contextMenu()
2268 m_contextMenu = WebContextMenu::create(this);
2269 return m_contextMenu.get();
2272 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2274 corePage()->contextMenuController().clearContextMenu();
2276 // Simulate a mouse click to generate the correct menu.
2277 PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2278 corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2279 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2280 auto* menu = handled ? contextMenu() : nullptr;
2281 PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2282 corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2290 static const WebEvent* g_currentEvent = 0;
2292 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2293 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2294 // platform events passed to the event handler code.
2295 const WebEvent* WebPage::currentEvent()
2297 return g_currentEvent;
2300 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
2302 auto* drawingArea = this->drawingArea();
2306 drawingArea->setLayerTreeStateIsFrozen(frozen || m_isSuspended);
2309 void WebPage::callVolatilityCompletionHandlers(bool succeeded)
2311 auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2312 for (auto& completionHandler : completionHandlers)
2313 completionHandler(succeeded);
2316 void WebPage::layerVolatilityTimerFired()
2318 Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2319 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2320 if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2321 m_layerVolatilityTimer.stop();
2323 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Succeeded in marking layers as volatile", this);
2325 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Failed to mark layers as volatile within %gms", this, maximumLayerVolatilityTimerInterval.milliseconds());
2326 callVolatilityCompletionHandlers(didSucceed);
2330 RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.milliseconds());
2331 m_layerVolatilityTimer.startRepeating(newInterval);
2334 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2336 return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2339 void WebPage::markLayersVolatile(WTF::Function<void (bool)>&& completionHandler)
2341 RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2343 if (m_layerVolatilityTimer.isActive())
2344 m_layerVolatilityTimer.stop();
2346 if (completionHandler)
2347 m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2349 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2350 if (didSucceed || m_isSuspendedUnderLock) {
2352 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2354 // 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.
2355 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2357 callVolatilityCompletionHandlers(didSucceed);
2361 RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.milliseconds());
2362 m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2365 void WebPage::cancelMarkLayersVolatile()
2367 RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2368 m_layerVolatilityTimer.stop();
2369 m_markLayersAsVolatileCompletionHandlers.clear();
2372 class CurrentEvent {
2374 explicit CurrentEvent(const WebEvent& event)
2375 : m_previousCurrentEvent(g_currentEvent)
2377 g_currentEvent = &event;
2382 g_currentEvent = m_previousCurrentEvent;
2386 const WebEvent* m_previousCurrentEvent;
2389 #if ENABLE(CONTEXT_MENUS)
2390 static bool isContextClick(const PlatformMouseEvent& event)
2393 return WebEventFactory::shouldBeHandledAsContextClick(event);
2395 return event.button() == WebCore::RightButton;
2399 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2401 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2402 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2404 Frame* frame = &page->corePage()->mainFrame();
2405 if (result.innerNonSharedNode())
2406 frame = result.innerNonSharedNode()->document().frame();
2408 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2410 page->contextMenu()->show();
2415 void WebPage::contextMenuForKeyEvent()
2417 corePage()->contextMenuController().clearContextMenu();
2419 Frame& frame = m_page->focusController().focusedOrMainFrame();
2420 bool handled = frame.eventHandler().sendContextMenuEventForKey();
2422 contextMenu()->show();
2426 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2428 Frame& frame = page->corePage()->mainFrame();
2432 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2434 switch (platformMouseEvent.type()) {
2435 case PlatformEvent::MousePressed: {
2436 #if ENABLE(CONTEXT_MENUS)
2437 if (isContextClick(platformMouseEvent))
2438 page->corePage()->contextMenuController().clearContextMenu();
2441 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2442 #if ENABLE(CONTEXT_MENUS)
2443 if (isContextClick(platformMouseEvent))
2444 handled = handleContextMenuEvent(platformMouseEvent, page);
2448 case PlatformEvent::MouseReleased:
2449 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2451 case PlatformEvent::MouseMoved:
2453 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2454 // button is currently pressed. It is possible that neither of those things will be true since on
2455 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2456 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2457 // efficient scrollbars-only version of the event.
2458 if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2459 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2461 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2463 case PlatformEvent::MouseForceChanged:
2464 case PlatformEvent::MouseForceDown:
2465 case PlatformEvent::MouseForceUp:
2466 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2469 ASSERT_NOT_REACHED();
2474 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2476 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2478 m_userActivityHysteresis.impulse();
2480 bool shouldHandleEvent = true;
2482 #if ENABLE(CONTEXT_MENUS)
2483 // Don't try to handle any pending mouse events if a context menu is showing.
2484 if (m_isShowingContextMenu)
2485 shouldHandleEvent = false;
2487 #if ENABLE(DRAG_SUPPORT)
2488 if (m_isStartingDrag)
2489 shouldHandleEvent = false;
2492 if (!shouldHandleEvent) {
2493 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2497 bool handled = false;
2499 #if !PLATFORM(IOS_FAMILY)
2500 if (!handled && m_headerBanner)
2501 handled = m_headerBanner->mouseEvent(mouseEvent);
2502 if (!handled && m_footerBanner)
2503 handled = m_footerBanner->mouseEvent(mouseEvent);
2504 #endif // !PLATFORM(IOS_FAMILY)
2507 CurrentEvent currentEvent(mouseEvent);
2508 handled = handleMouseEvent(mouseEvent, this);
2511 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2514 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2516 Frame& frame = page->mainFrame();
2520 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2521 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2524 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2526 m_userActivityHysteresis.impulse();
2528 CurrentEvent currentEvent(wheelEvent);
2530 bool handled = handleWheelEvent(wheelEvent, m_page.get());
2532 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2535 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2537 if (!page->mainFrame().view())
2540 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2541 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2542 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2545 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2547 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2549 m_userActivityHysteresis.impulse();
2551 CurrentEvent currentEvent(keyboardEvent);
2553 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2554 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2556 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2558 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2561 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2563 bool isEnabled = false;
2565 Frame& frame = m_page->focusController().focusedOrMainFrame();
2566 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2567 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2569 Editor::Command command = frame.editor().command(commandName);
2570 state = command.state();
2571 isEnabled = command.isSupported() && command.isEnabled();
2574 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2577 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2579 executeEditingCommand(commandName, argument);
2582 void WebPage::setNeedsFontAttributes(bool needsFontAttributes)
2584 if (m_needsFontAttributes == needsFontAttributes)
2587 m_needsFontAttributes = needsFontAttributes;
2589 if (m_needsFontAttributes)
2590 sendPartialEditorStateAndSchedulePostLayoutUpdate();
2593 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest, WebBackForwardListProxy::OverwriteExistingItem overwrite)
2595 for (const auto& itemState : itemStates) {
2596 auto historyItem = toHistoryItem(itemState);
2597 historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2598 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, overwrite);
2602 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2604 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes, WebBackForwardListProxy::OverwriteExistingItem::No);
2607 void WebPage::updateBackForwardListForReattach(const Vector<WebKit::BackForwardListItemState>& itemStates)
2609 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2612 void WebPage::setCurrentHistoryItemForReattach(WebKit::BackForwardListItemState&& itemState)
2614 auto historyItem = toHistoryItem(itemState);
2615 auto& historyItemRef = historyItem.get();
2616 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2617 corePage()->mainFrame().loader().history().setCurrentItem(historyItemRef);
2620 void WebPage::requestFontAttributesAtSelectionStart(CallbackID callbackID)
2622 auto attributes = m_page->focusController().focusedOrMainFrame().editor().fontAttributesAtSelectionStart();
2623 send(Messages::WebPageProxy::FontAttributesCallback(attributes, callbackID));
2626 #if ENABLE(TOUCH_EVENTS)
2627 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2629 if (!page->mainFrame().view())
2632 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2636 #if ENABLE(IOS_TOUCH_EVENTS)
2637 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2639 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2641 m_lastInteractionLocation = touchEvent.position();
2642 CurrentEvent currentEvent(touchEvent);
2643 handled = handleTouchEvent(touchEvent, m_page.get());
2644 updatePotentialTapSecurityOrigin(touchEvent, handled);
2647 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2649 EventDispatcher::TouchEventQueue queuedEvents;
2650 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2651 dispatchAsynchronousTouchEvents(queuedEvents);
2653 dispatchTouchEvent(touchEvent, handled);
2656 void WebPage::updatePotentialTapSecurityOrigin(const WebTouchEvent& touchEvent, bool wasHandled)
2661 if (!touchEvent.isPotentialTap())
2664 if (touchEvent.type() != WebEvent::TouchStart)
2667 auto& mainFrame = m_page->mainFrame();
2668 auto document = mainFrame.document();
2672 if (!document->handlingTouchEvent())
2675 Frame* touchEventTargetFrame = &mainFrame;
2676 while (auto subframe = touchEventTargetFrame->eventHandler().touchEventTargetSubframe())
2677 touchEventTargetFrame = subframe;
2679 auto& touches = touchEventTargetFrame->eventHandler().touches();
2680 if (touches.isEmpty())
2683 ASSERT(touches.size() == 1);
2685 if (auto targetDocument = touchEventTargetFrame->document())
2686 m_potentialTapSecurityOrigin = &targetDocument->securityOrigin();
2688 #elif ENABLE(TOUCH_EVENTS)
2689 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2691 CurrentEvent currentEvent(touchEvent);
2693 bool handled = handleTouchEvent(touchEvent, m_page.get());
2695 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2699 #if ENABLE(MAC_GESTURE_EVENTS)
2700 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2702 if (!page->mainFrame().view())
2705 return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2708 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2710 CurrentEvent currentEvent(gestureEvent);
2711 bool handled = handleGestureEvent(gestureEvent, m_page.get());
2712 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2716 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2718 return page->userInputBridge().scrollRecursively(direction, granularity);
2721 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2723 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2726 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2728 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2731 void WebPage::centerSelectionInVisibleArea()
2733 Frame& frame = m_page->focusController().focusedOrMainFrame();
2734 frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2735 findController().showFindIndicatorInSelection();
2738 bool WebPage::isControlledByAutomation() const
2740 return m_page->isControlledByAutomation();
2743 void WebPage::setControlledByAutomation(bool controlled)
2745 m_page->setControlledByAutomation(controlled);
2748 void WebPage::insertNewlineInQuotedContent()
2750 Frame& frame = m_page->focusController().focusedOrMainFrame();
2751 if (frame.selection().isNone())
2753 frame.editor().insertParagraphSeparatorInQuotedContent();
2756 #if ENABLE(REMOTE_INSPECTOR)
2757 void WebPage::setAllowsRemoteInspection(bool allow)
2759 m_page->setRemoteInspectionAllowed(allow);
2762 void WebPage::setRemoteInspectionNameOverride(const String& name)
2764 m_page->setRemoteInspectionNameOverride(name);
2768 void WebPage::setDrawsBackground(bool drawsBackground)
2770 if (m_drawsBackground == drawsBackground)
2773 m_drawsBackground = drawsBackground;
2775 if (FrameView* frameView = mainFrameView()) {
2776 Color backgroundColor = drawsBackground ? Color::white : Color::transparent;
2777 bool isTransparent = !drawsBackground;
2778 frameView->updateBackgroundRecursively(backgroundColor, isTransparent);
2781 m_drawingArea->pageBackgroundTransparencyChanged();
2782 m_drawingArea->setNeedsDisplay();
2786 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
2788 if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
2789 LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
2793 m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
2795 setTopContentInset(contentInset);
2797 deallocateSendRightSafely(fencePort.port());
2801 void WebPage::setTopContentInset(float contentInset)
2803 if (contentInset == m_page->topContentInset())
2806 m_page->setTopContentInset(contentInset);
2808 for (auto* pluginView : m_pluginViews)
2809 pluginView->topContentInsetDidChange();
2812 void WebPage::viewWillStartLiveResize()
2817 // FIXME: This should propagate to all ScrollableAreas.
2818 Frame& frame = m_page->focusController().focusedOrMainFrame();
2819 if (FrameView* view = frame.view())
2820 view->willStartLiveResize();
2823 void WebPage::viewWillEndLiveResize()
2828 // FIXME: This should propagate to all ScrollableAreas.
2829 Frame& frame = m_page->focusController().focusedOrMainFrame();
2830 if (FrameView* view = frame.view())
2831 view->willEndLiveResize();
2834 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
2839 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2841 Frame& frame = m_page->focusController().focusedOrMainFrame();
2842 frame.document()->setFocusedElement(0);
2844 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2845 PlatformKeyboardEvent platformEvent(platform(event));
2846 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2847 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
2849 send(Messages::WebPageProxy::VoidCallback(callbackID));
2853 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
2854 send(Messages::WebPageProxy::VoidCallback(callbackID));
2857 void WebPage::setCanStartMediaTimerFired()
2860 m_page->setCanStartMedia(true);
2863 void WebPage::updateIsInWindow(bool isInitialState)
2865 bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
2868 m_setCanStartMediaTimer.stop();
2869 m_page->setCanStartMedia(false);
2871 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2872 if (!isInitialState)
2873 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2875 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2876 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2877 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2878 if (m_mayStartMediaWhenInWindow)
2879 m_setCanStartMediaTimer.startOneShot(0_s);
2881 WebProcess::singleton().pageDidEnterWindow(m_pageID);
2888 void WebPage::visibilityDidChange()
2890 bool isVisible = m_activityState.contains(ActivityState::IsVisible);
2892 // We save the document / scroll state when backgrounding a tab so that we are able to restore it
2893 // if it gets terminated while in the background.
2894 if (auto* frame = m_mainFrame->coreFrame())
2895 frame->loader().history().saveDocumentAndScrollState();
2899 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
2901 LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
2903 auto changed = m_activityState ^ activityState;
2904 m_activityState = activityState;
2907 updateThrottleState();
2910 SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
2911 m_page->setActivityState(activityState);
2914 for (auto* pluginView : m_pluginViews)
2915 pluginView->activityStateDidChange(changed);
2917 m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
2918 WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
2920 if (changed & ActivityState::IsInWindow)
2923 if (changed & ActivityState::IsVisible)
2924 visibilityDidChange();
2927 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
2929 m_layerHostingMode = layerHostingMode;
2931 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2933 for (auto* pluginView : m_pluginViews)
2934 pluginView->setLayerHostingMode(m_layerHostingMode);
2937 void WebPage::setSessionID(PAL::SessionID sessionID)
2939 if (sessionID.isEphemeral())
2940 WebProcess::singleton().addWebsiteDataStore(WebsiteDataStoreParameters::privateSessionParameters(sessionID));
2941 m_page->setSessionID(sessionID);
2944 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, std::optional<WebsitePoliciesData>&& websitePolicies)
2946 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2949 if (policyAction == PolicyAction::Suspend) {
2950 ASSERT(frame == m_mainFrame);
2951 setIsSuspended(true);
2953 WebProcess::singleton().sendPrewarmInformation(mainWebFrame()->url());
2955 frame->didReceivePolicyDecision(listenerID, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
2958 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
2960 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2963 frame->continueWillSubmitForm(listenerID);
2966 void WebPage::didStartPageTransition()
2968 setLayerTreeStateIsFrozen(true);
2971 bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
2973 m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
2974 m_isAssistingNodeDueToUserInteraction = false;
2975 m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
2977 if (hasPreviouslyFocusedDueToUserInteraction)
2978 send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
2979 if (m_needsHiddenContentEditableQuirk) {
2980 m_needsHiddenContentEditableQuirk = false;
2981 send(Messages::WebPageProxy::SetNeedsHiddenContentEditableQuirk(m_needsHiddenContentEditableQuirk));
2983 if (m_needsPlainTextQuirk) {
2984 m_needsPlainTextQuirk = false;
2985 send(Messages::WebPageProxy::SetNeedsPlainTextQuirk(m_needsPlainTextQuirk));
2990 void WebPage::didCompletePageTransition()
2992 // FIXME: Layer tree freezing should be managed entirely in the UI process side.
2993 setLayerTreeStateIsFrozen(false);
2995 bool isInitialEmptyDocument = !m_mainFrame;
2996 send(Messages::WebPageProxy::DidCompletePageTransition(isInitialEmptyDocument));
2999 void WebPage::show()
3001 send(Messages::WebPageProxy::ShowPage());
3004 String WebPage::userAgent(const URL& webCoreURL) const
3006 return userAgent(nullptr, webCoreURL);
3009 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
3012 String userAgent = m_loaderClient->userAgentForURL(*frame, webcoreURL);
3013 if (!userAgent.isEmpty())
3017 String userAgent = platformUserAgent(webcoreURL);
3018 if (!userAgent.isEmpty())
3023 void WebPage::setUserAgent(const String& userAgent)
3025 if (m_userAgent == userAgent)
3028 m_userAgent = userAgent;
3031 m_page->userAgentChanged();
3034 void WebPage::suspendActiveDOMObjectsAndAnimations()
3036 m_page->suspendActiveDOMObjectsAndAnimations();
3039 void WebPage::resumeActiveDOMObjectsAndAnimations()
3041 m_page->resumeActiveDOMObjectsAndAnimations();
3044 IntPoint WebPage::screenToRootView(const IntPoint& point)
3046 IntPoint windowPoint;
3047 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
3051 IntRect WebPage::rootViewToScreen(const IntRect& rect)
3054 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
3058 #if PLATFORM(IOS_FAMILY)
3059 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
3061 IntPoint windowPoint;
3062 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
3066 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
3069 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
3074 KeyboardUIMode WebPage::keyboardUIMode()
3076 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
3077 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
3080 void WebPage::runJavaScript(const String& script, bool forceUserGesture, std::optional<String> worldName, CallbackID callbackID)
3082 // NOTE: We need to be careful when running scripts that the objects we depend on don't
3083 // disappear during script execution.
3085 RefPtr<SerializedScriptValue> serializedResultValue;
3086 JSLockHolder lock(commonVM());
3087 bool hadException = true;
3088 ExceptionDetails details;
3089 auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
3091 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
3092 hadException = false;
3093 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
3094 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
3098 IPC::DataReference dataReference;
3099 if (serializedResultValue)
3100 dataReference = serializedResultValue->data();
3101 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
3104 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
3106 runJavaScript(script, forceUserGesture, std::nullopt, callbackID);
3109 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
3111 runJavaScript(script, forceUserGesture, worldName, callbackID);
3114 void WebPage::getContentsAsString(CallbackID callbackID)
3116 String resultString = m_mainFrame->contentsAsString();
3117 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3121 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
3123 send(Messages::WebPageProxy::DataCallback({ MHTMLArchive::generateMHTMLData(m_page.get()) }, callbackID));
3127 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3129 String resultString = renderTreeExternalRepresentation();
3130 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3133 static Frame* frameWithSelection(Page* page)
3135 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3136 if (frame->selection().isRange())
3143 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3146 RetainPtr<CFDataRef> data;
3147 if (Frame* frame = frameWithSelection(m_page.get()))
3148 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3151 IPC::SharedBufferDataReference dataReference;
3154 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3156 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3159 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3161 WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3162 String resultString = focusedOrMainFrame->selectionAsString();
3163 if (resultString.isEmpty())
3164 resultString = focusedOrMainFrame->contentsAsString();
3165 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3168 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3170 String resultString;
3171 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3172 resultString = frame->source();
3174 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3177 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3179 RefPtr<SharedBuffer> buffer;
3180 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3181 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3182 buffer = pluginView->liveResourceData();
3184 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3185 buffer = loader->mainResourceData();
3189 IPC::SharedBufferDataReference dataReference;
3191 dataReference = { *buffer };
3192 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3195 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3197 DocumentLoader* loader = frame->loader().documentLoader();
3201 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3205 return &subresource->data();
3208 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3210 RefPtr<SharedBuffer> buffer;
3211 if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3212 URL resourceURL(URL(), resourceURLString);
3213 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3216 IPC::SharedBufferDataReference dataReference;
3218 dataReference = { *buffer };
3219 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3222 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3225 RetainPtr<CFDataRef> data;
3226 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3227 data = frame->webArchiveData(nullptr, nullptr);
3229 UNUSED_PARAM(frameID);
3232 IPC::SharedBufferDataReference dataReference;
3235 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3237 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3240 void WebPage::forceRepaintWithoutCallback()
3242 m_drawingArea->forceRepaint();
3245 void WebPage::forceRepaint(CallbackID callbackID)
3247 if (m_drawingArea->forceRepaintAsync(callbackID))
3250 forceRepaintWithoutCallback();
3251 send(Messages::WebPageProxy::VoidCallback(callbackID));
3254 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3256 WebPreferencesStore::removeTestRunnerOverrides();
3257 updatePreferences(store);
3260 void WebPage::updatePreferences(const WebPreferencesStore& store)
3262 updatePreferencesGenerated(store);
3264 Settings& settings = m_page->settings();
3266 bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3267 settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3268 settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3269 settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3270 settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3271 settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3272 settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3273 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3274 settings.setFrameFlattening(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()) ? WebCore::FrameFlattening::FullyEnabled : WebCore::FrameFlattening::Disabled);
3275 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3276 #if ENABLE(DATA_DETECTION)
3277 settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3280 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3282 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3283 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3284 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3285 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3287 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3288 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3290 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3291 setSessionID(PAL::SessionID::legacyPrivateSessionID());
3292 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3293 setSessionID(PAL::SessionID::defaultSessionID());
3295 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3296 if (m_processSuppressionEnabled != processSuppressionEnabled) {
3297 m_processSuppressionEnabled = processSuppressionEnabled;
3298 updateThrottleState();
3302 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3304 #if ENABLE(PAYMENT_REQUEST)
3305 settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3308 // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3309 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3311 #if PLATFORM(IOS_FAMILY)
3312 m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3313 m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3314 setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3316 settings.setUseImageDocumentForSubframePDF(true);
3318 DeprecatedGlobalSettings::setAVKitEnabled(true);
3322 #if ENABLE(SERVICE_WORKER)
3323 if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3324 ASSERT(parentProcessHasServiceWorkerEntitlement());
3325 if (!parentProcessHasServiceWorkerEntitlement())
3326 RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3330 settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3333 m_drawingArea->updatePreferences(store);
3336 #if ENABLE(DATA_DETECTION)
3337 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3339 DataDetectionResult dataDetectionResult;
3340 dataDetectionResult.results = detectionResults;
3341 send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3346 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3348 FrameView* frameView = corePage()->mainFrame().view();
3352 layerTransaction.setContentsSize(frameView->contentsSize());
3353 layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3354 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3355 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3356 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3358 layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3359 layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3360 layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3362 #if PLATFORM(IOS_FAMILY)
3363 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3364 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3365 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3366 layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3367 layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3368 layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3369 layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3370 layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3371 layerTransaction.setIsInStableState(m_isInStableState);
3372 layerTransaction.setAllowsUserScaling(allowsUserScaling());
3373 if (m_pendingDynamicViewportSizeUpdateID) {
3374 layerTransaction.setDynamicViewportSizeUpdateID(*m_pendingDynamicViewportSizeUpdateID);
3375 m_pendingDynamicViewportSizeUpdateID = std::nullopt;
3377 if (m_lastTransactionPageScaleFactor != layerTransaction.pageScaleFactor()) {
3378 m_lastTransactionPageScaleFactor = layerTransaction.pageScaleFactor();
3379 m_lastTransactionIDWithScaleChange = layerTransaction.transactionID();
3383 layerTransaction.setScrollPosition(frameView->scrollPosition());
3385 if (m_hasPendingEditorStateUpdate) {
3386 layerTransaction.setEditorState(editorState());
3387 m_hasPendingEditorStateUpdate = false;
3391 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3393 #if PLATFORM(IOS_FAMILY)
3394 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3395 Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3396 m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3398 m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3401 UNUSED_PARAM(timestamp);
3406 void WebPage::willDisplayPage()
3408 m_page->willDisplayPage();
3411 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3415 if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3416 m_inspector = WebInspector::create(this);
3417 return m_inspector.get();
3420 WebInspectorUI* WebPage::inspectorUI()
3425 m_inspectorUI = WebInspectorUI::create(*this);
3426 return m_inspectorUI.get();
3429 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3433 if (!m_remoteInspectorUI)
3434 m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3435 return m_remoteInspectorUI.get();
3438 void WebPage::inspectorFrontendCountChanged(unsigned count)
3440 send(Messages::WebPageProxy::DidChangeInspectorFrontendCount(count));
3443 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3444 PlaybackSessionManager& WebPage::playbackSessionManager()
3446 if (!m_playbackSessionManager)
3447 m_playbackSessionManager = PlaybackSessionManager::create(*this);
3448 return *m_playbackSessionManager;
3451 VideoFullscreenManager& WebPage::videoFullscreenManager()
3453 if (!m_videoFullscreenManager)
3454 m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3455 return *m_videoFullscreenManager;
3458 void WebPage::videoControlsManagerDidChange()
3460 #if ENABLE(FULLSCREEN_API)
3461 if (auto* manager = fullScreenManager())
3462 manager->videoControlsManagerDidChange();
3468 #if PLATFORM(IOS_FAMILY)
3469 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3471 m_page->setAllowsMediaDocumentInlinePlayback(allows);
3475 #if ENABLE(FULLSCREEN_API)
3476 WebFullScreenManager* WebPage::fullScreenManager()
3478 if (!m_fullScreenManager)
3479 m_fullScreenManager = WebFullScreenManager::create(this);
3480 return m_fullScreenManager.get();
3484 void WebPage::addConsoleMessage(uint64_t frameID, MessageSource messageSource, MessageLevel messageLevel, const String& message, uint64_t requestID)
3486 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3487 frame->addConsoleMessage(messageSource, messageLevel, message, requestID);
3490 void WebPage::sendCSPViolationReport(uint64_t frameID, const WebCore::URL& reportURL, IPC::FormDataReference&& reportData)
3492 auto report = reportData.takeData();
3495 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3496 PingLoader::sendViolationReport(*frame->coreFrame(), reportURL, report.releaseNonNull(), ViolationReportType::ContentSecurityPolicy);
3499 void WebPage::enqueueSecurityPolicyViolationEvent(uint64_t frameID, SecurityPolicyViolationEvent::Init&& eventInit)
3501 auto* frame = WebProcess::singleton().webFrame(frameID);
3504 auto* coreFrame = frame->coreFrame();
3507 if (auto* document = coreFrame->document())
3508 document->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
3511 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3513 if (m_notificationPermissionRequestManager)
3514 return m_notificationPermissionRequestManager.get();
3516 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3517 return m_notificationPermissionRequestManager.get();
3520 #if ENABLE(DRAG_SUPPORT)
3523 void WebPage::performDragControllerAction(DragControllerAction action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3526 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3530 DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3532 case DragControllerAction::Entered: {
3533 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3534 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }));
3537 case DragControllerAction::Updated: {
3538 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3539 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }));
3542 case DragControllerAction::Exited:
3543 m_page->dragController().dragExited(dragData);
3546 case DragControllerAction::PerformDragOperation: {
3547 m_page->dragController().performDragOperation(dragData);
3551 ASSERT_NOT_REACHED();
3554 void WebPage::performDragControllerAction(DragControllerAction action, const WebCore::DragData& dragData, SandboxExtension::Handle&& sandboxExtensionHandle, SandboxExtension::HandleArray&& sandboxExtensionsHandleArray)
3557 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3562 case DragControllerAction::Entered: {
3563 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3564 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), m_page->dragCaretController().caretRectInRootViewCoordinates()));
3567 case DragControllerAction::Updated: {
3568 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3569 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), m_page->dragCaretController().caretRectInRootViewCoordinates()));
3572 case DragControllerAction::Exited:
3573 m_page->dragController().dragExited(dragData);
3574 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3577 case DragControllerAction::PerformDragOperation: {
3578 ASSERT(!m_pendingDropSandboxExtension);
3580 m_pendingDropSandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
3581 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3582 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(WTFMove(sandboxExtensionsHandleArray[i])))
3583 m_pendingDropExtensionsForFileUpload.append(extension);
3586 bool handled = m_page->dragController().performDragOperation(dragData);
3588 // If we started loading a local file, the sandbox extension tracker would have adopted this
3589 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3590 m_pendingDropSandboxExtension = nullptr;
3592 m_pendingDropExtensionsForFileUpload.clear();
3593 send(Messages::WebPageProxy::DidPerformDragOperation(handled));
3597 ASSERT_NOT_REACHED();
3601 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3603 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3604 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3606 m_page->dragController().dragEnded();
3607 FrameView* view = m_page->mainFrame().view();
3610 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3611 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), 0, WebCore::NoTap);
3612 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3614 send(Messages::WebPageProxy::DidEndDragging());
3617 void WebPage::willPerformLoadDragDestinationAction()
3619 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(WTFMove(m_pendingDropSandboxExtension));
3622 void WebPage::mayPerformUploadDragDestinationAction()
3624 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3625 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3626 m_pendingDropExtensionsForFileUpload.clear();
3629 void WebPage::didStartDrag()
3631 m_isStartingDrag = false;
3632 m_page->mainFrame().eventHandler().didStartDrag();
3635 void WebPage::dragCancelled()
3637 m_isStartingDrag = false;
3638 m_page->mainFrame().eventHandler().dragCancelled();
3641 #endif // ENABLE(DRAG_SUPPORT)
3643 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3645 return m_undoStepMap.get(stepID);
3648 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3650 m_undoStepMap.set(stepID, entry);
3653 void WebPage::removeWebEditCommand(uint64_t stepID)
3655 m_undoStepMap.remove(stepID);
3658 bool WebPage::isAlwaysOnLoggingAllowed() const
3660 return corePage() && corePage()->isAlwaysOnLoggingAllowed();
3663 void WebPage::unapplyEditCommand(uint64_t stepID)
3665 WebUndoStep* step = webUndoStep(stepID);
3669 step->step().unapply();
3672 void WebPage::reapplyEditCommand(uint64_t stepID)
3674 WebUndoStep* step = webUndoStep(stepID);
3679 step->step().reapply();
3683 void WebPage::didRemoveEditCommand(uint64_t commandID)
3685 removeWebEditCommand(commandID);
3688 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3690 m_activePopupMenu = menu;
3693 #if ENABLE(INPUT_TYPE_COLOR)
3695 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3697 m_activeColorChooser = colorChooser;
3700 void WebPage::didEndColorPicker()
3702 m_activeColorChooser->didEndChooser();
3705 void WebPage::didChooseColor(const WebCore::Color& color)
3707 m_activeColorChooser->didChooseColor(color);
3712 #if ENABLE(DATALIST_ELEMENT)
3714 void WebPage::setActiveDataListSuggestionPicker(WebDataListSuggestionPicker* dataListSuggestionPicker)
3716 m_activeDataListSuggestionPicker = dataListSuggestionPicker;
3719 void WebPage::didSelectDataListOption(const String& selectedOption)
3721 m_activeDataListSuggestionPicker->didSelectOption(selectedOption);
3724 void WebPage::didCloseSuggestions()
3726 if (m_activeDataListSuggestionPicker)
3727 m_activeDataListSuggestionPicker->didCloseSuggestions();
3728 m_activeDataListSuggestionPicker = nullptr;
3733 void WebPage::setActiveOpenPanelResultListener(Ref<WebOpenPanelResultListener>&& openPanelResultListener)
3735 m_activeOpenPanelResultListener = WTFMove(openPanelResultListener);
3738 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3740 return m_page->findString(target, core(options));
3743 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3745 findController().findString(string, static_cast<FindOptions>(options), maxMatchCount);
3748 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3750 findController().findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3753 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3755 findController().getImageForFindMatch(matchIndex);
3758 void WebPage::selectFindMatch(uint32_t matchIndex)
3760 findController().selectFindMatch(matchIndex);
3763 void WebPage::hideFindUI()
3765 findController().hideFindUI();
3768 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3770 findController().countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3773 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3775 changeSelectedIndex(newIndex);
3776 m_activePopupMenu = nullptr;
3779 void WebPage::changeSelectedIndex(int32_t index)
3781 if (!m_activePopupMenu)
3784 m_activePopupMenu->didChangeSelectedIndex(index);
3787 #if PLATFORM(IOS_FAMILY)
3788 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3790 if (!m_activeOpenPanelResultListener)
3794 if (!iconData.isEmpty()) {
3795 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3796 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3797 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3798 icon = Icon::createIconForImage(imageRef.get());
3801 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3802 m_activeOpenPanelResultListener = nullptr;
3806 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3808 if (!m_activeOpenPanelResultListener)
3811 m_activeOpenPanelResultListener->didChooseFiles(files);
3812 m_activeOpenPanelResultListener = nullptr;
3815 void WebPage::didCancelForOpenPanel()
3817 m_activeOpenPanelResultListener = nullptr;
3820 #if ENABLE(SANDBOX_EXTENSIONS)
3821 void WebPage::extendSandboxForFilesFromOpenPanel(SandboxExtension::HandleArray&& handles)
3823 for (size_t i = 0; i < handles.size(); ++i) {
3824 bool result = SandboxExtension::consumePermanently(handles[i]);
3826 // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3827 WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3833 #if ENABLE(GEOLOCATION)
3834 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3836 geolocationPermissionRequestManager().didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3840 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3842 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3845 #if ENABLE(MEDIA_STREAM)
3847 #if !PLATFORM(IOS_FAMILY)
3848 void WebPage::prepareToSendUserMediaPermissionRequest()
3853 void WebPage::userMediaAccessWasGranted(uint64_t userMediaID, WebCore::CaptureDevice&& audioDevice, WebCore::CaptureDevice&& videoDevice, String&& mediaDeviceIdentifierHashSalt)
3855 m_userMediaPermissionRequestManager->userMediaAccessWasGranted(userMediaID, WTFMove(audioDevice), WTFMove(videoDevice), WTFMove(mediaDeviceIdentifierHashSalt));
3858 void WebPage::userMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String&& invalidConstraint)
3860 m_userMediaPermissionRequestManager->userMediaAccessWasDenied(userMediaID, static_cast<UserMediaRequest::MediaAccessDenialReason>(reason), WTFMove(invalidConstraint));
3863 void WebPage::didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vector<CaptureDevice>& devices, String&& deviceIdentifierHashSalt, bool originHasPersistentAccess)
3865 m_userMediaPermissionRequestManager->didCompleteMediaDeviceEnumeration(userMediaID, devices, WTFMove(deviceIdentifierHashSalt), originHasPersistentAccess);
3868 void WebPage::captureDevicesChanged(DeviceAccessState accessState)
3870 m_userMediaPermissionRequestManager->captureDevicesChanged(accessState);
3873 #if ENABLE(SANDBOX_EXTENSIONS)
3874 void WebPage::grantUserMediaDeviceSandboxExtensions(MediaDeviceSandboxExtensions&& extensions)
3876 m_userMediaPermissionRequestManager->grantUserMediaDeviceSandboxExtensions(WTFMove(extensions));
3879 void WebPage::revokeUserMediaDeviceSandboxExtensions(const Vector<String>& extensionIDs)
3881 m_userMediaPermissionRequestManager->revokeUserMediaDeviceSandboxExtensions(extensionIDs);
3886 #if !PLATFORM(IOS_FAMILY)
3887 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3889 Frame& frame = m_page->focusController().focusedOrMainFrame();
3890 frame.editor().advanceToNextMisspelling(startBeforeSelection);
3894 bool WebPage::hasRichlyEditableSelection() const
3896 auto& frame = m_page->focusController().focusedOrMainFrame();
3897 if (m_page->dragCaretController().isContentRichlyEditable())
3900 return frame.selection().selection().isContentRichlyEditable();
3903 void WebPage::changeSpellingToWord(const String& word)
3905 replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3908 void WebPage::unmarkAllMisspellings()
3910 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3911 if (Document* document = frame->document())
3912 document->markers().removeMarkers(DocumentMarker::Spelling);
3916 void WebPage::unmarkAllBadGrammar()
3918 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3919 if (Document* document = frame->document())
3920 document->markers().removeMarkers(DocumentMarker::Grammar);
3925 void WebPage::uppercaseWord()
3927 m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3930 void WebPage::lowercaseWord()
3932 m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3935 void WebPage::capitalizeWord()
3937 m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3941 void WebPage::setTextForActivePopupMenu(int32_t index)
3943 if (!m_activePopupMenu)
3946 m_activePopupMenu->setTextForIndex(index);
3950 void WebPage::failedToShowPopupMenu()
3952 if (!m_activePopupMenu)
3955 m_activePopupMenu->client()->popupDidHide();
3959 #if ENABLE(CONTEXT_MENUS)
3960 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3965 m_contextMenu->itemSelected(item);
3966 m_contextMenu = nullptr;
3970 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3972 bool selectReplacement = true;
3973 bool smartReplace = false;
3974 return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3977 #if !PLATFORM(IOS_FAMILY)
3978 void WebPage::clearSelection()
3980 m_page->focusController().focusedOrMainFrame().selection().clear();
3984 void WebPage::restoreSelectionInFocusedEditableElement()
3986 Frame& frame = m_page->focusController().focusedOrMainFrame();
3987 if (!frame.selection().isNone())
3990 if (auto document = frame.document()) {
3991 if (auto element = document->focusedElement())
3992 element->updateFocusAppearance(SelectionRestorationMode::Restore, SelectionRevealMode::DoNotReveal);
3996 bool WebPage::mainFrameHasCustomContentProvider() const
3998 if (Frame* frame = mainFrame()) {
3999 WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
4000 ASSERT(webFrameLoaderClient);
4001 return webFrameLoaderClient->frameHasCustomContentProvider();
4007 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
4009 m_mimeTypesWithCustomContentProviders.add(mimeType);
4012 void WebPage::updateMainFrameScrollOffsetPinning()
4014 Frame& frame = m_page->mainFrame();
4015 ScrollPosition scrollPosition = frame.view()->scrollPosition();
4016 ScrollPosition maximumScrollPosition = frame.view()->maximumScrollPosition();
4017 ScrollPosition minimumScrollPosition = frame.view()->minimumScrollPosition();
4019 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
4020 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
4021 bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
4022 bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
4024 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
4025 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
4027 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
4028 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
4029 m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
4030 m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
4034 void WebPage::mainFrameDidLayout()
4036 unsigned pageCount = m_page->pageCount();
4037 if (pageCount != m_cachedPageCount) {
4038 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
4039 m_cachedPageCount = pageCount;
4043 m_viewGestureGeometryCollector->mainFrameDidLayout();
4045 #if PLATFORM(IOS_FAMILY)
4046 if (FrameView* frameView = mainFrameView()) {
4047 IntSize newContentSize = frameView->contentsSize();
4048 LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " mainFrameDidLayout setting content size to " << newContentSize);
4049 if (m_viewportConfiguration.setContentsSize(newContentSize))
4050 viewportConfigurationChanged();
4052 findController().redraw();
4056 void WebPage::addPluginView(PluginView* pluginView)
4058 ASSERT(!m_pluginViews.contains(pluginView));
4060 m_pluginViews.add(pluginView);
4061 m_hasSeenPlugin = true;
4062 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
4063 LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
4064 m_determinePrimarySnapshottedPlugInTimer.startOneShot(0_s);
4068 void WebPage::removePluginView(PluginView* pluginView)
4070 ASSERT(m_pluginViews.contains(pluginView));
4072 m_pluginViews.remove(pluginView);
4073 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
4074 LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
4078 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
4081 m_hasCachedWindowFrame = false;
4083 send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
4087 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
4089 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
4090 m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
4091 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
4092 m_accessibilityPosition = accessibilityViewCoordinates;
4094 // Tell all our plug-in views that the window and view frames have changed.
4095 for (auto* pluginView : m_pluginViews)
4096 pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
4098 m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
4102 void WebPage::setMainFrameIsScrollable(bool isScrollable)
4104 m_mainFrameIsScrollable = isScrollable;
4105 m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
4107 if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
4108 frameView->setCanHaveScrollbars(isScrollable);
4109 frameView->setProhibitsScrolling(!isScrollable);
4113 bool WebPage::windowIsFocused() const
4115 return m_page->focusController().isActive();
4118 bool WebPage::windowAndWebPageAreFocused() const
4123 return m_page->focusController().isFocused() && m_page->focusController().isActive();
4126 void WebPage::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
4128 if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
4129 if (WebInspector* inspector = this->inspector())
4130 inspector->didReceiveMessage(connection, decoder);
4134 if (decoder.messageReceiverName() == Messages::WebInspectorUI::messageReceiverName()) {
4135 if (WebInspectorUI* inspectorUI = this->inspectorUI())
4136 inspectorUI->didReceiveMessage(connection, decoder);
4140 if (decoder.messageReceiverName() == Messages::RemoteWebInspectorUI::messageReceiverName()) {
4141 if (RemoteWebInspectorUI* remoteInspectorUI = this->remoteInspectorUI())
4142 remoteInspectorUI->didReceiveMessage(connection, decoder);
4146 #if ENABLE(FULLSCREEN_API)
4147 if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
4148 fullScreenManager()->didReceiveMessage(connection, decoder);
4153 didReceiveWebPageMessage(connection, decoder);
4156 void WebPage::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
4158 didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
4161 #if ENABLE(ASYNC_SCROLLING)
4162 ScrollingCoordinator* WebPage::scrollingCoordinator() const
4164 return m_page->scrollingCoordinator();
4168 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
4173 void WebPage::SandboxExtensionTracker::invalidate()
4175 m_pendingProvisionalSandboxExtension = nullptr;
4177 if (m_provisionalSandboxExtension) {
4178 m_provisionalSandboxExtension->revoke();
4179 m_provisionalSandboxExtension = nullptr;
4182 if (m_committedSandboxExtension) {
4183 m_committedSandboxExtension->revoke();
4184 m_committedSandboxExtension = nullptr;