2 * Copyright (C) 2010-2019 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 "DataReference.h"
34 #include "DragControllerAction.h"
35 #include "DrawingArea.h"
36 #include "DrawingAreaMessages.h"
37 #include "EditorState.h"
38 #include "EventDispatcher.h"
39 #include "FindController.h"
40 #include "FormDataReference.h"
41 #include "GeolocationPermissionRequestManager.h"
42 #include "InjectUserScriptImmediately.h"
43 #include "InjectedBundle.h"
44 #include "InjectedBundleScriptWorld.h"
45 #include "LibWebRTCProvider.h"
46 #include "LoadParameters.h"
48 #include "NetscapePlugin.h"
49 #include "NetworkConnectionToWebProcessMessages.h"
50 #include "NetworkProcessConnection.h"
51 #include "NotificationPermissionRequestManager.h"
52 #include "PageBanner.h"
53 #include "PluginProcessAttributes.h"
54 #include "PluginProxy.h"
55 #include "PluginView.h"
56 #include "PrintInfo.h"
57 #include "RemoteWebInspectorUI.h"
58 #include "RemoteWebInspectorUIMessages.h"
59 #include "SessionState.h"
60 #include "SessionStateConversion.h"
61 #include "ShareSheetCallbackID.h"
62 #include "ShareableBitmap.h"
63 #include "SharedBufferDataReference.h"
64 #include "UserMediaPermissionRequestManager.h"
65 #include "ViewGestureGeometryCollector.h"
66 #include "VisitedLinkTableController.h"
67 #include "WKBundleAPICast.h"
68 #include "WKRetainPtr.h"
69 #include "WKSharedAPICast.h"
70 #include "WebAlternativeTextClient.h"
71 #include "WebBackForwardListItem.h"
72 #include "WebBackForwardListProxy.h"
73 #include "WebCacheStorageProvider.h"
74 #include "WebChromeClient.h"
75 #include "WebColorChooser.h"
76 #include "WebContextMenu.h"
77 #include "WebContextMenuClient.h"
78 #include "WebCookieJar.h"
79 #include "WebCoreArgumentCoders.h"
80 #include "WebDataListSuggestionPicker.h"
81 #include "WebDatabaseProvider.h"
82 #include "WebDiagnosticLoggingClient.h"
83 #include "WebDocumentLoader.h"
84 #include "WebDragClient.h"
85 #include "WebEditorClient.h"
87 #include "WebEventConversion.h"
88 #include "WebEventFactory.h"
90 #include "WebFrameLoaderClient.h"
91 #include "WebFullScreenManager.h"
92 #include "WebFullScreenManagerMessages.h"
93 #include "WebGamepadProvider.h"
94 #include "WebGeolocationClient.h"
96 #include "WebInspector.h"
97 #include "WebInspectorClient.h"
98 #include "WebInspectorMessages.h"
99 #include "WebInspectorUI.h"
100 #include "WebInspectorUIMessages.h"
101 #include "WebMediaKeyStorageManager.h"
102 #include "WebNotificationClient.h"
103 #include "WebOpenPanelResultListener.h"
104 #include "WebPageCreationParameters.h"
105 #include "WebPageGroupProxy.h"
106 #include "WebPageInspectorTargetController.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/HTMLTextAreaElement.h>
175 #include <WebCore/HTMLUListElement.h>
176 #include <WebCore/HistoryController.h>
177 #include <WebCore/HistoryItem.h>
178 #include <WebCore/HitTestResult.h>
179 #include <WebCore/InspectorController.h>
180 #include <WebCore/JSDOMExceptionHandling.h>
181 #include <WebCore/JSDOMWindow.h>
182 #include <WebCore/KeyboardEvent.h>
183 #include <WebCore/MIMETypeRegistry.h>
184 #include <WebCore/MouseEvent.h>
185 #include <WebCore/NotImplemented.h>
186 #include <WebCore/Page.h>
187 #include <WebCore/PageCache.h>
188 #include <WebCore/PageConfiguration.h>
189 #include <WebCore/PingLoader.h>
190 #include <WebCore/PlatformKeyboardEvent.h>
191 #include <WebCore/PlatformMediaSessionManager.h>
192 #include <WebCore/PluginDocument.h>
193 #include <WebCore/PointerCaptureController.h>
194 #include <WebCore/PrintContext.h>
195 #include <WebCore/PromisedAttachmentInfo.h>
196 #include <WebCore/Range.h>
197 #include <WebCore/RegistrableDomain.h>
198 #include <WebCore/RemoteDOMWindow.h>
199 #include <WebCore/RemoteFrame.h>
200 #include <WebCore/RenderLayer.h>
201 #include <WebCore/RenderTheme.h>
202 #include <WebCore/RenderTreeAsText.h>
203 #include <WebCore/RenderView.h>
204 #include <WebCore/ResourceLoadStatistics.h>
205 #include <WebCore/ResourceRequest.h>
206 #include <WebCore/ResourceResponse.h>
207 #include <WebCore/RuntimeEnabledFeatures.h>
208 #include <WebCore/SchemeRegistry.h>
209 #include <WebCore/ScriptController.h>
210 #include <WebCore/SerializedScriptValue.h>
211 #include <WebCore/ServiceWorkerProvider.h>
212 #include <WebCore/Settings.h>
213 #include <WebCore/ShadowRoot.h>
214 #include <WebCore/SharedBuffer.h>
215 #include <WebCore/StyleProperties.h>
216 #include <WebCore/SubframeLoader.h>
217 #include <WebCore/SubstituteData.h>
218 #include <WebCore/TextIterator.h>
219 #include <WebCore/UserGestureIndicator.h>
220 #include <WebCore/UserInputBridge.h>
221 #include <WebCore/UserScript.h>
222 #include <WebCore/UserStyleSheet.h>
223 #include <WebCore/UserTypingGestureIndicator.h>
224 #include <WebCore/VisiblePosition.h>
225 #include <WebCore/VisibleUnits.h>
226 #include <WebCore/WebGLStateTracker.h>
227 #include <WebCore/WritingDirection.h>
228 #include <WebCore/markup.h>
229 #include <pal/SessionID.h>
230 #include <wtf/ProcessID.h>
231 #include <wtf/RunLoop.h>
232 #include <wtf/SetForScope.h>
233 #include <wtf/text/TextStream.h>
235 #if ENABLE(DATA_DETECTION)
236 #include "DataDetectionResult.h"
240 #include <WebCore/MHTMLArchive.h>
243 #if ENABLE(POINTER_LOCK)
244 #include <WebCore/PointerLockController.h>
248 #include "PDFPlugin.h"
249 #include "PlaybackSessionManager.h"
250 #include "RemoteLayerTreeTransaction.h"
251 #include "TouchBarMenuData.h"
252 #include "TouchBarMenuItemData.h"
253 #include "VideoFullscreenManager.h"
254 #include "WKStringCF.h"
255 #include <WebCore/LegacyWebArchive.h>
256 #include <WebCore/UTIRegistry.h>
257 #include <wtf/MachSendRight.h>
261 #include "WebPrintOperationGtk.h"
262 #include "WebSelectionData.h"
266 #if PLATFORM(IOS_FAMILY)
267 #include "InteractionInformationAtPosition.h"
268 #include "InteractionInformationRequest.h"
269 #include "RemoteLayerTreeDrawingArea.h"
270 #include <CoreGraphics/CoreGraphics.h>
271 #include <WebCore/Icon.h>
272 #include <pal/spi/cocoa/CoreTextSPI.h>
276 #include <WebCore/LocalDefaultSystemAppearance.h>
277 #include <pal/spi/cf/CFUtilitiesSPI.h>
281 #include <wtf/RefCountedLeakCounter.h>
284 #if ENABLE(DATA_DETECTION)
285 #include <WebCore/DataDetection.h>
288 #if ENABLE(VIDEO) && USE(GSTREAMER)
289 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
292 #if ENABLE(WEB_AUTHN)
293 #include "WebAuthenticatorCoordinator.h"
294 #include <WebCore/AuthenticatorCoordinator.h>
299 using namespace WebCore;
301 static const Seconds pageScrollHysteresisDuration { 300_ms };
302 static const Seconds initialLayerVolatilityTimerInterval { 20_ms };
303 static const Seconds maximumLayerVolatilityTimerInterval { 2_s };
305 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
306 #define RELEASE_LOG_ERROR_IF_ALLOWED(...) RELEASE_LOG_ERROR_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
308 class SendStopResponsivenessTimer {
310 ~SendStopResponsivenessTimer()
312 WebProcess::singleton().parentProcessConnection()->send(Messages::WebProcessProxy::StopResponsivenessTimer(), 0);
316 class DeferredPageDestructor {
318 static void createDeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
320 new DeferredPageDestructor(WTFMove(page), webPage);
324 DeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
325 : m_page(WTFMove(page))
331 void tryDestruction()
333 if (m_page->insideNestedRunLoop()) {
334 m_page->whenUnnested([this] { tryDestruction(); });
343 std::unique_ptr<Page> m_page;
344 RefPtr<WebPage> m_webPage;
347 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
349 Ref<WebPage> WebPage::create(uint64_t pageID, WebPageCreationParameters&& parameters)
351 Ref<WebPage> page = adoptRef(*new WebPage(pageID, WTFMove(parameters)));
353 if (WebProcess::singleton().injectedBundle())
354 WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
359 WebPage::WebPage(uint64_t pageID, WebPageCreationParameters&& parameters)
361 , m_viewSize(parameters.viewSize)
362 , m_alwaysShowsHorizontalScroller { parameters.alwaysShowsHorizontalScroller }
363 , m_alwaysShowsVerticalScroller { parameters.alwaysShowsVerticalScroller }
364 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
365 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
367 , m_layerHostingMode(parameters.layerHostingMode)
368 #if PLATFORM(COCOA) || PLATFORM(GTK)
369 , m_viewGestureGeometryCollector(std::make_unique<ViewGestureGeometryCollector>(*this))
370 #elif HAVE(ACCESSIBILITY) && PLATFORM(GTK)
371 , m_accessibilityObject(nullptr)
373 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
374 #if ENABLE(CONTEXT_MENUS)
375 , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
377 , m_editorClient { std::make_unique<API::InjectedBundle::EditorClient>() }
378 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
379 , m_loaderClient(std::make_unique<API::InjectedBundle::PageLoaderClient>())
380 , m_resourceLoadClient(std::make_unique<API::InjectedBundle::ResourceLoadClient>())
381 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
382 , m_findController(makeUniqueRef<FindController>(this))
383 , m_inspectorTargetController(std::make_unique<WebPageInspectorTargetController>(*this))
384 , m_userContentController(WebUserContentController::getOrCreate(parameters.userContentControllerID))
385 #if ENABLE(GEOLOCATION)
386 , m_geolocationPermissionRequestManager(makeUniqueRef<GeolocationPermissionRequestManager>(*this))
388 #if ENABLE(MEDIA_STREAM)
389 , m_userMediaPermissionRequestManager { makeUniqueRef<UserMediaPermissionRequestManager>(*this) }
391 , m_pageScrolledHysteresis([this](PAL::HysteresisState state) { if (state == PAL::HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisDuration)
392 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
393 , m_canRunModal(parameters.canRunModal)
394 #if PLATFORM(IOS_FAMILY)
395 , m_forceAlwaysUserScalable(parameters.ignoresViewportScaleLimits)
396 , m_screenSize(parameters.screenSize)
397 , m_availableScreenSize(parameters.availableScreenSize)
398 , m_overrideScreenSize(parameters.overrideScreenSize)
399 , m_deviceOrientation(parameters.deviceOrientation)
401 , m_layerVolatilityTimer(*this, &WebPage::layerVolatilityTimerFired)
402 , m_activityState(parameters.activityState)
403 , m_processSuppressionEnabled(true)
404 , m_userActivity("Process suppression disabled for page.")
405 , m_userActivityHysteresis([this](PAL::HysteresisState) { updateUserActivity(); })
406 , m_userInterfaceLayoutDirection(parameters.userInterfaceLayoutDirection)
407 , m_overrideContentSecurityPolicy { parameters.overrideContentSecurityPolicy }
408 , m_cpuLimit(parameters.cpuLimit)
410 , m_hostFileDescriptor(WTFMove(parameters.hostFileDescriptor))
415 m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
417 #if PLATFORM(IOS_FAMILY)
418 DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(true);
421 PageConfiguration pageConfiguration(
422 makeUniqueRef<WebEditorClient>(this),
423 WebSocketProvider::create(),
424 makeUniqueRef<WebKit::LibWebRTCProvider>(),
425 WebProcess::singleton().cacheStorageProvider(),
426 WebBackForwardListProxy::create(*this),
427 WebCookieJar::create()
429 pageConfiguration.chromeClient = new WebChromeClient(*this);
430 #if ENABLE(CONTEXT_MENUS)
431 pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
433 #if ENABLE(DRAG_SUPPORT)
434 pageConfiguration.dragClient = new WebDragClient(this);
436 pageConfiguration.inspectorClient = new WebInspectorClient(this);
437 #if USE(AUTOCORRECTION_PANEL)
438 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
441 pageConfiguration.plugInClient = new WebPlugInClient(*this);
442 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
443 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
444 pageConfiguration.diagnosticLoggingClient = std::make_unique<WebDiagnosticLoggingClient>(*this);
445 pageConfiguration.performanceLoggingClient = std::make_unique<WebPerformanceLoggingClient>(*this);
447 pageConfiguration.webGLStateTracker = std::make_unique<WebGLStateTracker>([this](bool isUsingHighPerformanceWebGL) {
448 send(Messages::WebPageProxy::SetIsUsingHighPerformanceWebGL(isUsingHighPerformanceWebGL));
452 pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(*this);
455 pageConfiguration.applicationCacheStorage = &WebProcess::singleton().applicationCacheStorage();
456 pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
457 pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
458 pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
459 pageConfiguration.userContentProvider = m_userContentController.ptr();
460 pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
462 #if ENABLE(APPLE_PAY)
463 pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinator(*this);
466 #if ENABLE(WEB_AUTHN)
467 pageConfiguration.authenticatorCoordinatorClient = std::make_unique<WebAuthenticatorCoordinator>(*this);
470 #if ENABLE(APPLICATION_MANIFEST)
471 pageConfiguration.applicationManifest = parameters.applicationManifest;
474 m_page = std::make_unique<Page>(WTFMove(pageConfiguration));
475 updatePreferences(parameters.store);
477 m_drawingArea = DrawingArea::create(*this, parameters);
478 m_drawingArea->setPaintingEnabled(false);
479 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
481 if (parameters.isProcessSwap)
482 freezeLayerTree(LayerTreeFreezeReason::ProcessSwap);
484 #if ENABLE(ASYNC_SCROLLING)
485 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
486 if (!m_drawingArea->supportsAsyncScrolling())
487 m_useAsyncScrolling = false;
488 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
491 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
492 m_drawingArea->updatePreferences(parameters.store);
494 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
495 setPageAndTextZoomFactors(parameters.pageZoomFactor, parameters.textZoomFactor);
497 #if ENABLE(GEOLOCATION)
498 WebCore::provideGeolocationTo(m_page.get(), *new WebGeolocationClient(*this));
500 #if ENABLE(NOTIFICATIONS)
501 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
503 #if ENABLE(MEDIA_STREAM)
504 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
507 m_page->setControlledByAutomation(parameters.controlledByAutomation);
509 m_page->setCanStartMedia(false);
510 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
512 m_page->setGroupName(m_pageGroup->identifier());
513 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
514 m_page->setUserInterfaceLayoutDirection(m_userInterfaceLayoutDirection);
515 #if PLATFORM(IOS_FAMILY)
516 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
519 platformInitialize();
521 setUseFixedLayout(parameters.useFixedLayout);
523 setUnderlayColor(parameters.underlayColor);
525 setPaginationMode(parameters.paginationMode);
526 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
527 setPageLength(parameters.pageLength);
528 setGapBetweenPages(parameters.gapBetweenPages);
529 setPaginationLineGridEnabled(parameters.paginationLineGridEnabled);
531 setUseDarkAppearance(parameters.useDarkAppearance);
534 setUseSystemAppearance(parameters.useSystemAppearance);
537 // If the page is created off-screen, its visibilityState should be prerender.
538 m_page->setActivityState(m_activityState);
540 m_page->setIsPrerender();
542 updateIsInWindow(true);
544 setViewLayoutSize(parameters.viewLayoutSize);
545 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
546 setViewportSizeForCSSViewportUnits(parameters.viewportSizeForCSSViewportUnits);
548 setScrollPinningBehavior(parameters.scrollPinningBehavior);
549 if (parameters.scrollbarOverlayStyle)
550 m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
552 m_scrollbarOverlayStyle = Optional<ScrollbarOverlayStyle>();
554 setTopContentInset(parameters.topContentInset);
556 m_userAgent = parameters.userAgent;
558 if (!parameters.itemStates.isEmpty())
559 restoreSessionInternal(parameters.itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
561 if (parameters.sessionID.isValid())
562 setSessionID(parameters.sessionID);
564 m_drawingArea->setPaintingEnabled(true);
566 setMediaVolume(parameters.mediaVolume);
568 setMuted(parameters.muted);
570 // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
571 m_page->addLayoutMilestones({ DidFirstLayout, DidFirstVisuallyNonEmptyLayout });
573 auto& webProcess = WebProcess::singleton();
574 webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
576 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
577 webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
578 webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
579 webProcess.addMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID, *this);
580 #if ENABLE(FULLSCREEN_API)
581 webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
585 webPageCounter.increment();
588 #if ENABLE(ASYNC_SCROLLING)
589 if (m_useAsyncScrolling)
590 webProcess.eventDispatcher().addScrollingTreeForPage(this);
593 for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
594 m_mimeTypesWithCustomContentProviders.add(mimeType);
597 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
598 if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
599 m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
601 m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
603 if (parameters.viewScaleFactor != 1)
604 scaleView(parameters.viewScaleFactor);
606 m_page->addLayoutMilestones(parameters.observedLayoutMilestones);
609 m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
610 setSmartInsertDeleteEnabled(parameters.smartInsertDeleteEnabled);
611 WebCore::setAdditionalSupportedImageTypes(parameters.additionalSupportedImageTypes);
614 #if ENABLE(SERVICE_WORKER)
615 if (parameters.hasRegisteredServiceWorkers)
616 ServiceWorkerProvider::singleton().setMayHaveRegisteredServiceWorkers();
619 m_needsFontAttributes = parameters.needsFontAttributes;
622 if (!parameters.iceCandidateFilteringEnabled)
623 disableICECandidateFiltering();
625 if (parameters.enumeratingAllNetworkInterfacesEnabled)
626 enableEnumeratingAllNetworkInterfaces();
630 for (const auto& iterator : parameters.urlSchemeHandlers)
631 registerURLSchemeHandler(iterator.value, iterator.key);
633 m_userContentController->addUserContentWorlds(parameters.userContentWorlds);
634 m_userContentController->addUserScripts(WTFMove(parameters.userScripts), InjectUserScriptImmediately::No);
635 m_userContentController->addUserStyleSheets(parameters.userStyleSheets);
636 m_userContentController->addUserScriptMessageHandlers(parameters.messageHandlers);
637 #if ENABLE(CONTENT_EXTENSIONS)
638 m_userContentController->addContentRuleLists(parameters.contentRuleLists);
641 #if PLATFORM(IOS_FAMILY)
642 setViewportConfigurationViewLayoutSize(parameters.viewportConfigurationViewLayoutSize, parameters.viewportConfigurationLayoutSizeScaleFactor, 0);
643 setMaximumUnobscuredSize(parameters.maximumUnobscuredSize);
646 #if USE(AUDIO_SESSION)
647 PlatformMediaSessionManager::setShouldDeactivateAudioSession(true);
650 setBackgroundColor(parameters.backgroundColor);
654 void WebPage::disableICECandidateFiltering()
656 m_page->disableICECandidateFiltering();
659 void WebPage::enableICECandidateFiltering()
661 m_page->enableICECandidateFiltering();
665 void WebPage::disableEnumeratingAllNetworkInterfaces()
667 m_page->libWebRTCProvider().disableEnumeratingAllNetworkInterfaces();
670 void WebPage::enableEnumeratingAllNetworkInterfaces()
672 m_page->libWebRTCProvider().enableEnumeratingAllNetworkInterfaces();
677 void WebPage::stopAllMediaPlayback()
679 m_page->stopAllMediaPlayback();
682 void WebPage::suspendAllMediaPlayback()
684 m_page->suspendAllMediaPlayback();
687 void WebPage::resumeAllMediaPlayback()
689 m_page->resumeAllMediaPlayback();
692 void WebPage::reinitializeWebPage(WebPageCreationParameters&& parameters)
694 ASSERT(m_drawingArea);
696 setSize(parameters.viewSize);
698 if (m_shouldResetDrawingAreaAfterSuspend) {
699 auto oldDrawingArea = std::exchange(m_drawingArea, nullptr);
700 oldDrawingArea->removeMessageReceiverIfNeeded();
701 m_shouldResetDrawingAreaAfterSuspend = false;
703 m_drawingArea = DrawingArea::create(*this, parameters);
704 m_drawingArea->setPaintingEnabled(false);
705 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
706 m_drawingArea->updatePreferences(parameters.store);
707 m_drawingArea->setPaintingEnabled(true);
709 m_drawingArea->adoptLayersFromDrawingArea(*oldDrawingArea);
711 unfreezeLayerTree(LayerTreeFreezeReason::PageSuspended);
713 RELEASE_ASSERT(m_drawingArea->identifier() == parameters.drawingAreaIdentifier);
715 setViewLayoutSize(parameters.viewLayoutSize);
717 if (m_activityState != parameters.activityState)
718 setActivityState(parameters.activityState, ActivityStateChangeAsynchronous, Vector<CallbackID>());
719 if (m_layerHostingMode != parameters.layerHostingMode)
720 setLayerHostingMode(parameters.layerHostingMode);
722 platformReinitialize();
725 void WebPage::updateThrottleState()
727 bool isActive = m_activityState.containsAny({ ActivityState::IsLoading, ActivityState::IsAudible, ActivityState::IsCapturingMedia, ActivityState::WindowIsActive });
728 bool isVisuallyIdle = m_activityState.contains(ActivityState::IsVisuallyIdle);
729 bool pageSuppressed = m_processSuppressionEnabled && !isActive && isVisuallyIdle;
731 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
732 if (!pageSuppressed) {
733 // App nap must be manually enabled when not running the NSApplication run loop.
734 static std::once_flag onceKey;
735 std::call_once(onceKey, [] {
736 __CFRunLoopSetOptionsReason(__CFRunLoopOptionsEnableAppNap, CFSTR("Finished checkin as application - enable app nap"));
740 // The UserActivity keeps the processes runnable. So if the page should be suppressed, stop the activity.
741 // If the page should not be supressed, start it.
743 m_userActivityHysteresis.stop();
745 m_userActivityHysteresis.start();
748 void WebPage::updateUserActivity()
750 if (m_userActivityHysteresis.state() == PAL::HysteresisState::Started)
751 m_userActivity.start();
753 m_userActivity.stop();
762 m_sandboxExtensionTracker.invalidate();
764 for (auto* pluginView : m_pluginViews)
765 pluginView->webPageDestroyed();
767 #if !PLATFORM(IOS_FAMILY)
769 m_headerBanner->detachFromPage();
771 m_footerBanner->detachFromPage();
772 #endif // !PLATFORM(IOS_FAMILY)
775 webPageCounter.decrement();
778 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
779 if (m_playbackSessionManager)
780 m_playbackSessionManager->invalidate();
782 if (m_videoFullscreenManager)
783 m_videoFullscreenManager->invalidate();
787 IPC::Connection* WebPage::messageSenderConnection() const
789 return WebProcess::singleton().parentProcessConnection();
792 uint64_t WebPage::messageSenderDestinationID() const
797 #if ENABLE(CONTEXT_MENUS)
798 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>&& contextMenuClient)
800 if (!contextMenuClient) {
801 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
805 m_contextMenuClient = WTFMove(contextMenuClient);
809 void WebPage::setInjectedBundleEditorClient(std::unique_ptr<API::InjectedBundle::EditorClient>&& editorClient)
812 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
816 m_editorClient = WTFMove(editorClient);
819 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>&& formClient)
822 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
826 m_formClient = WTFMove(formClient);
829 void WebPage::setInjectedBundlePageLoaderClient(std::unique_ptr<API::InjectedBundle::PageLoaderClient>&& loaderClient)
832 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
836 m_loaderClient = WTFMove(loaderClient);
838 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
839 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
840 // for backwards compatibility.
841 if (auto milestones = m_loaderClient->layoutMilestones())
842 listenForLayoutMilestones(milestones);
845 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
847 m_policyClient.initialize(client);
850 void WebPage::setInjectedBundleResourceLoadClient(std::unique_ptr<API::InjectedBundle::ResourceLoadClient>&& client)
852 if (!m_resourceLoadClient)
853 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
855 m_resourceLoadClient = WTFMove(client);
858 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>&& uiClient)
861 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
865 m_uiClient = WTFMove(uiClient);
868 #if ENABLE(FULLSCREEN_API)
869 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
871 m_fullScreenClient.initialize(client);
875 #if ENABLE(NETSCAPE_PLUGIN_API)
876 RefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
878 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
879 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
881 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
882 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
883 unsigned pluginArea = 0;
884 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
886 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
889 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
891 uint64_t pluginProcessToken;
892 uint32_t pluginLoadPolicy;
893 String unavailabilityDescription;
895 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)))
898 PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
899 bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
901 if (isUnsupported || isBlockedPlugin || !pluginProcessToken) {
902 #if ENABLE(PDFKIT_PLUGIN)
903 String path = parameters.url.path();
904 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWithIgnoringASCIICase(".pdf") || path.endsWithIgnoringASCIICase(".ps")))))
905 return PDFPlugin::create(*frame);
910 pluginElement->setReplacement(RenderEmbeddedObject::UnsupportedPlugin, unavailabilityDescription);
914 if (isBlockedPlugin) {
915 bool isReplacementObscured = pluginElement->setReplacement(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
916 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, isReplacementObscured));
920 if (!pluginProcessToken)
923 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
924 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
926 #endif // ENABLE(NETSCAPE_PLUGIN_API)
928 #if ENABLE(WEBGL) && !PLATFORM(MAC)
929 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const URL&)
931 return WebGLAllowCreation;
934 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const URL&)
936 return WebGLAllowCreation;
940 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
942 Frame& frame = m_page->focusController().focusedOrMainFrame();
946 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
947 if (!pluginView->getSelectionString().isNull()) {
948 result.selectionIsNone = false;
949 result.selectionIsRange = true;
950 result.isInPlugin = true;
955 const VisibleSelection& selection = frame.selection().selection();
956 const Editor& editor = frame.editor();
958 result.selectionIsNone = selection.isNone();
959 result.selectionIsRange = selection.isRange();
960 result.isContentEditable = selection.isContentEditable();
961 result.isContentRichlyEditable = selection.isContentRichlyEditable();
962 result.isInPasswordField = selection.isInPasswordField();
963 result.hasComposition = editor.hasComposition();
964 result.shouldIgnoreSelectionChanges = editor.ignoreSelectionChanges();
966 if (auto* document = frame.document())
967 result.originIdentifierForPasteboard = document->originIdentifierForPasteboard();
969 bool canIncludePostLayoutData = frame.view() && !frame.view()->needsLayout();
970 if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && canIncludePostLayoutData) {
971 auto& postLayoutData = result.postLayoutData();
972 postLayoutData.canCut = editor.canCut();
973 postLayoutData.canCopy = editor.canCopy();
974 postLayoutData.canPaste = editor.canPaste();
976 if (m_needsFontAttributes)
977 postLayoutData.fontAttributes = editor.fontAttributesAtSelectionStart();
980 if (result.isContentEditable && !selection.isNone()) {
981 if (auto editingStyle = EditingStyle::styleAtSelectionStart(selection)) {
982 if (editingStyle->hasStyle(CSSPropertyFontWeight, "bold"))
983 postLayoutData.typingAttributes |= AttributeBold;
985 if (editingStyle->hasStyle(CSSPropertyFontStyle, "italic") || editingStyle->hasStyle(CSSPropertyFontStyle, "oblique"))
986 postLayoutData.typingAttributes |= AttributeItalics;
988 if (editingStyle->hasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline"))
989 postLayoutData.typingAttributes |= AttributeUnderline;
991 if (auto* styleProperties = editingStyle->style()) {
992 bool isLeftToRight = styleProperties->propertyAsValueID(CSSPropertyDirection) == CSSValueLtr;
993 switch (styleProperties->propertyAsValueID(CSSPropertyTextAlign)) {
995 case CSSValueWebkitRight:
996 postLayoutData.textAlignment = RightAlignment;
999 case CSSValueWebkitLeft:
1000 postLayoutData.textAlignment = LeftAlignment;
1002 case CSSValueCenter:
1003 case CSSValueWebkitCenter:
1004 postLayoutData.textAlignment = CenterAlignment;
1006 case CSSValueJustify:
1007 postLayoutData.textAlignment = JustifiedAlignment;
1010 postLayoutData.textAlignment = isLeftToRight ? LeftAlignment : RightAlignment;
1013 postLayoutData.textAlignment = isLeftToRight ? RightAlignment : LeftAlignment;
1018 if (auto textColor = styleProperties->propertyAsColor(CSSPropertyColor))
1019 postLayoutData.textColor = *textColor;
1023 if (auto* enclosingListElement = enclosingList(selection.start().containerNode())) {
1024 if (is<HTMLUListElement>(*enclosingListElement))
1025 postLayoutData.enclosingListType = UnorderedList;
1026 else if (is<HTMLOListElement>(*enclosingListElement))
1027 postLayoutData.enclosingListType = OrderedList;
1029 ASSERT_NOT_REACHED();
1032 postLayoutData.baseWritingDirection = editor.baseWritingDirectionForSelectionStart();
1037 platformEditorState(frame, result, shouldIncludePostLayoutData);
1039 m_lastEditorStateWasContentEditable = result.isContentEditable ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1044 void WebPage::changeFontAttributes(WebCore::FontAttributeChanges&& changes)
1046 auto& frame = m_page->focusController().focusedOrMainFrame();
1047 if (frame.selection().selection().isContentEditable())
1048 frame.editor().applyStyleToSelection(changes.createEditingStyle(), changes.editAction(), Editor::ColorFilterMode::InvertColor);
1051 void WebPage::changeFont(WebCore::FontChanges&& changes)
1053 auto& frame = m_page->focusController().focusedOrMainFrame();
1054 if (frame.selection().selection().isContentEditable())
1055 frame.editor().applyStyleToSelection(changes.createEditingStyle(), EditAction::SetFont, Editor::ColorFilterMode::InvertColor);
1058 void WebPage::executeEditCommandWithCallback(const String& commandName, const String& argument, CallbackID callbackID)
1060 executeEditCommand(commandName, argument);
1061 send(Messages::WebPageProxy::VoidCallback(callbackID));
1064 void WebPage::updateEditorStateAfterLayoutIfEditabilityChanged()
1066 // FIXME: We should update EditorStateIsContentEditable to track whether the state is richly
1067 // editable or plainttext-only.
1068 if (m_lastEditorStateWasContentEditable == EditorStateIsContentEditable::Unset)
1071 Frame& frame = m_page->focusController().focusedOrMainFrame();
1072 EditorStateIsContentEditable editorStateIsContentEditable = frame.selection().selection().isContentEditable() ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1073 if (m_lastEditorStateWasContentEditable != editorStateIsContentEditable)
1074 sendPartialEditorStateAndSchedulePostLayoutUpdate();
1077 String WebPage::renderTreeExternalRepresentation() const
1079 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
1082 String WebPage::renderTreeExternalRepresentationForPrinting() const
1084 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
1087 uint64_t WebPage::renderTreeSize() const
1091 return m_page->renderTreeSize();
1094 void WebPage::setTracksRepaints(bool trackRepaints)
1096 if (FrameView* view = mainFrameView())
1097 view->setTracksRepaints(trackRepaints);
1100 bool WebPage::isTrackingRepaints() const
1102 if (FrameView* view = mainFrameView())
1103 return view->isTrackingRepaints();
1108 void WebPage::resetTrackedRepaints()
1110 if (FrameView* view = mainFrameView())
1111 view->resetTrackedRepaints();
1114 Ref<API::Array> WebPage::trackedRepaintRects()
1116 FrameView* view = mainFrameView();
1118 return API::Array::create();
1120 Vector<RefPtr<API::Object>> repaintRects;
1121 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
1123 for (const auto& repaintRect : view->trackedRepaintRects())
1124 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
1126 return API::Array::create(WTFMove(repaintRects));
1129 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
1131 if (!is<PluginDocument>(frame.document()))
1134 auto& pluginDocument = downcast<PluginDocument>(*frame.document());
1135 if (pluginDocument.focusedElement() != pluginDocument.pluginElement())
1138 return pluginViewForFrame(&frame);
1141 PluginView* WebPage::pluginViewForFrame(Frame* frame)
1143 if (!frame || !is<PluginDocument>(frame->document()))
1146 auto& document = downcast<PluginDocument>(*frame->document());
1147 return static_cast<PluginView*>(document.pluginWidget());
1150 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
1152 Frame& frame = m_page->focusController().focusedOrMainFrame();
1154 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
1155 pluginView->handleEditingCommand(commandName, argument);
1159 frame.editor().command(commandName).execute(argument);
1162 void WebPage::setEditable(bool editable)
1164 m_page->setEditable(editable);
1165 m_page->setTabKeyCyclesThroughElements(!editable);
1166 Frame& frame = m_page->focusController().focusedOrMainFrame();
1168 frame.editor().applyEditingStyleToBodyElement();
1169 // If the page is made editable and the selection is empty, set it to something.
1170 if (frame.selection().isNone())
1171 frame.selection().setSelectionFromNone();
1175 void WebPage::increaseListLevel()
1177 m_page->focusController().focusedOrMainFrame().editor().increaseSelectionListLevel();
1180 void WebPage::decreaseListLevel()
1182 m_page->focusController().focusedOrMainFrame().editor().decreaseSelectionListLevel();
1185 void WebPage::changeListType()
1187 m_page->focusController().focusedOrMainFrame().editor().changeSelectionListType();
1190 void WebPage::setBaseWritingDirection(WritingDirection direction)
1192 m_page->focusController().focusedOrMainFrame().editor().setBaseWritingDirection(direction);
1195 bool WebPage::isEditingCommandEnabled(const String& commandName)
1197 Frame& frame = m_page->focusController().focusedOrMainFrame();
1199 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1200 return pluginView->isEditingCommandEnabled(commandName);
1202 Editor::Command command = frame.editor().command(commandName);
1203 return command.isSupported() && command.isEnabled();
1206 void WebPage::clearMainFrameName()
1208 if (Frame* frame = mainFrame())
1209 frame->tree().clearName();
1212 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
1214 m_drawingArea->setRootCompositingLayer(layer);
1217 void WebPage::exitAcceleratedCompositingMode()
1219 m_drawingArea->setRootCompositingLayer(nullptr);
1222 void WebPage::close()
1227 #if ENABLE(RESOURCE_LOAD_STATISTICS)
1228 WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::RemoveStorageAccessForAllFramesOnPage(sessionID(), m_pageID), 0);
1233 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1234 if (!mainWebFrame()->url().isEmpty())
1235 reportUsedFeatures();
1237 if (WebProcess::singleton().injectedBundle())
1238 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1241 m_inspector->disconnectFromPage();
1242 m_inspector = nullptr;
1245 m_page->inspectorController().disconnectAllFrontends();
1247 #if ENABLE(MEDIA_STREAM)
1248 m_userMediaPermissionRequestManager->clear();
1251 #if ENABLE(FULLSCREEN_API)
1252 m_fullScreenManager = nullptr;
1255 if (m_activePopupMenu) {
1256 m_activePopupMenu->disconnectFromPage();
1257 m_activePopupMenu = nullptr;
1260 if (m_activeOpenPanelResultListener) {
1261 m_activeOpenPanelResultListener->disconnectFromPage();
1262 m_activeOpenPanelResultListener = nullptr;
1265 #if ENABLE(INPUT_TYPE_COLOR)
1266 if (m_activeColorChooser) {
1267 m_activeColorChooser->disconnectFromPage();
1268 m_activeColorChooser = nullptr;
1273 if (m_printOperation) {
1274 m_printOperation->disconnectFromPage();
1275 m_printOperation = nullptr;
1279 #if ENABLE(VIDEO) && USE(GSTREAMER)
1280 if (m_installMediaPluginsCallback) {
1281 m_installMediaPluginsCallback->invalidate();
1282 m_installMediaPluginsCallback = nullptr;
1286 m_sandboxExtensionTracker.invalidate();
1288 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1289 m_determinePrimarySnapshottedPlugInTimer.stop();
1292 #if ENABLE(CONTEXT_MENUS)
1293 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1295 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
1296 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1297 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
1298 m_policyClient.initialize(0);
1299 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
1300 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1301 #if ENABLE(FULLSCREEN_API)
1302 m_fullScreenClient.initialize(0);
1305 m_printContext = nullptr;
1306 m_mainFrame->coreFrame()->loader().detachFromParent();
1307 m_drawingArea = nullptr;
1309 DeferredPageDestructor::createDeferredPageDestructor(WTFMove(m_page), this);
1311 bool isRunningModal = m_isRunningModal;
1312 m_isRunningModal = false;
1314 auto& webProcess = WebProcess::singleton();
1315 #if ENABLE(ASYNC_SCROLLING)
1316 if (m_useAsyncScrolling)
1317 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
1319 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
1320 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
1321 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
1322 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
1323 webProcess.removeMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID);
1324 #if ENABLE(FULLSCREEN_API)
1325 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
1327 #if PLATFORM(COCOA) || PLATFORM(GTK)
1328 m_viewGestureGeometryCollector = nullptr;
1331 // The WebPage can be destroyed by this call.
1332 WebProcess::singleton().removeWebPage(m_pageID);
1334 WebProcess::singleton().updateActivePages();
1337 RunLoop::main().stop();
1340 void WebPage::tryClose()
1342 SendStopResponsivenessTimer stopper;
1344 if (!corePage()->userInputBridge().tryClosePage())
1347 send(Messages::WebPageProxy::ClosePage(true));
1350 void WebPage::sendClose()
1352 send(Messages::WebPageProxy::ClosePage(false));
1355 void WebPage::suspendForProcessSwap()
1357 auto failedToSuspend = [this, protectedThis = makeRef(*this)] {
1358 send(Messages::WebPageProxy::DidFailToSuspendAfterProcessSwap());
1361 auto* currentHistoryItem = m_mainFrame->coreFrame()->loader().history().currentItem();
1362 if (!currentHistoryItem) {
1367 if (!PageCache::singleton().addIfCacheable(*currentHistoryItem, corePage())) {
1372 send(Messages::WebPageProxy::DidSuspendAfterProcessSwap());
1375 void WebPage::loadURLInFrame(URL&& url, uint64_t frameID)
1377 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1381 frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(url), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1384 #if !PLATFORM(COCOA)
1385 void WebPage::platformDidReceiveLoadParameters(const LoadParameters& loadParameters)
1390 void WebPage::loadRequest(LoadParameters&& loadParameters)
1392 SendStopResponsivenessTimer stopper;
1394 m_pendingNavigationID = loadParameters.navigationID;
1395 m_pendingWebsitePolicies = WTFMove(loadParameters.websitePolicies);
1397 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), WTFMove(loadParameters.sandboxExtensionHandle));
1399 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1400 // to all the client to set up any needed state.
1401 m_loaderClient->willLoadURLRequest(*this, loadParameters.request, WebProcess::singleton().transformHandlesToObjects(loadParameters.userData.object()).get());
1403 platformDidReceiveLoadParameters(loadParameters);
1405 // Initate the load in WebCore.
1406 FrameLoadRequest frameLoadRequest { *m_mainFrame->coreFrame(), loadParameters.request, ShouldOpenExternalURLsPolicy::ShouldNotAllow };
1407 ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(loadParameters.shouldOpenExternalURLsPolicy);
1408 frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1409 frameLoadRequest.setShouldTreatAsContinuingLoad(loadParameters.shouldTreatAsContinuingLoad);
1410 frameLoadRequest.setLockHistory(loadParameters.lockHistory);
1411 frameLoadRequest.setlockBackForwardList(loadParameters.lockBackForwardList);
1412 frameLoadRequest.setClientRedirectSourceForHistory(loadParameters.clientRedirectSourceForHistory);
1413 frameLoadRequest.setIsRequestFromClientOrUserInput();
1415 corePage()->userInputBridge().loadRequest(WTFMove(frameLoadRequest));
1417 ASSERT(!m_pendingNavigationID);
1418 ASSERT(!m_pendingWebsitePolicies);
1421 void WebPage::loadDataImpl(uint64_t navigationID, bool shouldTreatAsContinuingLoad, Optional<WebsitePoliciesData>&& websitePolicies, Ref<SharedBuffer>&& sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1423 SendStopResponsivenessTimer stopper;
1425 m_pendingNavigationID = navigationID;
1426 m_pendingWebsitePolicies = WTFMove(websitePolicies);
1428 ResourceRequest request(baseURL);
1429 ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1430 SubstituteData substituteData(WTFMove(sharedBuffer), unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1432 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1433 // to all the client to set up any needed state.
1434 m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1436 // Initate the load in WebCore.
1437 FrameLoadRequest frameLoadRequest(*m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData);
1438 frameLoadRequest.setShouldTreatAsContinuingLoad(shouldTreatAsContinuingLoad);
1439 m_mainFrame->coreFrame()->loader().load(WTFMove(frameLoadRequest));
1442 void WebPage::loadData(LoadParameters&& loadParameters)
1444 platformDidReceiveLoadParameters(loadParameters);
1446 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1447 URL baseURL = loadParameters.baseURLString.isEmpty() ? WTF::blankURL() : URL(URL(), loadParameters.baseURLString);
1448 loadDataImpl(loadParameters.navigationID, loadParameters.shouldTreatAsContinuingLoad, WTFMove(loadParameters.websitePolicies), WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, URL(), loadParameters.userData);
1451 void WebPage::loadAlternateHTML(LoadParameters&& loadParameters)
1453 platformDidReceiveLoadParameters(loadParameters);
1455 URL baseURL = loadParameters.baseURLString.isEmpty() ? WTF::blankURL() : URL(URL(), loadParameters.baseURLString);
1456 URL unreachableURL = loadParameters.unreachableURLString.isEmpty() ? URL() : URL(URL(), loadParameters.unreachableURLString);
1457 URL provisionalLoadErrorURL = loadParameters.provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), loadParameters.provisionalLoadErrorURLString);
1458 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1459 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1460 loadDataImpl(loadParameters.navigationID, loadParameters.shouldTreatAsContinuingLoad, WTFMove(loadParameters.websitePolicies), WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, unreachableURL, loadParameters.userData);
1461 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1464 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1466 Frame* mainFrame = m_mainFrame->coreFrame();
1467 Document* mainFrameDocument = mainFrame->document();
1468 if (!mainFrameDocument)
1471 const int singleClick = 1;
1472 // FIXME: Set modifier keys.
1473 // FIXME: This should probably set IsSimulated::Yes.
1474 auto mouseEvent = MouseEvent::create(eventNames().clickEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes, Event::IsComposed::Yes,
1475 MonotonicTime::now(), nullptr, singleClick, screenPoint, documentPoint, { }, { }, 0, 0, nullptr, 0, WebCore::NoTap, nullptr);
1477 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.ptr(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1480 void WebPage::stopLoadingFrame(uint64_t frameID)
1482 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1486 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1489 void WebPage::stopLoading()
1491 SendStopResponsivenessTimer stopper;
1493 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1496 bool WebPage::defersLoading() const
1498 return m_page->defersLoading();
1501 void WebPage::setDefersLoading(bool defersLoading)
1503 m_page->setDefersLoading(defersLoading);
1506 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, SandboxExtension::Handle&& sandboxExtensionHandle)
1508 SendStopResponsivenessTimer stopper;
1510 ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1511 m_pendingNavigationID = navigationID;
1513 m_sandboxExtensionTracker.beginReload(m_mainFrame.get(), WTFMove(sandboxExtensionHandle));
1514 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1516 if (m_pendingNavigationID) {
1517 // This can happen if FrameLoader::reload() returns early because the document URL is empty.
1518 // The reload does nothing so we need to reset the pending navigation. See webkit.org/b/153210.
1519 m_pendingNavigationID = 0;
1523 void WebPage::goToBackForwardItem(uint64_t navigationID, const BackForwardItemIdentifier& backForwardItemID, FrameLoadType backForwardType, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad, Optional<WebsitePoliciesData>&& websitePolicies)
1525 SendStopResponsivenessTimer stopper;
1527 ASSERT(isBackForwardLoadType(backForwardType));
1529 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1534 LOG(Loading, "In WebProcess pid %i, WebPage %" PRIu64 " is navigating to back/forward URL %s", getCurrentProcessID(), m_pageID, item->url().string().utf8().data());
1536 ASSERT(!m_pendingNavigationID);
1537 m_pendingNavigationID = navigationID;
1538 m_pendingWebsitePolicies = WTFMove(websitePolicies);
1540 m_page->goToItem(*item, backForwardType, shouldTreatAsContinuingLoad);
1543 void WebPage::tryRestoreScrollPosition()
1545 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1548 void WebPage::layoutIfNeeded()
1550 if (m_mainFrame->coreFrame()->view())
1551 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1554 WebPage* WebPage::fromCorePage(Page* page)
1556 return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1559 void WebPage::setSize(const WebCore::IntSize& viewSize)
1561 if (m_viewSize == viewSize)
1564 m_viewSize = viewSize;
1565 FrameView* view = m_page->mainFrame().view();
1566 view->resize(viewSize);
1567 m_drawingArea->setNeedsDisplay();
1569 #if USE(COORDINATED_GRAPHICS)
1570 if (view->useFixedLayout())
1571 sendViewportAttributesChanged(m_page->viewportArguments());
1575 #if USE(COORDINATED_GRAPHICS)
1576 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1578 FrameView* view = m_page->mainFrame().view();
1579 ASSERT(view && view->useFixedLayout());
1581 // Viewport properties have no impact on zero sized fixed viewports.
1582 if (m_viewSize.isEmpty())
1585 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1586 Settings& settings = m_page->settings();
1588 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1590 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1591 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1592 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1594 ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1596 // If no layout was done yet set contentFixedOrigin to (0,0).
1597 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1599 // Put the width and height to the viewport width and height. In css units however.
1600 // Use FloatSize to avoid truncated values during scale.
1601 FloatSize contentFixedSize = m_viewSize;
1603 #if ENABLE(CSS_DEVICE_ADAPTATION)
1604 // CSS viewport descriptors might be applied to already affected viewport size
1605 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1606 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1609 contentFixedSize.scale(1 / attr.initialScale);
1610 view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1612 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1614 // This also takes care of the relayout.
1615 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1617 #if USE(COORDINATED_GRAPHICS_THREADED)
1618 m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1620 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1625 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1627 FrameView* frameView = m_page->mainFrame().view();
1629 ScrollPosition scrollPosition = frameView->scrollPosition();
1630 ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1632 // If the current scroll position in a direction is the max scroll position
1633 // we don't want to scroll at all.
1634 IntSize newScrollOffset;
1635 if (scrollPosition.x() < maximumScrollPosition.x())
1636 newScrollOffset.setWidth(scrollOffset.width());
1637 if (scrollPosition.y() < maximumScrollPosition.y())
1638 newScrollOffset.setHeight(scrollOffset.height());
1640 if (newScrollOffset.isZero())
1643 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1646 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1649 FrameView* mainFrameView = m_page->mainFrame().view();
1650 LocalDefaultSystemAppearance localAppearance(mainFrameView ? mainFrameView->useDarkAppearance() : false);
1653 GraphicsContextStateSaver stateSaver(graphicsContext);
1654 graphicsContext.clip(rect);
1656 m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1659 double WebPage::textZoomFactor() const
1661 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1662 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1663 if (pluginView->handlesPageScaleFactor())
1664 return pluginView->pageScaleFactor();
1665 return pageScaleFactor();
1668 Frame* frame = m_mainFrame->coreFrame();
1671 return frame->textZoomFactor();
1674 void WebPage::setTextZoomFactor(double zoomFactor)
1676 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1677 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1678 if (pluginView->handlesPageScaleFactor())
1679 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1681 scalePage(zoomFactor, IntPoint());
1685 Frame* frame = m_mainFrame->coreFrame();
1688 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1691 double WebPage::pageZoomFactor() const
1693 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1694 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1695 if (pluginView->handlesPageScaleFactor())
1696 return pluginView->pageScaleFactor();
1697 return pageScaleFactor();
1700 Frame* frame = m_mainFrame->coreFrame();
1703 return frame->pageZoomFactor();
1706 void WebPage::setPageZoomFactor(double zoomFactor)
1708 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1709 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1710 if (pluginView->handlesPageScaleFactor())
1711 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1713 scalePage(zoomFactor, IntPoint());
1717 Frame* frame = m_mainFrame->coreFrame();
1720 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1723 static void dumpHistoryItem(HistoryItem& item, size_t indent, bool isCurrentItem, StringBuilder& stringBuilder, const String& directoryName)
1726 stringBuilder.appendLiteral("curr-> ");
1728 for (size_t i = 0; i < indent; ++i)
1729 stringBuilder.append(' ');
1732 auto url = item.url();
1733 if (url.protocolIs("file")) {
1734 size_t start = url.string().find(directoryName);
1735 if (start == WTF::notFound)
1738 start += directoryName.length();
1739 stringBuilder.appendLiteral("(file test):");
1740 stringBuilder.append(url.string().substring(start));
1742 stringBuilder.append(url);
1744 auto& target = item.target();
1745 if (target.length()) {
1746 stringBuilder.appendLiteral(" (in frame \"");
1747 stringBuilder.append(target);
1748 stringBuilder.appendLiteral("\")");
1751 if (item.isTargetItem())
1752 stringBuilder.appendLiteral(" **nav target**");
1754 stringBuilder.append('\n');
1756 Vector<Ref<HistoryItem>> children;
1757 children.reserveInitialCapacity(item.children().size());
1758 for (auto& child : item.children())
1759 children.uncheckedAppend(child.copyRef());
1760 std::stable_sort(children.begin(), children.end(), [] (auto& a, auto& b) {
1761 return codePointCompare(a->target(), b->target()) < 0;
1763 for (auto& child : children)
1764 dumpHistoryItem(child, indent + 4, false, stringBuilder, directoryName);
1767 String WebPage::dumpHistoryForTesting(const String& directory)
1772 auto& list = m_page->backForward();
1774 StringBuilder builder;
1775 int begin = -list.backCount();
1776 if (list.itemAtIndex(begin)->url() == WTF::blankURL())
1778 for (int i = begin; i <= static_cast<int>(list.forwardCount()); ++i)
1779 dumpHistoryItem(*list.itemAtIndex(i), 8, !i, builder, directory);
1780 return builder.toString();
1783 void WebPage::clearHistory()
1788 static_cast<WebBackForwardListProxy&>(m_page->backForward().client()).clear();
1791 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1793 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1794 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1795 if (pluginView->handlesPageScaleFactor())
1796 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1798 scalePage(pageZoomFactor, IntPoint());
1802 Frame* frame = m_mainFrame->coreFrame();
1805 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1808 void WebPage::windowScreenDidChange(uint32_t displayID)
1810 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1813 void WebPage::scalePage(double scale, const IntPoint& origin)
1815 double totalScale = scale * viewScaleFactor();
1816 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1818 #if PLATFORM(IOS_FAMILY)
1819 if (willChangeScaleFactor) {
1820 if (!m_inDynamicSizeUpdate)
1821 m_dynamicSizeUpdateHistory.clear();
1822 m_scaleWasSetByUIProcess = false;
1825 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1826 if (pluginView && pluginView->handlesPageScaleFactor()) {
1827 // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1828 // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1829 if (m_page->pageScaleFactor() != 1) {
1830 m_page->setPageScaleFactor(1, origin);
1831 for (auto* pluginView : m_pluginViews)
1832 pluginView->pageScaleFactorDidChange();
1835 pluginView->setPageScaleFactor(totalScale, origin);
1839 m_page->setPageScaleFactor(totalScale, origin);
1841 // We can't early return before setPageScaleFactor because the origin might be different.
1842 if (!willChangeScaleFactor)
1845 for (auto* pluginView : m_pluginViews)
1846 pluginView->pageScaleFactorDidChange();
1848 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1849 m_drawingArea->deviceOrPageScaleFactorChanged();
1852 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1855 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1857 double totalScale = scale * viewScaleFactor();
1858 if (totalScale == totalScaleFactor())
1861 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1862 double scaleRatio = scale / pageScaleFactor();
1863 scrollPositionAtNewScale.scale(scaleRatio);
1864 scalePage(scale, scrollPositionAtNewScale);
1867 double WebPage::totalScaleFactor() const
1869 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1870 if (pluginView && pluginView->handlesPageScaleFactor())
1871 return pluginView->pageScaleFactor();
1873 return m_page->pageScaleFactor();
1876 double WebPage::pageScaleFactor() const
1878 return totalScaleFactor() / viewScaleFactor();
1881 double WebPage::viewScaleFactor() const
1883 return m_page->viewScaleFactor();
1886 void WebPage::scaleView(double scale)
1888 if (viewScaleFactor() == scale)
1891 float pageScale = pageScaleFactor();
1893 IntPoint scrollPositionAtNewScale;
1894 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1895 double scaleRatio = scale / viewScaleFactor();
1896 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1897 scrollPositionAtNewScale.scale(scaleRatio);
1900 m_page->setViewScaleFactor(scale);
1901 scalePage(pageScale, scrollPositionAtNewScale);
1904 void WebPage::setDeviceScaleFactor(float scaleFactor)
1906 if (scaleFactor == m_page->deviceScaleFactor())
1909 m_page->setDeviceScaleFactor(scaleFactor);
1911 // Tell all our plug-in views that the device scale factor changed.
1913 for (auto* pluginView : m_pluginViews)
1914 pluginView->setDeviceScaleFactor(scaleFactor);
1916 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1919 if (findController().isShowingOverlay()) {
1920 // We must have updated layout to get the selection rects right.
1922 findController().deviceScaleFactorDidChange();
1925 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1926 m_drawingArea->deviceOrPageScaleFactorChanged();
1930 float WebPage::deviceScaleFactor() const
1932 return m_page->deviceScaleFactor();
1935 void WebPage::accessibilitySettingsDidChange()
1937 m_page->accessibilitySettingsDidChange();
1940 #if ENABLE(ACCESSIBILITY_EVENTS)
1941 void WebPage::updateAccessibilityEventsEnabled(bool enabled)
1943 m_page->settings().setAccessibilityEventsEnabled(enabled);
1947 void WebPage::setUseFixedLayout(bool fixed)
1949 // Do not overwrite current settings if initially setting it to false.
1950 if (m_useFixedLayout == fixed)
1952 m_useFixedLayout = fixed;
1954 #if !PLATFORM(IOS_FAMILY)
1955 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1958 FrameView* view = mainFrameView();
1962 view->setUseFixedLayout(fixed);
1964 setFixedLayoutSize(IntSize());
1966 send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1969 bool WebPage::setFixedLayoutSize(const IntSize& size)
1971 FrameView* view = mainFrameView();
1972 if (!view || view->fixedLayoutSize() == size)
1975 LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " setFixedLayoutSize " << size);
1976 view->setFixedLayoutSize(size);
1978 send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1982 IntSize WebPage::fixedLayoutSize() const
1984 FrameView* view = mainFrameView();
1987 return view->fixedLayoutSize();
1990 void WebPage::disabledAdaptationsDidChange(const OptionSet<DisabledAdaptations>& disabledAdaptations)
1992 #if PLATFORM(IOS_FAMILY)
1993 if (m_viewportConfiguration.setDisabledAdaptations(disabledAdaptations))
1994 viewportConfigurationChanged();
1996 UNUSED_PARAM(disabledAdaptations);
2000 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
2002 #if PLATFORM(IOS_FAMILY)
2003 if (m_viewportConfiguration.setViewportArguments(viewportArguments))
2004 viewportConfigurationChanged();
2007 #if USE(COORDINATED_GRAPHICS)
2008 FrameView* view = m_page->mainFrame().view();
2009 if (view && view->useFixedLayout())
2010 sendViewportAttributesChanged(viewportArguments);
2011 #if USE(COORDINATED_GRAPHICS_THREADED)
2013 m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
2017 #if !PLATFORM(IOS_FAMILY) && !USE(COORDINATED_GRAPHICS)
2018 UNUSED_PARAM(viewportArguments);
2022 void WebPage::listenForLayoutMilestones(OptionSet<WebCore::LayoutMilestone> milestones)
2026 m_page->addLayoutMilestones(milestones);
2029 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
2031 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
2034 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
2036 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
2039 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
2041 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
2044 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
2046 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
2047 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
2050 void WebPage::setPaginationMode(uint32_t mode)
2052 Pagination pagination = m_page->pagination();
2053 pagination.mode = static_cast<Pagination::Mode>(mode);
2054 m_page->setPagination(pagination);
2057 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
2059 Pagination pagination = m_page->pagination();
2060 pagination.behavesLikeColumns = behavesLikeColumns;
2061 m_page->setPagination(pagination);
2064 void WebPage::setPageLength(double pageLength)
2066 Pagination pagination = m_page->pagination();
2067 pagination.pageLength = pageLength;
2068 m_page->setPagination(pagination);
2071 void WebPage::setGapBetweenPages(double gap)
2073 Pagination pagination = m_page->pagination();
2074 pagination.gap = gap;
2075 m_page->setPagination(pagination);
2078 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
2080 m_page->setPaginationLineGridEnabled(lineGridEnabled);
2083 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
2085 auto& webProcess = WebProcess::singleton();
2086 InjectedBundle* injectedBundle = webProcess.injectedBundle();
2087 if (!injectedBundle)
2090 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
2093 #if !PLATFORM(IOS_FAMILY)
2095 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
2098 m_headerBanner->detachFromPage();
2100 m_headerBanner = pageBanner;
2103 m_headerBanner->addToPage(PageBanner::Header, this);
2106 PageBanner* WebPage::headerPageBanner()
2108 return m_headerBanner.get();
2111 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
2114 m_footerBanner->detachFromPage();
2116 m_footerBanner = pageBanner;
2119 m_footerBanner->addToPage(PageBanner::Footer, this);
2122 PageBanner* WebPage::footerPageBanner()
2124 return m_footerBanner.get();
2127 void WebPage::hidePageBanners()
2130 m_headerBanner->hide();
2132 m_footerBanner->hide();
2135 void WebPage::showPageBanners()
2138 m_headerBanner->showIfHidden();
2140 m_footerBanner->showIfHidden();
2143 void WebPage::setHeaderBannerHeightForTesting(int height)
2145 corePage()->setHeaderHeight(height);
2148 void WebPage::setFooterBannerHeightForTesting(int height)
2150 corePage()->setFooterHeight(height);
2153 #endif // !PLATFORM(IOS_FAMILY)
2155 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
2157 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
2158 snapshotOptions |= SnapshotOptionsShareable;
2160 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
2162 ShareableBitmap::Handle handle;
2164 image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
2166 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
2169 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
2171 IntRect snapshotRect = rect;
2172 IntSize bitmapSize = snapshotRect.size();
2173 if (options & SnapshotOptionsPrinting) {
2174 ASSERT(additionalScaleFactor == 1);
2175 Frame* coreFrame = m_mainFrame->coreFrame();
2178 bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
2180 double scaleFactor = additionalScaleFactor;
2181 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
2182 scaleFactor *= corePage()->deviceScaleFactor();
2183 bitmapSize.scale(scaleFactor);
2186 return snapshotAtSize(rect, bitmapSize, options);
2189 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
2191 IntRect snapshotRect = rect;
2192 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
2193 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
2194 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
2196 if (options & SnapshotOptionsPrinting) {
2197 PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
2201 Color documentBackgroundColor = frameView.documentBackgroundColor();
2202 Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
2203 graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
2205 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2206 double deviceScaleFactor = frame.page()->deviceScaleFactor();
2207 graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
2208 scaleFactor /= deviceScaleFactor;
2211 graphicsContext.scale(scaleFactor);
2212 graphicsContext.translate(-snapshotRect.location());
2214 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
2215 if (options & SnapshotOptionsExcludeSelectionHighlighting)
2216 shouldPaintSelection = FrameView::ExcludeSelection;
2218 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
2219 if (options & SnapshotOptionsInViewCoordinates)
2220 coordinateSpace = FrameView::ViewCoordinates;
2222 frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
2224 if (options & SnapshotOptionsPaintSelectionRectangle) {
2225 FloatRect selectionRectangle = frame.selection().selectionBounds();
2226 graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
2227 graphicsContext.strokeRect(selectionRectangle, 1);
2231 static ShareableBitmap::Configuration snapshotOptionsToBitmapConfiguration(SnapshotOptions options, WebPage& page)
2233 ShareableBitmap::Configuration configuration;
2235 if (options & SnapshotOptionsUseScreenColorSpace)
2236 configuration.colorSpace.cgColorSpace = screenColorSpace(page.corePage()->mainFrame().view());
2238 return configuration;
2241 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2243 Frame* coreFrame = m_mainFrame->coreFrame();
2247 FrameView* frameView = coreFrame->view();
2251 auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2254 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2256 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2262 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2264 Frame* coreFrame = m_mainFrame->coreFrame();
2268 FrameView* frameView = coreFrame->view();
2272 auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2275 auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2276 auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2277 auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2279 CGPDFContextBeginPage(pdfContext.get(), nullptr);
2281 GraphicsContext graphicsContext { pdfContext.get() };
2282 graphicsContext.scale({ 1, -1 });
2283 graphicsContext.translate(0, -bitmapSize.height());
2284 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2286 CGPDFContextEndPage(pdfContext.get());
2287 CGPDFContextClose(pdfContext.get());
2290 return WTFMove(data);
2294 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2296 Frame* coreFrame = m_mainFrame->coreFrame();
2300 FrameView* frameView = coreFrame->view();
2304 if (!node.renderer())
2307 LayoutRect topLevelRect;
2308 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2309 if (snapshotRect.isEmpty())
2312 double scaleFactor = 1;
2313 IntSize snapshotSize = snapshotRect.size();
2314 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2315 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2316 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2317 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2320 auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2323 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2325 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2326 double deviceScaleFactor = corePage()->deviceScaleFactor();
2327 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2328 scaleFactor /= deviceScaleFactor;
2331 graphicsContext->scale(scaleFactor);
2332 graphicsContext->translate(-snapshotRect.location());
2334 Color savedBackgroundColor = frameView->baseBackgroundColor();
2335 frameView->setBaseBackgroundColor(Color::transparent);
2336 frameView->setNodeToDraw(&node);
2338 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2340 frameView->setBaseBackgroundColor(savedBackgroundColor);
2341 frameView->setNodeToDraw(nullptr);
2346 void WebPage::pageDidScroll()
2348 #if PLATFORM(IOS_FAMILY)
2349 if (!m_inDynamicSizeUpdate)
2350 m_dynamicSizeUpdateHistory.clear();
2352 m_uiClient->pageDidScroll(this);
2354 m_pageScrolledHysteresis.impulse();
2356 send(Messages::WebPageProxy::PageDidScroll());
2359 void WebPage::pageStoppedScrolling()
2361 // Maintain the current history item's scroll position up-to-date.
2362 if (Frame* frame = m_mainFrame->coreFrame())
2363 frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2366 #if ENABLE(CONTEXT_MENUS)
2367 WebContextMenu* WebPage::contextMenu()
2370 m_contextMenu = WebContextMenu::create(this);
2371 return m_contextMenu.get();
2374 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2376 corePage()->contextMenuController().clearContextMenu();
2378 // Simulate a mouse click to generate the correct menu.
2379 PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2380 corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2381 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2382 auto* menu = handled ? contextMenu() : nullptr;
2383 PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2384 corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2392 static const WebEvent* g_currentEvent = 0;
2394 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2395 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2396 // platform events passed to the event handler code.
2397 const WebEvent* WebPage::currentEvent()
2399 return g_currentEvent;
2402 void WebPage::freezeLayerTree(LayerTreeFreezeReason reason)
2404 m_LayerTreeFreezeReasons.add(reason);
2405 updateDrawingAreaLayerTreeFreezeState();
2408 void WebPage::unfreezeLayerTree(LayerTreeFreezeReason reason)
2410 m_LayerTreeFreezeReasons.remove(reason);
2411 updateDrawingAreaLayerTreeFreezeState();
2414 void WebPage::updateDrawingAreaLayerTreeFreezeState()
2418 m_drawingArea->setLayerTreeStateIsFrozen(!!m_LayerTreeFreezeReasons);
2421 void WebPage::callVolatilityCompletionHandlers(bool succeeded)
2423 auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2424 for (auto& completionHandler : completionHandlers)
2425 completionHandler(succeeded);
2428 void WebPage::layerVolatilityTimerFired()
2430 Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2431 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2432 if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2433 m_layerVolatilityTimer.stop();
2435 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Succeeded in marking layers as volatile", this);
2437 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Failed to mark layers as volatile within %gms", this, maximumLayerVolatilityTimerInterval.milliseconds());
2438 callVolatilityCompletionHandlers(didSucceed);
2442 RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.milliseconds());
2443 m_layerVolatilityTimer.startRepeating(newInterval);
2446 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2448 return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2451 void WebPage::markLayersVolatile(WTF::Function<void (bool)>&& completionHandler)
2453 RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2455 if (m_layerVolatilityTimer.isActive())
2456 m_layerVolatilityTimer.stop();
2458 if (completionHandler)
2459 m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2461 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2462 if (didSucceed || m_isSuspendedUnderLock) {
2464 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2466 // 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.
2467 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2469 callVolatilityCompletionHandlers(didSucceed);
2473 RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.milliseconds());
2474 m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2477 void WebPage::cancelMarkLayersVolatile()
2479 RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2480 m_layerVolatilityTimer.stop();
2481 m_markLayersAsVolatileCompletionHandlers.clear();
2484 class CurrentEvent {
2486 explicit CurrentEvent(const WebEvent& event)
2487 : m_previousCurrentEvent(g_currentEvent)
2489 g_currentEvent = &event;
2494 g_currentEvent = m_previousCurrentEvent;
2498 const WebEvent* m_previousCurrentEvent;
2501 #if ENABLE(CONTEXT_MENUS)
2502 static bool isContextClick(const PlatformMouseEvent& event)
2505 return WebEventFactory::shouldBeHandledAsContextClick(event);
2507 return event.button() == WebCore::RightButton;
2511 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2513 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2514 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2516 Frame* frame = &page->corePage()->mainFrame();
2517 if (result.innerNonSharedNode())
2518 frame = result.innerNonSharedNode()->document().frame();
2520 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2522 page->contextMenu()->show();
2527 void WebPage::contextMenuForKeyEvent()
2529 corePage()->contextMenuController().clearContextMenu();
2531 Frame& frame = m_page->focusController().focusedOrMainFrame();
2532 bool handled = frame.eventHandler().sendContextMenuEventForKey();
2534 contextMenu()->show();
2538 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2540 Frame& frame = page->corePage()->mainFrame();
2544 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2546 switch (platformMouseEvent.type()) {
2547 case PlatformEvent::MousePressed: {
2548 #if ENABLE(CONTEXT_MENUS)
2549 if (isContextClick(platformMouseEvent))
2550 page->corePage()->contextMenuController().clearContextMenu();
2553 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2554 #if ENABLE(CONTEXT_MENUS)
2555 if (isContextClick(platformMouseEvent))
2556 handled = handleContextMenuEvent(platformMouseEvent, page);
2560 case PlatformEvent::MouseReleased:
2561 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2563 case PlatformEvent::MouseMoved:
2565 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2566 // button is currently pressed. It is possible that neither of those things will be true since on
2567 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2568 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2569 // efficient scrollbars-only version of the event.
2570 if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2571 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2573 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2575 case PlatformEvent::MouseForceChanged:
2576 case PlatformEvent::MouseForceDown:
2577 case PlatformEvent::MouseForceUp:
2578 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2581 ASSERT_NOT_REACHED();
2586 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2588 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2590 m_userActivityHysteresis.impulse();
2592 bool shouldHandleEvent = true;
2594 #if ENABLE(CONTEXT_MENUS)
2595 // Don't try to handle any pending mouse events if a context menu is showing.
2596 if (m_isShowingContextMenu)
2597 shouldHandleEvent = false;
2599 #if ENABLE(DRAG_SUPPORT)
2600 if (m_isStartingDrag)
2601 shouldHandleEvent = false;
2604 if (!shouldHandleEvent) {
2605 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2609 bool handled = false;
2611 #if !PLATFORM(IOS_FAMILY)
2612 if (!handled && m_headerBanner)
2613 handled = m_headerBanner->mouseEvent(mouseEvent);
2614 if (!handled && m_footerBanner)
2615 handled = m_footerBanner->mouseEvent(mouseEvent);
2616 #endif // !PLATFORM(IOS_FAMILY)
2619 CurrentEvent currentEvent(mouseEvent);
2620 handled = handleMouseEvent(mouseEvent, this);
2623 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2626 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2628 Frame& frame = page->mainFrame();
2632 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2633 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2636 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2638 m_userActivityHysteresis.impulse();
2640 CurrentEvent currentEvent(wheelEvent);
2642 bool handled = handleWheelEvent(wheelEvent, m_page.get());
2644 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2647 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2649 if (!page->mainFrame().view())
2652 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2653 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2654 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2657 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2659 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2661 m_userActivityHysteresis.impulse();
2663 PlatformKeyboardEvent::setCurrentModifierState(platform(keyboardEvent).modifiers());
2665 CurrentEvent currentEvent(keyboardEvent);
2667 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2668 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2670 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2672 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2675 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2677 bool isEnabled = false;
2679 Frame& frame = m_page->focusController().focusedOrMainFrame();
2680 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2681 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2683 Editor::Command command = frame.editor().command(commandName);
2684 state = command.state();
2685 isEnabled = command.isSupported() && command.isEnabled();
2688 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2691 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2693 executeEditingCommand(commandName, argument);
2696 void WebPage::setNeedsFontAttributes(bool needsFontAttributes)
2698 if (m_needsFontAttributes == needsFontAttributes)
2701 m_needsFontAttributes = needsFontAttributes;
2703 if (m_needsFontAttributes)
2704 sendPartialEditorStateAndSchedulePostLayoutUpdate();
2707 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest, WebBackForwardListProxy::OverwriteExistingItem overwrite)
2709 // Since we're merely restoring HistoryItems from the UIProcess, there is no need to send HistoryItem update notifications back to the UIProcess.
2710 // Also, with process-swap on navigation, these updates may actually overwrite important state in the UIProcess such as the scroll position.
2711 SetForScope<void (*)(WebCore::HistoryItem&)> bypassHistoryItemUpdateNotifications(WebCore::notifyHistoryItemChanged, [](WebCore::HistoryItem&){});
2712 for (const auto& itemState : itemStates) {
2713 auto historyItem = toHistoryItem(itemState);
2714 historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2715 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, overwrite);
2719 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2721 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes, WebBackForwardListProxy::OverwriteExistingItem::No);
2724 void WebPage::updateBackForwardListForReattach(const Vector<WebKit::BackForwardListItemState>& itemStates)
2726 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2729 void WebPage::setCurrentHistoryItemForReattach(WebKit::BackForwardListItemState&& itemState)
2731 auto historyItem = toHistoryItem(itemState);
2732 auto& historyItemRef = historyItem.get();
2733 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2734 corePage()->mainFrame().loader().history().setCurrentItem(historyItemRef);
2737 void WebPage::requestFontAttributesAtSelectionStart(CallbackID callbackID)
2739 auto attributes = m_page->focusController().focusedOrMainFrame().editor().fontAttributesAtSelectionStart();
2740 send(Messages::WebPageProxy::FontAttributesCallback(attributes, callbackID));
2743 void WebPage::cancelGesturesBlockedOnSynchronousReplies()
2745 #if ENABLE(IOS_TOUCH_EVENTS)
2746 if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2750 #if PLATFORM(IOS_FAMILY)
2751 if (auto reply = WTFMove(m_pendingSynchronousPositionInformationReply))
2752 reply(InteractionInformationAtPosition::invalidInformation());
2756 #if ENABLE(TOUCH_EVENTS)
2757 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2759 if (!page->mainFrame().view())
2762 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2766 #if ENABLE(IOS_TOUCH_EVENTS)
2767 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2769 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2771 m_lastInteractionLocation = touchEvent.position();
2772 CurrentEvent currentEvent(touchEvent);
2773 handled = handleTouchEvent(touchEvent, m_page.get());
2774 updatePotentialTapSecurityOrigin(touchEvent, handled);
2777 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, CompletionHandler<void(bool)>&& reply)
2779 m_pendingSynchronousTouchEventReply = WTFMove(reply);
2781 EventDispatcher::TouchEventQueue queuedEvents;
2782 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2783 dispatchAsynchronousTouchEvents(queuedEvents);
2785 bool handled = true;
2786 dispatchTouchEvent(touchEvent, handled);
2788 if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2792 void WebPage::updatePotentialTapSecurityOrigin(const WebTouchEvent& touchEvent, bool wasHandled)
2797 if (!touchEvent.isPotentialTap())
2800 if (touchEvent.type() != WebEvent::TouchStart)
2803 auto& mainFrame = m_page->mainFrame();
2804 auto document = mainFrame.document();
2808 if (!document->handlingTouchEvent())
2811 Frame* touchEventTargetFrame = &mainFrame;
2812 while (auto subframe = touchEventTargetFrame->eventHandler().touchEventTargetSubframe())
2813 touchEventTargetFrame = subframe;
2815 auto& touches = touchEventTargetFrame->eventHandler().touches();
2816 if (touches.isEmpty())
2819 ASSERT(touches.size() == 1);
2821 if (auto targetDocument = touchEventTargetFrame->document())
2822 m_potentialTapSecurityOrigin = &targetDocument->securityOrigin();
2824 #elif ENABLE(TOUCH_EVENTS)
2825 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2827 CurrentEvent currentEvent(touchEvent);
2829 bool handled = handleTouchEvent(touchEvent, m_page.get());
2831 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2835 #if ENABLE(POINTER_EVENTS)
2836 void WebPage::cancelPointer(WebCore::PointerID pointerId, const WebCore::IntPoint& documentPoint)
2838 m_page->pointerCaptureController().cancelPointer(pointerId, documentPoint);
2842 #if ENABLE(MAC_GESTURE_EVENTS)
2843 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2845 if (!page->mainFrame().view())
2848 return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2851 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2853 CurrentEvent currentEvent(gestureEvent);
2854 bool handled = handleGestureEvent(gestureEvent, m_page.get());
2855 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2859 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2861 return page->userInputBridge().scrollRecursively(direction, granularity);
2864 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2866 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2869 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2871 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2874 void WebPage::centerSelectionInVisibleArea()
2876 Frame& frame = m_page->focusController().focusedOrMainFrame();
2877 frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2878 findController().showFindIndicatorInSelection();
2881 bool WebPage::isControlledByAutomation() const
2883 return m_page->isControlledByAutomation();
2886 void WebPage::setControlledByAutomation(bool controlled)
2888 m_page->setControlledByAutomation(controlled);
2891 void WebPage::connectInspector(const String& targetId, Inspector::FrontendChannel::ConnectionType connectionType)
2893 m_inspectorTargetController->connectInspector(targetId, connectionType);
2896 void WebPage::disconnectInspector(const String& targetId)
2898 m_inspectorTargetController->disconnectInspector(targetId);
2901 void WebPage::sendMessageToTargetBackend(const String& targetId, const String& message)
2903 m_inspectorTargetController->sendMessageToTargetBackend(targetId, message);
2906 void WebPage::insertNewlineInQuotedContent()
2908 Frame& frame = m_page->focusController().focusedOrMainFrame();
2909 if (frame.selection().isNone())
2911 frame.editor().insertParagraphSeparatorInQuotedContent();
2914 #if ENABLE(REMOTE_INSPECTOR)
2915 void WebPage::setIndicating(bool indicating)
2917 m_page->inspectorController().setIndicating(indicating);
2921 void WebPage::setBackgroundColor(const Optional<WebCore::Color>& backgroundColor)
2923 if (m_backgroundColor == backgroundColor)
2926 m_backgroundColor = backgroundColor;
2928 if (FrameView* frameView = mainFrameView())
2929 frameView->updateBackgroundRecursively(backgroundColor);
2931 m_drawingArea->setNeedsDisplay();
2935 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
2937 if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
2938 LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
2942 m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
2944 setTopContentInset(contentInset);
2946 deallocateSendRightSafely(fencePort.port());
2950 void WebPage::setTopContentInset(float contentInset)
2952 if (contentInset == m_page->topContentInset())
2955 m_page->setTopContentInset(contentInset);
2957 for (auto* pluginView : m_pluginViews)
2958 pluginView->topContentInsetDidChange();
2961 void WebPage::viewWillStartLiveResize()
2966 // FIXME: This should propagate to all ScrollableAreas.
2967 Frame& frame = m_page->focusController().focusedOrMainFrame();
2968 if (FrameView* view = frame.view())
2969 view->willStartLiveResize();
2972 void WebPage::viewWillEndLiveResize()
2977 // FIXME: This should propagate to all ScrollableAreas.
2978 Frame& frame = m_page->focusController().focusedOrMainFrame();
2979 if (FrameView* view = frame.view())
2980 view->willEndLiveResize();
2983 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
2988 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2990 Frame& frame = m_page->focusController().focusedOrMainFrame();
2991 frame.document()->setFocusedElement(0);
2993 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2994 PlatformKeyboardEvent platformEvent(platform(event));
2995 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2996 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
2998 send(Messages::WebPageProxy::VoidCallback(callbackID));
3002 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
3003 send(Messages::WebPageProxy::VoidCallback(callbackID));
3006 void WebPage::setCanStartMediaTimerFired()
3009 m_page->setCanStartMedia(true);
3012 void WebPage::updateIsInWindow(bool isInitialState)
3014 bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
3017 m_setCanStartMediaTimer.stop();
3018 m_page->setCanStartMedia(false);
3020 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
3021 if (!isInitialState)
3022 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
3024 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
3025 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
3026 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
3027 if (m_mayStartMediaWhenInWindow)
3028 m_setCanStartMediaTimer.startOneShot(0_s);
3030 WebProcess::singleton().pageDidEnterWindow(m_pageID);
3037 void WebPage::visibilityDidChange()
3039 bool isVisible = m_activityState.contains(ActivityState::IsVisible);
3041 // We save the document / scroll state when backgrounding a tab so that we are able to restore it
3042 // if it gets terminated while in the background.
3043 if (auto* frame = m_mainFrame->coreFrame())
3044 frame->loader().history().saveDocumentAndScrollState();
3048 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
3050 LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
3052 auto changed = m_activityState ^ activityState;
3053 m_activityState = activityState;
3056 updateThrottleState();
3058 ASSERT_WITH_MESSAGE(m_page, "setActivityState called on %" PRIu64 " but WebCore page was null", pageID());
3060 SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
3061 m_page->setActivityState(activityState);
3064 for (auto* pluginView : m_pluginViews)
3065 pluginView->activityStateDidChange(changed);
3067 m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
3068 WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
3070 if (changed & ActivityState::IsInWindow)
3073 if (changed & ActivityState::IsVisible)
3074 visibilityDidChange();
3077 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
3079 m_layerHostingMode = layerHostingMode;
3081 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
3083 for (auto* pluginView : m_pluginViews)
3084 pluginView->setLayerHostingMode(m_layerHostingMode);
3087 void WebPage::setSessionID(PAL::SessionID sessionID)
3089 m_page->setSessionID(sessionID);
3092 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyCheckIdentifier identifier, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, Optional<WebsitePoliciesData>&& websitePolicies)
3094 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3097 frame->didReceivePolicyDecision(listenerID, identifier, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
3100 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
3102 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3105 frame->continueWillSubmitForm(listenerID);
3108 void WebPage::didStartPageTransition()
3110 freezeLayerTree(LayerTreeFreezeReason::PageTransition);
3113 bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
3115 m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
3116 m_isFocusingElementDueToUserInteraction = false;
3117 m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
3119 if (hasPreviouslyFocusedDueToUserInteraction)
3120 send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
3121 if (m_needsHiddenContentEditableQuirk) {
3122 m_needsHiddenContentEditableQuirk = false;
3123 send(Messages::WebPageProxy::SetNeedsHiddenContentEditableQuirk(m_needsHiddenContentEditableQuirk));
3125 if (m_needsPlainTextQuirk) {
3126 m_needsPlainTextQuirk = false;
3127 send(Messages::WebPageProxy::SetNeedsPlainTextQuirk(m_needsPlainTextQuirk));
3132 void WebPage::didCompletePageTransition()
3134 unfreezeLayerTree(LayerTreeFreezeReason::PageTransition);
3136 bool isInitialEmptyDocument = !m_mainFrame;
3137 if (!isInitialEmptyDocument)
3138 unfreezeLayerTree(LayerTreeFreezeReason::ProcessSwap);
3141 void WebPage::show()
3143 send(Messages::WebPageProxy::ShowPage());
3146 String WebPage::userAgent(const URL& webCoreURL) const
3148 return userAgent(nullptr, webCoreURL);
3151 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
3154 String userAgent = m_loaderClient->userAgentForURL(*frame, webcoreURL);
3155 if (!userAgent.isEmpty())
3159 String userAgent = platformUserAgent(webcoreURL);
3160 if (!userAgent.isEmpty())
3165 void WebPage::setUserAgent(const String& userAgent)
3167 if (m_userAgent == userAgent)
3170 m_userAgent = userAgent;
3173 m_page->userAgentChanged();
3176 void WebPage::suspendActiveDOMObjectsAndAnimations()
3178 m_page->suspendActiveDOMObjectsAndAnimations();
3181 void WebPage::resumeActiveDOMObjectsAndAnimations()
3183 m_page->resumeActiveDOMObjectsAndAnimations();
3186 IntPoint WebPage::screenToRootView(const IntPoint& point)
3188 IntPoint windowPoint;
3189 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
3193 IntRect WebPage::rootViewToScreen(const IntRect& rect)
3196 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
3200 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
3202 IntPoint windowPoint;
3203 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
3207 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
3210 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
3214 KeyboardUIMode WebPage::keyboardUIMode()
3216 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
3217 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
3220 void WebPage::runJavaScript(const String& script, bool forceUserGesture, Optional<String> worldName, CallbackID callbackID)
3222 // NOTE: We need to be careful when running scripts that the objects we depend on don't
3223 // disappear during script execution.
3225 RefPtr<SerializedScriptValue> serializedResultValue;
3226 JSLockHolder lock(commonVM());
3227 bool hadException = true;
3228 ExceptionDetails details;
3229 auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
3231 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
3232 hadException = false;
3233 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
3234 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
3238 IPC::DataReference dataReference;
3239 if (serializedResultValue)
3240 dataReference = serializedResultValue->data();
3241 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
3244 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
3246 runJavaScript(script, forceUserGesture, WTF::nullopt, callbackID);
3249 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
3251 runJavaScript(script, forceUserGesture, worldName, callbackID);
3254 void WebPage::getContentsAsString(CallbackID callbackID)
3256 String resultString = m_mainFrame->contentsAsString();
3257 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3261 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
3263 send(Messages::WebPageProxy::DataCallback({ MHTMLArchive::generateMHTMLData(m_page.get()) }, callbackID));
3267 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3269 String resultString = renderTreeExternalRepresentation();
3270 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3273 static Frame* frameWithSelection(Page* page)
3275 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3276 if (frame->selection().isRange())
3283 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3286 RetainPtr<CFDataRef> data;
3287 if (Frame* frame = frameWithSelection(m_page.get()))
3288 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3291 IPC::SharedBufferDataReference dataReference;
3294 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3296 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3299 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3301 WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3302 String resultString = focusedOrMainFrame->selectionAsString();
3303 if (resultString.isEmpty())
3304 resultString = focusedOrMainFrame->contentsAsString();
3305 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3308 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3310 String resultString;
3311 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3312 resultString = frame->source();
3314 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3317 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3319 RefPtr<SharedBuffer> buffer;
3320 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3321 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3322 buffer = pluginView->liveResourceData();
3324 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3325 buffer = loader->mainResourceData();
3329 IPC::SharedBufferDataReference dataReference;
3331 dataReference = { *buffer };
3332 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3335 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3337 DocumentLoader* loader = frame->loader().documentLoader();
3341 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3345 return &subresource->data();
3348 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3350 RefPtr<SharedBuffer> buffer;
3351 if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3352 URL resourceURL(URL(), resourceURLString);
3353 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3356 IPC::SharedBufferDataReference dataReference;
3358 dataReference = { *buffer };
3359 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3362 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3365 RetainPtr<CFDataRef> data;
3366 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3367 data = frame->webArchiveData(nullptr, nullptr);
3369 UNUSED_PARAM(frameID);
3372 IPC::SharedBufferDataReference dataReference;
3375 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3377 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3380 void WebPage::forceRepaintWithoutCallback()
3382 m_drawingArea->forceRepaint();
3385 void WebPage::forceRepaint(CallbackID callbackID)
3387 if (m_drawingArea->forceRepaintAsync(callbackID))
3390 forceRepaintWithoutCallback();
3391 send(Messages::WebPageProxy::VoidCallback(callbackID));
3394 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3396 WebPreferencesStore::removeTestRunnerOverrides();
3397 updatePreferences(store);
3400 void WebPage::updatePreferences(const WebPreferencesStore& store)
3402 updatePreferencesGenerated(store);
3404 Settings& settings = m_page->settings();
3407 if (!settings.acceleratedCompositingEnabled()) {
3408 RELEASE_LOG_IF_ALLOWED("%p - WebPage - acceleratedCompositingEnabled setting was false. WebKit cannot function in this mode; changing setting to true", this);
3409 settings.setAcceleratedCompositingEnabled(true);
3413 bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3414 settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3415 settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3416 settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3417 settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3418 settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3419 settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3420 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3421 settings.setFrameFlattening(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()) ? WebCore::FrameFlattening::FullyEnabled : WebCore::FrameFlattening::Disabled);
3422 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3423 #if ENABLE(DATA_DETECTION)
3424 settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3427 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3429 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3430 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3431 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3432 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3434 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3435 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3437 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3438 setSessionID(PAL::SessionID::legacyPrivateSessionID());
3439 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3440 setSessionID(PAL::SessionID::defaultSessionID());
3442 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3443 if (m_processSuppressionEnabled != processSuppressionEnabled) {
3444 m_processSuppressionEnabled = processSuppressionEnabled;
3445 updateThrottleState();
3449 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3451 #if ENABLE(PAYMENT_REQUEST)
3452 settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3455 // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3456 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3458 #if PLATFORM(IOS_FAMILY)
3459 m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3460 m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3461 setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3463 settings.setUseImageDocumentForSubframePDF(true);
3465 DeprecatedGlobalSettings::setAVKitEnabled(true);
3469 #if ENABLE(SERVICE_WORKER)
3470 if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3471 ASSERT(parentProcessHasServiceWorkerEntitlement());
3472 if (!parentProcessHasServiceWorkerEntitlement())
3473 RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3477 settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3480 m_drawingArea->updatePreferences(store);
3483 #if ENABLE(DATA_DETECTION)
3485 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3487 DataDetectionResult dataDetectionResult;
3488 dataDetectionResult.results = detectionResults;
3489 send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3492 void WebPage::removeDataDetectedLinks(CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3494 for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3495 auto document = makeRefPtr(frame->document());
3499 DataDetection::removeDataDetectedLinksInDocument(*document);
3500 frame->setDataDetectionResults(nullptr);
3502 completionHandler({ m_page->mainFrame().dataDetectionResults() });
3505 void WebPage::detectDataInAllFrames(uint64_t types, CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3507 auto dataDetectorTypes = static_cast<WebCore::DataDetectorTypes>(types);
3508 for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3509 auto document = makeRefPtr(frame->document());
3513 RefPtr<Range> range = Range::create(*document, Position { document.get(), Position::PositionIsBeforeChildren }, Position { document.get(), Position::PositionIsAfterChildren });
3514 frame->setDataDetectionResults(DataDetection::detectContentInRange(range, dataDetectorTypes, m_dataDetectionContext.get()));
3516 completionHandler({ m_page->mainFrame().dataDetectionResults() });
3519 #endif // ENABLE(DATA_DETECTION)
3522 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3524 FrameView* frameView = corePage()->mainFrame().view();
3528 layerTransaction.setContentsSize(frameView->contentsSize());
3529 layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3530 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3531 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3532 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3534 layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3535 layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3536 layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3538 #if PLATFORM(IOS_FAMILY)
3539 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3540 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3541 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3542 layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3543 layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3544 layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3545 layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3546 layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3547 layerTransaction.setIsInStableState(m_isInStableState);
3548 layerTransaction.setAllowsUserScaling(allowsUserScaling());
3549 if (m_pendingDynamicViewportSizeUpdateID) {
3550 layerTransaction.setDynamicViewportSizeUpdateID(*m_pendingDynamicViewportSizeUpdateID);
3551 m_pendingDynamicViewportSizeUpdateID = WTF::nullopt;
3553 if (m_lastTransactionPageScaleFactor != layerTransaction.pageScaleFactor()) {
3554 m_lastTransactionPageScaleFactor = layerTransaction.pageScaleFactor();
3555 m_lastTransactionIDWithScaleChange = layerTransaction.transactionID();
3559 layerTransaction.setScrollPosition(frameView->scrollPosition());
3561 if (m_hasPendingEditorStateUpdate) {
3562 layerTransaction.setEditorState(editorState());
3563 m_hasPendingEditorStateUpdate = false;
3567 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3569 #if PLATFORM(IOS_FAMILY)
3570 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3571 Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3572 m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3574 m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3577 UNUSED_PARAM(timestamp);
3582 void WebPage::willDisplayPage()
3584 m_page->willDisplayPage();
3587 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3591 if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3592 m_inspector = WebInspector::create(this);
3593 return m_inspector.get();
3596 WebInspectorUI* WebPage::inspectorUI()
3601 m_inspectorUI = WebInspectorUI::create(*this);
3602 return m_inspectorUI.get();
3605 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3609 if (!m_remoteInspectorUI)
3610 m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3611 return m_remoteInspectorUI.get();
3614 void WebPage::inspectorFrontendCountChanged(unsigned count)
3616 send(Messages::WebPageProxy::DidChangeInspectorFrontendCount(count));
3619 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3620 PlaybackSessionManager& WebPage::playbackSessionManager()
3622 if (!m_playbackSessionManager)
3623 m_playbackSessionManager = PlaybackSessionManager::create(*this);
3624 return *m_playbackSessionManager;
3627 VideoFullscreenManager& WebPage::videoFullscreenManager()
3629 if (!m_videoFullscreenManager)
3630 m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3631 return *m_videoFullscreenManager;
3634 void WebPage::videoControlsManagerDidChange()
3636 #if ENABLE(FULLSCREEN_API)
3637 if (auto* manager = fullScreenManager())
3638 manager->videoControlsManagerDidChange();
3644 #if PLATFORM(IOS_FAMILY)
3645 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3647 m_page->setAllowsMediaDocumentInlinePlayback(allows);
3651 #if ENABLE(FULLSCREEN_API)
3652 WebFullScreenManager* WebPage::fullScreenManager()
3654 if (!m_fullScreenManager)
3655 m_fullScreenManager = WebFullScreenManager::create(this);
3656 return m_fullScreenManager.get();
3660 void WebPage::addConsoleMessage(uint64_t frameID, MessageSource messageSource, MessageLevel messageLevel, const String& message, uint64_t requestID)
3662 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3663 frame->addConsoleMessage(messageSource, messageLevel, message, requestID);
3666 void WebPage::sendCSPViolationReport(uint64_t frameID, const URL& reportURL, IPC::FormDataReference&& reportData)
3668 auto report = reportData.takeData();
3671 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3672 PingLoader::sendViolationReport(*frame->coreFrame(), reportURL, report.releaseNonNull(), ViolationReportType::ContentSecurityPolicy);
3675 void WebPage::enqueueSecurityPolicyViolationEvent(uint64_t frameID, SecurityPolicyViolationEvent::Init&& eventInit)
3677 auto* frame = WebProcess::singleton().webFrame(frameID);
3680 auto* coreFrame = frame->coreFrame();
3683 if (auto* document = coreFrame->document())
3684 document->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
3687 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3689 if (m_notificationPermissionRequestManager)
3690 return m_notificationPermissionRequestManager.get();
3692 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3693 return m_notificationPermissionRequestManager.get();
3696 #if ENABLE(DRAG_SUPPORT)
3699 void WebPage::performDragControllerAction(DragControllerAction action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3702 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3706 DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3708 case DragControllerAction::Entered: {
3709 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3710 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3713 case DragControllerAction::Updated: {
3714 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3715 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3718 case DragControllerAction::Exited:
3719 m_page->dragController().dragExited(dragData);
3722 case DragControllerAction::PerformDragOperation: {
3723 m_page->dragController().performDragOperation(dragData);
3727 ASSERT_NOT_REACHED();
3730 void WebPage::performDragControllerAction(DragControllerAction action, const WebCore::DragData& dragData, SandboxExtension::Handle&& sandboxExtensionHandle, SandboxExtension::HandleArray&& sandboxExtensionsHandleArray)
3733 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3738 case DragControllerAction::Entered: {
3739 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3740 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), m_page->dragCaretController().caretRectInRootViewCoordinates(), m_page->dragCaretController().editableElementRectInRootViewCoordinates()));
3743 case DragControllerAction::Updated: {
3744 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3745 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), m_page->dragCaretController().caretRectInRootViewCoordinates(), m_page->dragCaretController().editableElementRectInRootViewCoordinates()));
3748 case DragControllerAction::Exited:
3749 m_page->dragController().dragExited(dragData);
3750 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3753 case DragControllerAction::PerformDragOperation: {
3754 ASSERT(!m_pendingDropSandboxExtension);
3756 m_pendingDropSandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
3757 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3758 if (auto extension = SandboxExtension::create(WTFMove(sandboxExtensionsHandleArray[i])))
3759 m_pendingDropExtensionsForFileUpload.append(extension);
3762 bool handled = m_page->dragController().performDragOperation(dragData);
3764 // If we started loading a local file, the sandbox extension tracker would have adopted this
3765 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3766 m_pendingDropSandboxExtension = nullptr;
3768 m_pendingDropExtensionsForFileUpload.clear();
3769 send(Messages::WebPageProxy::DidPerformDragOperation(handled));
3773 ASSERT_NOT_REACHED();
3777 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3779 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3780 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3782 m_page->dragController().dragEnded();
3783 FrameView* view = m_page->mainFrame().view();
3786 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3787 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), 0, WebCore::NoTap);
3788 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3790 send(Messages::WebPageProxy::DidEndDragging());
3793 void WebPage::willPerformLoadDragDestinationAction()
3795 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(WTFMove(m_pendingDropSandboxExtension));
3798 void WebPage::mayPerformUploadDragDestinationAction()
3800 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3801 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3802 m_pendingDropExtensionsForFileUpload.clear();
3805 void WebPage::didStartDrag()
3807 m_isStartingDrag = false;
3808 m_page->mainFrame().eventHandler().didStartDrag();
3811 void WebPage::dragCancelled()
3813 m_isStartingDrag = false;
3814 m_page->mainFrame().eventHandler().dragCancelled();
3817 #endif // ENABLE(DRAG_SUPPORT)
3819 WebUndoStep* WebPage::webUndoStep(WebUndoStepID stepID)
3821 return m_undoStepMap.get(stepID);
3824 void WebPage::addWebUndoStep(WebUndoStepID stepID, Ref<WebUndoStep>&& entry)
3826 auto addResult = m_undoStepMap.set(stepID, WTFMove(entry));
3827 ASSERT_UNUSED(addResult, addResult.isNewEntry);
3830 void WebPage::removeWebEditCommand(WebUndoStepID stepID)
3832 if (auto undoStep = m_undoStepMap.take(stepID))
3833 undoStep->didRemoveFromUndoManager();
3836 bool WebPage::isAlwaysOnLoggingAllowed() const
3838 return corePage() && corePage()->isAlwaysOnLoggingAllowed();
3841 void WebPage::unapplyEditCommand(WebUndoStepID stepID)
3843 auto* step = webUndoStep(stepID);
3847 step->step().unapply();
3850 void WebPage::reapplyEditCommand(WebUndoStepID stepID)
3852 auto* step = webUndoStep(stepID);
3857 step->step().reapply();
3861 void WebPage::didRemoveEditCommand(WebUndoStepID commandID)
3863 removeWebEditCommand(commandID);
3866 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3868 m_activePopupMenu = menu;
3871 #if ENABLE(INPUT_TYPE_COLOR)
3873 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3875 m_activeColorChooser = colorChooser;
3878 void WebPage::didEndColorPicker()
3880 m_activeColorChooser->didEndChooser();
3883 void WebPage::didChooseColor(const WebCore::Color& color)
3885 m_activeColorChooser->didChooseColor(color);
3890 #if ENABLE(DATALIST_ELEMENT)
3892 void WebPage::setActiveDataListSuggestionPicker(WebDataListSuggestionPicker* dataListSuggestionPicker)
3894 m_activeDataListSuggestionPicker = dataListSuggestionPicker;
3897 void WebPage::didSelectDataListOption(const String& selectedOption)
3899 m_activeDataListSuggestionPicker->didSelectOption(selectedOption);
3902 void WebPage::didCloseSuggestions()
3904 if (m_activeDataListSuggestionPicker)
3905 m_activeDataListSuggestionPicker->didCloseSuggestions();
3906 m_activeDataListSuggestionPicker = nullptr;
3911 void WebPage::setActiveOpenPanelResultListener(Ref<WebOpenPanelResultListener>&& openPanelResultListener)
3913 m_activeOpenPanelResultListener = WTFMove(openPanelResultListener);
3916 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3918 return m_page->findString(target, core(options));
3921 void WebPage::findStringMatchesFromInjectedBundle(const String& target, FindOptions options)
3923 findController().findStringMatches(target, options, 0);
3926 void WebPage::replaceStringMatchesFromInjectedBundle(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly)
3928 findController().replaceMatches(matchIndices, replacementText, selectionOnly);
3931 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3933 findController().findString(string, static_cast<FindOptions>(options), maxMatchCount);
3936 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3938 findController().findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3941 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3943 findController().getImageForFindMatch(matchIndex);
3946 void WebPage::selectFindMatch(uint32_t matchIndex)
3948 findController().selectFindMatch(matchIndex);
3951 void WebPage::hideFindUI()
3953 findController().hideFindUI();
3956 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3958 findController().countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3961 void WebPage::replaceMatches(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly, CallbackID callbackID)
3963 auto numberOfReplacements = findController().replaceMatches(matchIndices, replacementText, selectionOnly);
3964 send(Messages::WebPageProxy::UnsignedCallback(numberOfReplacements, callbackID));
3967 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3969 changeSelectedIndex(newIndex);
3970 m_activePopupMenu = nullptr;
3973 void WebPage::changeSelectedIndex(int32_t index)
3975 if (!m_activePopupMenu)
3978 m_activePopupMenu->didChangeSelectedIndex(index);
3981 #if PLATFORM(IOS_FAMILY)
3982 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3984 if (!m_activeOpenPanelResultListener)
3988 if (!iconData.isEmpty()) {
3989 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3990 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3991 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3992 icon = Icon::createIconForImage(imageRef.get());
3995 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3996 m_activeOpenPanelResultListener = nullptr;
4000 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
4002 if (!m_activeOpenPanelResultListener)
4005 m_activeOpenPanelResultListener->didChooseFiles(files);
4006 m_activeOpenPanelResultListener = nullptr;
4009 void WebPage::didCancelForOpenPanel()
4011 m_activeOpenPanelResultListener = nullptr;
4014 #if ENABLE(SANDBOX_EXTENSIONS)
4015 void WebPage::extendSandboxForFilesFromOpenPanel(SandboxExtension::HandleArray&& handles)
4017 for (size_t i = 0; i < handles.size(); ++i) {
4018 bool result = SandboxExtension::consumePermanently(handles[i]);
4020 // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
4021 WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
4027 #if ENABLE(GEOLOCATION)
4028 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
4030 geolocationPermissionRequestManager().didReceiveGeolocationPermissionDecision(geolocationID, allowed);
4034 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
4036 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
4039 #if ENABLE(MEDIA_STREAM)
4041 void WebPage::userMediaAccessWasGranted(uint64_t userMediaID, WebCore::CaptureDevice&& audioDevice, WebCore::CaptureDevice&& videoDevice, String&& mediaDeviceIdentifierHashSalt)
4043 m_userMediaPermissionRequestManager->userMediaAccessWasGranted(userMediaID, WTFMove(audioDevice), WTFMove(videoDevice), WTFMove(mediaDeviceIdentifierHashSalt));
4046 void WebPage::userMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String&& invalidConstraint)
4048 m_userMediaPermissionRequestManager->userMediaAccessWasDenied(userMediaID, static_cast<UserMediaRequest::MediaAccessDenialReason>(reason), WTFMove(invalidConstraint));
4051 void WebPage::didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vector<CaptureDevice>& devices, String&& deviceIdentifierHashSalt, bool originHasPersistentAccess)
4053 m_userMediaPermissionRequestManager->didCompleteMediaDeviceEnumeration(userMediaID, devices, WTFMove(deviceIdentifierHashSalt), originHasPersistentAccess);
4056 void WebPage::captureDevicesChanged()
4058 m_userMediaPermissionRequestManager->captureDevicesChanged();
4061 #if ENABLE(SANDBOX_EXTENSIONS)
4062 void WebPage::grantUserMediaDeviceSandboxExtensions(MediaDeviceSandboxExtensions&& extensions)
4064 m_userMediaPermissionRequestManager->grantUserMediaDeviceSandboxExtensions(WTFMove(extensions));
4067 void WebPage::revokeUserMediaDeviceSandboxExtensions(const Vector<String>& extensionIDs)
4069 m_userMediaPermissionRequestManager->revokeUserMediaDeviceSandboxExtensions(extensionIDs);
4074 #if !PLATFORM(IOS_FAMILY)
4075 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
4077 Frame& frame = m_page->focusController().focusedOrMainFrame();
4078 frame.editor().advanceToNextMisspelling(startBeforeSelection);
4082 bool WebPage::hasRichlyEditableSelection() const
4084 auto& frame = m_page->focusController().focusedOrMainFrame();
4085 if (m_page->dragCaretController().isContentRichlyEditable())
4088 return frame.selection().selection().isContentRichlyEditable();
4091 void WebPage::changeSpellingToWord(const String& word)
4093 replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
4096 void WebPage::unmarkAllMisspellings()
4098 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
4099 if (Document* document = frame->document())
4100 document->markers().removeMarkers(DocumentMarker::Spelling);
4104 void WebPage::unmarkAllBadGrammar()
4106 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
4107 if (Document* document = frame->document())
4108 document->markers().removeMarkers(DocumentMarker::Grammar);
4113 void WebPage::uppercaseWord()
4115 m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
4118 void WebPage::lowercaseWord()
4120 m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
4123 void WebPage::capitalizeWord()
4125 m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
4129 void WebPage::setTextForActivePopupMenu(int32_t index)
4131 if (!m_activePopupMenu)
4134 m_activePopupMenu->setTextForIndex(index);
4138 void WebPage::failedToShowPopupMenu()
4140 if (!m_activePopupMenu)
4143 m_activePopupMenu->client()->popupDidHide();
4147 #if ENABLE(CONTEXT_MENUS)
4148 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
4153 m_contextMenu->itemSelected(item);
4154 m_contextMenu = nullptr;
4158 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
4160 return frame->editor().replaceSelectionWithText(text, WebCore::Editor::SelectReplacement::Yes, WebCore::Editor::SmartReplace::No);