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 "WebSpeechSynthesisClient.h"
124 #include "WebStorageNamespaceProvider.h"
125 #include "WebURLSchemeHandlerProxy.h"
126 #include "WebUndoStep.h"
127 #include "WebUserContentController.h"
128 #include "WebUserMediaClient.h"
129 #include "WebValidationMessageClient.h"
130 #include "WebsiteDataStoreParameters.h"
131 #include <JavaScriptCore/APICast.h>
132 #include <JavaScriptCore/JSCInlines.h>
133 #include <JavaScriptCore/JSCJSValue.h>
134 #include <JavaScriptCore/JSLock.h>
135 #include <JavaScriptCore/ProfilerDatabase.h>
136 #include <JavaScriptCore/SamplingProfiler.h>
137 #include <WebCore/ApplicationCacheStorage.h>
138 #include <WebCore/ArchiveResource.h>
139 #include <WebCore/BackForwardController.h>
140 #include <WebCore/Chrome.h>
141 #include <WebCore/CommonVM.h>
142 #include <WebCore/ContextMenuController.h>
143 #include <WebCore/DOMPasteAccess.h>
144 #include <WebCore/DataTransfer.h>
145 #include <WebCore/DatabaseManager.h>
146 #include <WebCore/DeprecatedGlobalSettings.h>
147 #include <WebCore/DocumentFragment.h>
148 #include <WebCore/DocumentLoader.h>
149 #include <WebCore/DocumentMarkerController.h>
150 #include <WebCore/DragController.h>
151 #include <WebCore/DragData.h>
152 #include <WebCore/Editing.h>
153 #include <WebCore/Editor.h>
154 #include <WebCore/ElementIterator.h>
155 #include <WebCore/EventHandler.h>
156 #include <WebCore/EventNames.h>
157 #include <WebCore/File.h>
158 #include <WebCore/FocusController.h>
159 #include <WebCore/FontAttributeChanges.h>
160 #include <WebCore/FontAttributes.h>
161 #include <WebCore/FormState.h>
162 #include <WebCore/Frame.h>
163 #include <WebCore/FrameLoadRequest.h>
164 #include <WebCore/FrameLoaderTypes.h>
165 #include <WebCore/FrameView.h>
166 #include <WebCore/GraphicsContext3D.h>
167 #include <WebCore/HTMLAttachmentElement.h>
168 #include <WebCore/HTMLFormElement.h>
169 #include <WebCore/HTMLImageElement.h>
170 #include <WebCore/HTMLInputElement.h>
171 #include <WebCore/HTMLMenuElement.h>
172 #include <WebCore/HTMLMenuItemElement.h>
173 #include <WebCore/HTMLOListElement.h>
174 #include <WebCore/HTMLPlugInElement.h>
175 #include <WebCore/HTMLPlugInImageElement.h>
176 #include <WebCore/HTMLSelectElement.h>
177 #include <WebCore/HTMLTextAreaElement.h>
178 #include <WebCore/HTMLTextFormControlElement.h>
179 #include <WebCore/HTMLUListElement.h>
180 #include <WebCore/HistoryController.h>
181 #include <WebCore/HistoryItem.h>
182 #include <WebCore/HitTestResult.h>
183 #include <WebCore/InspectorController.h>
184 #include <WebCore/JSDOMExceptionHandling.h>
185 #include <WebCore/JSDOMWindow.h>
186 #include <WebCore/KeyboardEvent.h>
187 #include <WebCore/LocalizedStrings.h>
188 #include <WebCore/MIMETypeRegistry.h>
189 #include <WebCore/MouseEvent.h>
190 #include <WebCore/NotImplemented.h>
191 #include <WebCore/Page.h>
192 #include <WebCore/PageCache.h>
193 #include <WebCore/PageConfiguration.h>
194 #include <WebCore/PingLoader.h>
195 #include <WebCore/PlatformKeyboardEvent.h>
196 #include <WebCore/PlatformMediaSessionManager.h>
197 #include <WebCore/PluginDocument.h>
198 #include <WebCore/PointerCaptureController.h>
199 #include <WebCore/PrintContext.h>
200 #include <WebCore/PromisedAttachmentInfo.h>
201 #include <WebCore/Quirks.h>
202 #include <WebCore/Range.h>
203 #include <WebCore/RegistrableDomain.h>
204 #include <WebCore/RemoteDOMWindow.h>
205 #include <WebCore/RemoteFrame.h>
206 #include <WebCore/RenderLayer.h>
207 #include <WebCore/RenderTheme.h>
208 #include <WebCore/RenderTreeAsText.h>
209 #include <WebCore/RenderView.h>
210 #include <WebCore/ResourceLoadStatistics.h>
211 #include <WebCore/ResourceRequest.h>
212 #include <WebCore/ResourceResponse.h>
213 #include <WebCore/RuntimeEnabledFeatures.h>
214 #include <WebCore/SchemeRegistry.h>
215 #include <WebCore/ScriptController.h>
216 #include <WebCore/SerializedScriptValue.h>
217 #include <WebCore/ServiceWorkerProvider.h>
218 #include <WebCore/Settings.h>
219 #include <WebCore/ShadowRoot.h>
220 #include <WebCore/SharedBuffer.h>
221 #include <WebCore/StyleProperties.h>
222 #include <WebCore/SubframeLoader.h>
223 #include <WebCore/SubstituteData.h>
224 #include <WebCore/TextIterator.h>
225 #include <WebCore/UserGestureIndicator.h>
226 #include <WebCore/UserInputBridge.h>
227 #include <WebCore/UserScript.h>
228 #include <WebCore/UserStyleSheet.h>
229 #include <WebCore/UserTypingGestureIndicator.h>
230 #include <WebCore/VisiblePosition.h>
231 #include <WebCore/VisibleUnits.h>
232 #include <WebCore/WebGLStateTracker.h>
233 #include <WebCore/WritingDirection.h>
234 #include <WebCore/markup.h>
235 #include <pal/SessionID.h>
236 #include <wtf/ProcessID.h>
237 #include <wtf/RunLoop.h>
238 #include <wtf/SetForScope.h>
239 #include <wtf/text/TextStream.h>
241 #if ENABLE(DATA_DETECTION)
242 #include "DataDetectionResult.h"
246 #include <WebCore/MHTMLArchive.h>
249 #if ENABLE(POINTER_LOCK)
250 #include <WebCore/PointerLockController.h>
254 #include "PDFPlugin.h"
255 #include "PlaybackSessionManager.h"
256 #include "RemoteLayerTreeTransaction.h"
257 #include "TextCheckingControllerProxy.h"
258 #include "TouchBarMenuData.h"
259 #include "TouchBarMenuItemData.h"
260 #include "VideoFullscreenManager.h"
261 #include "WKStringCF.h"
262 #include <WebCore/LegacyWebArchive.h>
263 #include <WebCore/UTIRegistry.h>
264 #include <wtf/MachSendRight.h>
268 #include "WebPrintOperationGtk.h"
269 #include "WebSelectionData.h"
273 #if PLATFORM(IOS_FAMILY)
274 #include "InteractionInformationAtPosition.h"
275 #include "InteractionInformationRequest.h"
276 #include "RemoteLayerTreeDrawingArea.h"
277 #include "WebAutocorrectionContext.h"
278 #include <CoreGraphics/CoreGraphics.h>
279 #include <WebCore/Icon.h>
280 #include <pal/spi/cocoa/CoreTextSPI.h>
284 #include <WebCore/LocalDefaultSystemAppearance.h>
285 #include <pal/spi/cf/CFUtilitiesSPI.h>
289 #include <wtf/RefCountedLeakCounter.h>
292 #if ENABLE(DATA_DETECTION)
293 #include <WebCore/DataDetection.h>
296 #if ENABLE(VIDEO) && USE(GSTREAMER)
297 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
300 #if ENABLE(WEB_AUTHN)
301 #include "WebAuthenticatorCoordinator.h"
302 #include <WebCore/AuthenticatorCoordinator.h>
307 using namespace WebCore;
309 static const Seconds pageScrollHysteresisDuration { 300_ms };
310 static const Seconds initialLayerVolatilityTimerInterval { 20_ms };
311 static const Seconds maximumLayerVolatilityTimerInterval { 2_s };
313 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
314 #define RELEASE_LOG_ERROR_IF_ALLOWED(...) RELEASE_LOG_ERROR_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
316 class SendStopResponsivenessTimer {
318 ~SendStopResponsivenessTimer()
320 WebProcess::singleton().parentProcessConnection()->send(Messages::WebProcessProxy::StopResponsivenessTimer(), 0);
324 class DeferredPageDestructor {
326 static void createDeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
328 new DeferredPageDestructor(WTFMove(page), webPage);
332 DeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
333 : m_page(WTFMove(page))
339 void tryDestruction()
341 if (m_page->insideNestedRunLoop()) {
342 m_page->whenUnnested([this] { tryDestruction(); });
351 std::unique_ptr<Page> m_page;
352 RefPtr<WebPage> m_webPage;
355 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
357 Ref<WebPage> WebPage::create(uint64_t pageID, WebPageCreationParameters&& parameters)
359 Ref<WebPage> page = adoptRef(*new WebPage(pageID, WTFMove(parameters)));
361 if (WebProcess::singleton().injectedBundle())
362 WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
367 WebPage::WebPage(uint64_t pageID, WebPageCreationParameters&& parameters)
369 , m_viewSize(parameters.viewSize)
370 , m_alwaysShowsHorizontalScroller { parameters.alwaysShowsHorizontalScroller }
371 , m_alwaysShowsVerticalScroller { parameters.alwaysShowsVerticalScroller }
372 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
373 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
375 , m_layerHostingMode(parameters.layerHostingMode)
376 #if ENABLE(PLATFORM_DRIVEN_TEXT_CHECKING)
377 , m_textCheckingControllerProxy(makeUniqueRef<TextCheckingControllerProxy>(*this))
379 #if PLATFORM(COCOA) || PLATFORM(GTK)
380 , m_viewGestureGeometryCollector(std::make_unique<ViewGestureGeometryCollector>(*this))
381 #elif HAVE(ACCESSIBILITY) && PLATFORM(GTK)
382 , m_accessibilityObject(nullptr)
384 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
385 #if ENABLE(CONTEXT_MENUS)
386 , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
388 , m_editorClient { std::make_unique<API::InjectedBundle::EditorClient>() }
389 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
390 , m_loaderClient(std::make_unique<API::InjectedBundle::PageLoaderClient>())
391 , m_resourceLoadClient(std::make_unique<API::InjectedBundle::ResourceLoadClient>())
392 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
393 , m_findController(makeUniqueRef<FindController>(this))
394 , m_inspectorTargetController(std::make_unique<WebPageInspectorTargetController>(*this))
395 , m_userContentController(WebUserContentController::getOrCreate(parameters.userContentControllerID))
396 #if ENABLE(GEOLOCATION)
397 , m_geolocationPermissionRequestManager(makeUniqueRef<GeolocationPermissionRequestManager>(*this))
399 #if ENABLE(MEDIA_STREAM)
400 , m_userMediaPermissionRequestManager { makeUniqueRef<UserMediaPermissionRequestManager>(*this) }
402 , m_pageScrolledHysteresis([this](PAL::HysteresisState state) { if (state == PAL::HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisDuration)
403 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
404 , m_canRunModal(parameters.canRunModal)
405 #if PLATFORM(IOS_FAMILY)
406 , m_forceAlwaysUserScalable(parameters.ignoresViewportScaleLimits)
407 , m_screenSize(parameters.screenSize)
408 , m_availableScreenSize(parameters.availableScreenSize)
409 , m_overrideScreenSize(parameters.overrideScreenSize)
410 , m_deviceOrientation(parameters.deviceOrientation)
411 , m_keyboardIsAttached(parameters.keyboardIsAttached)
413 , m_layerVolatilityTimer(*this, &WebPage::layerVolatilityTimerFired)
414 , m_activityState(parameters.activityState)
415 , m_processSuppressionEnabled(true)
416 , m_userActivity("Process suppression disabled for page.")
417 , m_userActivityHysteresis([this](PAL::HysteresisState) { updateUserActivity(); })
418 , m_userInterfaceLayoutDirection(parameters.userInterfaceLayoutDirection)
419 , m_overrideContentSecurityPolicy { parameters.overrideContentSecurityPolicy }
420 , m_cpuLimit(parameters.cpuLimit)
422 , m_hostFileDescriptor(WTFMove(parameters.hostFileDescriptor))
427 m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
429 #if PLATFORM(IOS_FAMILY)
430 DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(true);
433 PageConfiguration pageConfiguration(
434 makeUniqueRef<WebEditorClient>(this),
435 WebSocketProvider::create(),
436 makeUniqueRef<WebKit::LibWebRTCProvider>(),
437 WebProcess::singleton().cacheStorageProvider(),
438 WebBackForwardListProxy::create(*this),
439 WebCookieJar::create()
441 pageConfiguration.chromeClient = new WebChromeClient(*this);
442 #if ENABLE(CONTEXT_MENUS)
443 pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
445 #if ENABLE(DRAG_SUPPORT)
446 pageConfiguration.dragClient = new WebDragClient(this);
448 pageConfiguration.inspectorClient = new WebInspectorClient(this);
449 #if USE(AUTOCORRECTION_PANEL)
450 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
453 pageConfiguration.plugInClient = new WebPlugInClient(*this);
454 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
455 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
456 pageConfiguration.diagnosticLoggingClient = std::make_unique<WebDiagnosticLoggingClient>(*this);
457 pageConfiguration.performanceLoggingClient = std::make_unique<WebPerformanceLoggingClient>(*this);
459 pageConfiguration.webGLStateTracker = std::make_unique<WebGLStateTracker>([this](bool isUsingHighPerformanceWebGL) {
460 send(Messages::WebPageProxy::SetIsUsingHighPerformanceWebGL(isUsingHighPerformanceWebGL));
463 #if ENABLE(SPEECH_SYNTHESIS)
464 pageConfiguration.speechSynthesisClient = std::make_unique<WebSpeechSynthesisClient>(*this);
468 pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(*this);
471 pageConfiguration.applicationCacheStorage = &WebProcess::singleton().applicationCacheStorage();
472 pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
473 pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
474 pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
475 pageConfiguration.userContentProvider = m_userContentController.ptr();
476 pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
478 #if ENABLE(APPLE_PAY)
479 pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinator(*this);
482 #if ENABLE(WEB_AUTHN)
483 pageConfiguration.authenticatorCoordinatorClient = std::make_unique<WebAuthenticatorCoordinator>(*this);
486 #if ENABLE(APPLICATION_MANIFEST)
487 pageConfiguration.applicationManifest = parameters.applicationManifest;
490 m_page = std::make_unique<Page>(WTFMove(pageConfiguration));
492 // Set the sessionID *before* updating the preferences as the privateBrowsingEnabled preferences may need to override it.
493 if (parameters.sessionID.isValid())
494 setSessionID(parameters.sessionID);
496 updatePreferences(parameters.store);
498 m_drawingArea = DrawingArea::create(*this, parameters);
499 m_drawingArea->setPaintingEnabled(false);
500 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
502 if (parameters.isProcessSwap)
503 freezeLayerTree(LayerTreeFreezeReason::ProcessSwap);
505 #if ENABLE(ASYNC_SCROLLING)
506 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
507 if (!m_drawingArea->supportsAsyncScrolling())
508 m_useAsyncScrolling = false;
509 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
512 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
513 m_drawingArea->updatePreferences(parameters.store);
515 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
516 setPageAndTextZoomFactors(parameters.pageZoomFactor, parameters.textZoomFactor);
518 #if ENABLE(GEOLOCATION)
519 WebCore::provideGeolocationTo(m_page.get(), *new WebGeolocationClient(*this));
521 #if ENABLE(NOTIFICATIONS)
522 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
524 #if ENABLE(MEDIA_STREAM)
525 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
528 m_page->setControlledByAutomation(parameters.controlledByAutomation);
530 m_page->setCanStartMedia(false);
531 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
533 m_page->setGroupName(m_pageGroup->identifier());
534 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
535 m_page->setUserInterfaceLayoutDirection(m_userInterfaceLayoutDirection);
536 #if PLATFORM(IOS_FAMILY)
537 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
540 platformInitialize();
542 setUseFixedLayout(parameters.useFixedLayout);
544 setUnderlayColor(parameters.underlayColor);
546 setPaginationMode(parameters.paginationMode);
547 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
548 setPageLength(parameters.pageLength);
549 setGapBetweenPages(parameters.gapBetweenPages);
550 setPaginationLineGridEnabled(parameters.paginationLineGridEnabled);
552 setUseDarkAppearance(parameters.useDarkAppearance);
554 if (parameters.isEditable)
558 setUseSystemAppearance(parameters.useSystemAppearance);
561 // If the page is created off-screen, its visibilityState should be prerender.
562 m_page->setActivityState(m_activityState);
564 m_page->setIsPrerender();
566 updateIsInWindow(true);
568 setViewLayoutSize(parameters.viewLayoutSize);
569 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
570 setViewportSizeForCSSViewportUnits(parameters.viewportSizeForCSSViewportUnits);
572 setScrollPinningBehavior(parameters.scrollPinningBehavior);
573 if (parameters.scrollbarOverlayStyle)
574 m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
576 m_scrollbarOverlayStyle = Optional<ScrollbarOverlayStyle>();
578 setTopContentInset(parameters.topContentInset);
580 m_userAgent = parameters.userAgent;
582 if (!parameters.itemStates.isEmpty())
583 restoreSessionInternal(parameters.itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
585 m_drawingArea->setPaintingEnabled(true);
587 setMediaVolume(parameters.mediaVolume);
589 setMuted(parameters.muted);
591 // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
592 m_page->addLayoutMilestones({ DidFirstLayout, DidFirstVisuallyNonEmptyLayout });
594 auto& webProcess = WebProcess::singleton();
595 webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
597 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
598 webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
599 webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
600 webProcess.addMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID, *this);
601 #if ENABLE(FULLSCREEN_API)
602 webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
606 webPageCounter.increment();
609 #if ENABLE(ASYNC_SCROLLING)
610 if (m_useAsyncScrolling)
611 webProcess.eventDispatcher().addScrollingTreeForPage(this);
614 for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
615 m_mimeTypesWithCustomContentProviders.add(mimeType);
618 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
619 if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
620 m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
622 m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
624 if (parameters.viewScaleFactor != 1)
625 scaleView(parameters.viewScaleFactor);
627 m_page->addLayoutMilestones(parameters.observedLayoutMilestones);
630 m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
631 setSmartInsertDeleteEnabled(parameters.smartInsertDeleteEnabled);
632 WebCore::setAdditionalSupportedImageTypes(parameters.additionalSupportedImageTypes);
635 #if ENABLE(SERVICE_WORKER)
636 if (parameters.hasRegisteredServiceWorkers)
637 ServiceWorkerProvider::singleton().setMayHaveRegisteredServiceWorkers();
640 m_needsFontAttributes = parameters.needsFontAttributes;
643 if (!parameters.iceCandidateFilteringEnabled)
644 disableICECandidateFiltering();
646 if (parameters.enumeratingAllNetworkInterfacesEnabled)
647 enableEnumeratingAllNetworkInterfaces();
651 for (const auto& iterator : parameters.urlSchemeHandlers)
652 registerURLSchemeHandler(iterator.value, iterator.key);
654 m_userContentController->addUserContentWorlds(parameters.userContentWorlds);
655 m_userContentController->addUserScripts(WTFMove(parameters.userScripts), InjectUserScriptImmediately::No);
656 m_userContentController->addUserStyleSheets(parameters.userStyleSheets);
657 m_userContentController->addUserScriptMessageHandlers(parameters.messageHandlers);
658 #if ENABLE(CONTENT_EXTENSIONS)
659 m_userContentController->addContentRuleLists(WTFMove(parameters.contentRuleLists));
662 #if PLATFORM(IOS_FAMILY)
663 setViewportConfigurationViewLayoutSize(parameters.viewportConfigurationViewLayoutSize, parameters.viewportConfigurationLayoutSizeScaleFactor, 0);
664 setMaximumUnobscuredSize(parameters.maximumUnobscuredSize);
667 #if USE(AUDIO_SESSION)
668 PlatformMediaSessionManager::setShouldDeactivateAudioSession(true);
671 setBackgroundColor(parameters.backgroundColor);
675 void WebPage::disableICECandidateFiltering()
677 m_page->disableICECandidateFiltering();
680 void WebPage::enableICECandidateFiltering()
682 m_page->enableICECandidateFiltering();
686 void WebPage::disableEnumeratingAllNetworkInterfaces()
688 m_page->libWebRTCProvider().disableEnumeratingAllNetworkInterfaces();
691 void WebPage::enableEnumeratingAllNetworkInterfaces()
693 m_page->libWebRTCProvider().enableEnumeratingAllNetworkInterfaces();
698 void WebPage::stopAllMediaPlayback()
700 m_page->stopAllMediaPlayback();
703 void WebPage::suspendAllMediaPlayback()
705 m_page->suspendAllMediaPlayback();
708 void WebPage::resumeAllMediaPlayback()
710 m_page->resumeAllMediaPlayback();
713 void WebPage::suspendAllMediaBuffering()
715 m_page->suspendAllMediaBuffering();
718 void WebPage::resumeAllMediaBuffering()
720 m_page->resumeAllMediaBuffering();
724 void WebPage::reinitializeWebPage(WebPageCreationParameters&& parameters)
726 ASSERT(m_drawingArea);
728 setSize(parameters.viewSize);
730 // If the UIProcess created a new DrawingArea, then we need to do the same.
731 if (m_drawingArea->identifier() != parameters.drawingAreaIdentifier) {
732 auto oldDrawingArea = std::exchange(m_drawingArea, nullptr);
733 oldDrawingArea->removeMessageReceiverIfNeeded();
735 m_drawingArea = DrawingArea::create(*this, parameters);
736 m_drawingArea->setPaintingEnabled(false);
737 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
738 m_drawingArea->updatePreferences(parameters.store);
739 m_drawingArea->setPaintingEnabled(true);
741 m_drawingArea->adoptLayersFromDrawingArea(*oldDrawingArea);
743 unfreezeLayerTree(LayerTreeFreezeReason::PageSuspended);
746 setViewLayoutSize(parameters.viewLayoutSize);
748 if (m_activityState != parameters.activityState)
749 setActivityState(parameters.activityState, ActivityStateChangeAsynchronous, Vector<CallbackID>());
750 if (m_layerHostingMode != parameters.layerHostingMode)
751 setLayerHostingMode(parameters.layerHostingMode);
753 platformReinitialize();
756 void WebPage::updateThrottleState()
758 bool isActive = m_activityState.containsAny({ ActivityState::IsLoading, ActivityState::IsAudible, ActivityState::IsCapturingMedia, ActivityState::WindowIsActive });
759 bool isVisuallyIdle = m_activityState.contains(ActivityState::IsVisuallyIdle);
760 bool pageSuppressed = m_processSuppressionEnabled && !isActive && isVisuallyIdle;
762 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
763 if (!pageSuppressed) {
764 // App nap must be manually enabled when not running the NSApplication run loop.
765 static std::once_flag onceKey;
766 std::call_once(onceKey, [] {
767 __CFRunLoopSetOptionsReason(__CFRunLoopOptionsEnableAppNap, CFSTR("Finished checkin as application - enable app nap"));
771 // The UserActivity keeps the processes runnable. So if the page should be suppressed, stop the activity.
772 // If the page should not be supressed, start it.
774 m_userActivityHysteresis.stop();
776 m_userActivityHysteresis.start();
779 void WebPage::updateUserActivity()
781 if (m_userActivityHysteresis.state() == PAL::HysteresisState::Started)
782 m_userActivity.start();
784 m_userActivity.stop();
793 m_sandboxExtensionTracker.invalidate();
795 for (auto* pluginView : m_pluginViews)
796 pluginView->webPageDestroyed();
798 #if !PLATFORM(IOS_FAMILY)
800 m_headerBanner->detachFromPage();
802 m_footerBanner->detachFromPage();
803 #endif // !PLATFORM(IOS_FAMILY)
806 webPageCounter.decrement();
809 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
810 if (m_playbackSessionManager)
811 m_playbackSessionManager->invalidate();
813 if (m_videoFullscreenManager)
814 m_videoFullscreenManager->invalidate();
818 IPC::Connection* WebPage::messageSenderConnection() const
820 return WebProcess::singleton().parentProcessConnection();
823 uint64_t WebPage::messageSenderDestinationID() const
828 #if ENABLE(CONTEXT_MENUS)
829 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>&& contextMenuClient)
831 if (!contextMenuClient) {
832 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
836 m_contextMenuClient = WTFMove(contextMenuClient);
840 void WebPage::setInjectedBundleEditorClient(std::unique_ptr<API::InjectedBundle::EditorClient>&& editorClient)
843 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
847 m_editorClient = WTFMove(editorClient);
850 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>&& formClient)
853 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
857 m_formClient = WTFMove(formClient);
860 void WebPage::setInjectedBundlePageLoaderClient(std::unique_ptr<API::InjectedBundle::PageLoaderClient>&& loaderClient)
863 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
867 m_loaderClient = WTFMove(loaderClient);
869 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
870 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
871 // for backwards compatibility.
872 if (auto milestones = m_loaderClient->layoutMilestones())
873 listenForLayoutMilestones(milestones);
876 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
878 m_policyClient.initialize(client);
881 void WebPage::setInjectedBundleResourceLoadClient(std::unique_ptr<API::InjectedBundle::ResourceLoadClient>&& client)
883 if (!m_resourceLoadClient)
884 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
886 m_resourceLoadClient = WTFMove(client);
889 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>&& uiClient)
892 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
896 m_uiClient = WTFMove(uiClient);
899 #if ENABLE(FULLSCREEN_API)
900 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
902 m_fullScreenClient.initialize(client);
906 #if ENABLE(NETSCAPE_PLUGIN_API)
908 constexpr int smallPluginDimensionThreshold = 5;
910 static bool pluginIsSmall(WebCore::HTMLPlugInElement& pluginElement)
912 auto* renderer = pluginElement.renderer();
913 if (!is<RenderEmbeddedObject>(*renderer))
916 auto& box = downcast<RenderBox>(*renderer);
917 return box.contentWidth() <= smallPluginDimensionThreshold && box.contentHeight() <= smallPluginDimensionThreshold;
920 RefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
922 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
923 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
925 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
926 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
927 unsigned pluginArea = 0;
928 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
930 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
933 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
935 uint64_t pluginProcessToken;
936 uint32_t pluginLoadPolicy;
937 String unavailabilityDescription;
939 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)))
942 PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
943 bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
945 if (isUnsupported || isBlockedPlugin || !pluginProcessToken) {
946 #if ENABLE(PDFKIT_PLUGIN)
947 String path = parameters.url.path();
948 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWithIgnoringASCIICase(".pdf") || path.endsWithIgnoringASCIICase(".ps")))))
949 return PDFPlugin::create(*frame);
954 pluginElement->setReplacement(RenderEmbeddedObject::UnsupportedPlugin, unavailabilityDescription);
958 if (isBlockedPlugin) {
959 bool isReplacementObscured = pluginElement->setReplacement(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
960 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, isReplacementObscured));
964 if (!pluginProcessToken)
967 if (m_page->settings().blockingOfSmallPluginsEnabled() && pluginIsSmall(*pluginElement)) {
968 RELEASE_LOG(Plugins, "Blocking a plugin because it is too small");
969 pluginElement->setReplacement(RenderEmbeddedObject::PluginTooSmall, pluginTooSmallText());
973 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
974 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
976 #endif // ENABLE(NETSCAPE_PLUGIN_API)
978 #if ENABLE(WEBGL) && !PLATFORM(MAC)
979 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const URL&)
981 return WebGLAllowCreation;
984 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const URL&)
986 return WebGLAllowCreation;
990 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
992 Frame& frame = m_page->focusController().focusedOrMainFrame();
996 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
997 if (!pluginView->getSelectionString().isNull()) {
998 result.selectionIsNone = false;
999 result.selectionIsRange = true;
1000 result.isInPlugin = true;
1005 const VisibleSelection& selection = frame.selection().selection();
1006 const Editor& editor = frame.editor();
1008 result.selectionIsNone = selection.isNone();
1009 result.selectionIsRange = selection.isRange();
1010 result.isContentEditable = selection.isContentEditable();
1011 result.isContentRichlyEditable = selection.isContentRichlyEditable();
1012 result.isInPasswordField = selection.isInPasswordField();
1013 result.hasComposition = editor.hasComposition();
1014 result.shouldIgnoreSelectionChanges = editor.ignoreSelectionChanges();
1016 if (auto* document = frame.document())
1017 result.originIdentifierForPasteboard = document->originIdentifierForPasteboard();
1019 bool canIncludePostLayoutData = frame.view() && !frame.view()->needsLayout();
1020 if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && canIncludePostLayoutData) {
1021 auto& postLayoutData = result.postLayoutData();
1022 postLayoutData.canCut = editor.canCut();
1023 postLayoutData.canCopy = editor.canCopy();
1024 postLayoutData.canPaste = editor.canPaste();
1026 if (m_needsFontAttributes)
1027 postLayoutData.fontAttributes = editor.fontAttributesAtSelectionStart();
1030 if (result.isContentEditable && !selection.isNone()) {
1031 if (auto editingStyle = EditingStyle::styleAtSelectionStart(selection)) {
1032 if (editingStyle->hasStyle(CSSPropertyFontWeight, "bold"))
1033 postLayoutData.typingAttributes |= AttributeBold;
1035 if (editingStyle->hasStyle(CSSPropertyFontStyle, "italic") || editingStyle->hasStyle(CSSPropertyFontStyle, "oblique"))
1036 postLayoutData.typingAttributes |= AttributeItalics;
1038 if (editingStyle->hasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline"))
1039 postLayoutData.typingAttributes |= AttributeUnderline;
1041 if (auto* styleProperties = editingStyle->style()) {
1042 bool isLeftToRight = styleProperties->propertyAsValueID(CSSPropertyDirection) == CSSValueLtr;
1043 switch (styleProperties->propertyAsValueID(CSSPropertyTextAlign)) {
1045 case CSSValueWebkitRight:
1046 postLayoutData.textAlignment = RightAlignment;
1049 case CSSValueWebkitLeft:
1050 postLayoutData.textAlignment = LeftAlignment;
1052 case CSSValueCenter:
1053 case CSSValueWebkitCenter:
1054 postLayoutData.textAlignment = CenterAlignment;
1056 case CSSValueJustify:
1057 postLayoutData.textAlignment = JustifiedAlignment;
1060 postLayoutData.textAlignment = isLeftToRight ? LeftAlignment : RightAlignment;
1063 postLayoutData.textAlignment = isLeftToRight ? RightAlignment : LeftAlignment;
1068 if (auto textColor = styleProperties->propertyAsColor(CSSPropertyColor))
1069 postLayoutData.textColor = *textColor;
1073 if (auto* enclosingListElement = enclosingList(selection.start().containerNode())) {
1074 if (is<HTMLUListElement>(*enclosingListElement))
1075 postLayoutData.enclosingListType = UnorderedList;
1076 else if (is<HTMLOListElement>(*enclosingListElement))
1077 postLayoutData.enclosingListType = OrderedList;
1079 ASSERT_NOT_REACHED();
1082 postLayoutData.baseWritingDirection = editor.baseWritingDirectionForSelectionStart();
1087 platformEditorState(frame, result, shouldIncludePostLayoutData);
1089 m_lastEditorStateWasContentEditable = result.isContentEditable ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1094 void WebPage::changeFontAttributes(WebCore::FontAttributeChanges&& changes)
1096 auto& frame = m_page->focusController().focusedOrMainFrame();
1097 if (frame.selection().selection().isContentEditable())
1098 frame.editor().applyStyleToSelection(changes.createEditingStyle(), changes.editAction(), Editor::ColorFilterMode::InvertColor);
1101 void WebPage::changeFont(WebCore::FontChanges&& changes)
1103 auto& frame = m_page->focusController().focusedOrMainFrame();
1104 if (frame.selection().selection().isContentEditable())
1105 frame.editor().applyStyleToSelection(changes.createEditingStyle(), EditAction::SetFont, Editor::ColorFilterMode::InvertColor);
1108 void WebPage::executeEditCommandWithCallback(const String& commandName, const String& argument, CallbackID callbackID)
1110 executeEditCommand(commandName, argument);
1111 send(Messages::WebPageProxy::VoidCallback(callbackID));
1114 void WebPage::updateEditorStateAfterLayoutIfEditabilityChanged()
1116 // FIXME: We should update EditorStateIsContentEditable to track whether the state is richly
1117 // editable or plainttext-only.
1118 if (m_lastEditorStateWasContentEditable == EditorStateIsContentEditable::Unset)
1121 Frame& frame = m_page->focusController().focusedOrMainFrame();
1122 EditorStateIsContentEditable editorStateIsContentEditable = frame.selection().selection().isContentEditable() ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1123 if (m_lastEditorStateWasContentEditable != editorStateIsContentEditable)
1124 sendPartialEditorStateAndSchedulePostLayoutUpdate();
1127 String WebPage::renderTreeExternalRepresentation() const
1129 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
1132 String WebPage::renderTreeExternalRepresentationForPrinting() const
1134 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
1137 uint64_t WebPage::renderTreeSize() const
1141 return m_page->renderTreeSize();
1144 void WebPage::setTracksRepaints(bool trackRepaints)
1146 if (FrameView* view = mainFrameView())
1147 view->setTracksRepaints(trackRepaints);
1150 bool WebPage::isTrackingRepaints() const
1152 if (FrameView* view = mainFrameView())
1153 return view->isTrackingRepaints();
1158 void WebPage::resetTrackedRepaints()
1160 if (FrameView* view = mainFrameView())
1161 view->resetTrackedRepaints();
1164 Ref<API::Array> WebPage::trackedRepaintRects()
1166 FrameView* view = mainFrameView();
1168 return API::Array::create();
1170 Vector<RefPtr<API::Object>> repaintRects;
1171 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
1173 for (const auto& repaintRect : view->trackedRepaintRects())
1174 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
1176 return API::Array::create(WTFMove(repaintRects));
1179 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
1181 if (!is<PluginDocument>(frame.document()))
1184 auto& pluginDocument = downcast<PluginDocument>(*frame.document());
1185 if (pluginDocument.focusedElement() != pluginDocument.pluginElement())
1188 return pluginViewForFrame(&frame);
1191 PluginView* WebPage::pluginViewForFrame(Frame* frame)
1193 if (!frame || !is<PluginDocument>(frame->document()))
1196 auto& document = downcast<PluginDocument>(*frame->document());
1197 return static_cast<PluginView*>(document.pluginWidget());
1200 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
1202 Frame& frame = m_page->focusController().focusedOrMainFrame();
1204 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
1205 pluginView->handleEditingCommand(commandName, argument);
1209 frame.editor().command(commandName).execute(argument);
1212 void WebPage::setEditable(bool editable)
1214 m_page->setEditable(editable);
1215 m_page->setTabKeyCyclesThroughElements(!editable);
1216 Frame& frame = m_page->focusController().focusedOrMainFrame();
1218 frame.editor().applyEditingStyleToBodyElement();
1219 // If the page is made editable and the selection is empty, set it to something.
1220 if (frame.selection().isNone())
1221 frame.selection().setSelectionFromNone();
1225 void WebPage::increaseListLevel()
1227 m_page->focusController().focusedOrMainFrame().editor().increaseSelectionListLevel();
1230 void WebPage::decreaseListLevel()
1232 m_page->focusController().focusedOrMainFrame().editor().decreaseSelectionListLevel();
1235 void WebPage::changeListType()
1237 m_page->focusController().focusedOrMainFrame().editor().changeSelectionListType();
1240 void WebPage::setBaseWritingDirection(WritingDirection direction)
1242 m_page->focusController().focusedOrMainFrame().editor().setBaseWritingDirection(direction);
1245 bool WebPage::isEditingCommandEnabled(const String& commandName)
1247 Frame& frame = m_page->focusController().focusedOrMainFrame();
1249 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1250 return pluginView->isEditingCommandEnabled(commandName);
1252 Editor::Command command = frame.editor().command(commandName);
1253 return command.isSupported() && command.isEnabled();
1256 void WebPage::clearMainFrameName()
1258 if (Frame* frame = mainFrame())
1259 frame->tree().clearName();
1262 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
1264 m_drawingArea->setRootCompositingLayer(layer);
1267 void WebPage::exitAcceleratedCompositingMode()
1269 m_drawingArea->setRootCompositingLayer(nullptr);
1272 void WebPage::close()
1277 #if ENABLE(RESOURCE_LOAD_STATISTICS)
1278 WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::ClearPageSpecificDataForResourceLoadStatistics(sessionID(), m_pageID), 0);
1283 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1284 if (!mainWebFrame()->url().isEmpty())
1285 reportUsedFeatures();
1287 if (WebProcess::singleton().injectedBundle())
1288 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1291 m_inspector->disconnectFromPage();
1292 m_inspector = nullptr;
1295 m_page->inspectorController().disconnectAllFrontends();
1297 #if ENABLE(FULLSCREEN_API)
1298 m_fullScreenManager = nullptr;
1301 if (m_activePopupMenu) {
1302 m_activePopupMenu->disconnectFromPage();
1303 m_activePopupMenu = nullptr;
1306 if (m_activeOpenPanelResultListener) {
1307 m_activeOpenPanelResultListener->disconnectFromPage();
1308 m_activeOpenPanelResultListener = nullptr;
1311 #if ENABLE(INPUT_TYPE_COLOR)
1312 if (m_activeColorChooser) {
1313 m_activeColorChooser->disconnectFromPage();
1314 m_activeColorChooser = nullptr;
1319 if (m_printOperation) {
1320 m_printOperation->disconnectFromPage();
1321 m_printOperation = nullptr;
1325 #if ENABLE(VIDEO) && USE(GSTREAMER)
1326 if (m_installMediaPluginsCallback) {
1327 m_installMediaPluginsCallback->invalidate();
1328 m_installMediaPluginsCallback = nullptr;
1332 m_sandboxExtensionTracker.invalidate();
1334 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1335 m_determinePrimarySnapshottedPlugInTimer.stop();
1338 #if ENABLE(CONTEXT_MENUS)
1339 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1341 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
1342 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1343 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
1344 m_policyClient.initialize(0);
1345 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
1346 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1347 #if ENABLE(FULLSCREEN_API)
1348 m_fullScreenClient.initialize(0);
1351 m_printContext = nullptr;
1352 m_mainFrame->coreFrame()->loader().detachFromParent();
1353 m_drawingArea = nullptr;
1355 DeferredPageDestructor::createDeferredPageDestructor(WTFMove(m_page), this);
1357 bool isRunningModal = m_isRunningModal;
1358 m_isRunningModal = false;
1360 auto& webProcess = WebProcess::singleton();
1361 #if ENABLE(ASYNC_SCROLLING)
1362 if (m_useAsyncScrolling)
1363 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
1365 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
1366 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
1367 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
1368 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
1369 webProcess.removeMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID);
1370 #if ENABLE(FULLSCREEN_API)
1371 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
1373 #if PLATFORM(COCOA) || PLATFORM(GTK)
1374 m_viewGestureGeometryCollector = nullptr;
1377 // The WebPage can be destroyed by this call.
1378 WebProcess::singleton().removeWebPage(m_pageID);
1380 WebProcess::singleton().updateActivePages();
1383 RunLoop::main().stop();
1386 void WebPage::tryClose()
1388 SendStopResponsivenessTimer stopper;
1390 if (!corePage()->userInputBridge().tryClosePage())
1393 send(Messages::WebPageProxy::ClosePage(true));
1396 void WebPage::sendClose()
1398 send(Messages::WebPageProxy::ClosePage(false));
1401 void WebPage::suspendForProcessSwap()
1403 auto failedToSuspend = [this, protectedThis = makeRef(*this)] {
1404 send(Messages::WebPageProxy::DidFailToSuspendAfterProcessSwap());
1407 auto* currentHistoryItem = m_mainFrame->coreFrame()->loader().history().currentItem();
1408 if (!currentHistoryItem) {
1413 if (!PageCache::singleton().addIfCacheable(*currentHistoryItem, corePage())) {
1418 send(Messages::WebPageProxy::DidSuspendAfterProcessSwap());
1421 void WebPage::loadURLInFrame(URL&& url, uint64_t frameID)
1423 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1427 frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(url), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1430 void WebPage::loadDataInFrame(IPC::DataReference&& data, String&& MIMEType, String&& encodingName, URL&& baseURL, uint64_t frameID)
1432 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1436 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
1437 ResourceResponse response(baseURL, MIMEType, sharedBuffer->size(), encodingName);
1438 SubstituteData substituteData(WTFMove(sharedBuffer), baseURL, WTFMove(response), SubstituteData::SessionHistoryVisibility::Hidden);
1439 frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(baseURL), ShouldOpenExternalURLsPolicy::ShouldNotAllow, WTFMove(substituteData)));
1442 #if !PLATFORM(COCOA)
1443 void WebPage::platformDidReceiveLoadParameters(const LoadParameters& loadParameters)
1448 void WebPage::loadRequest(LoadParameters&& loadParameters)
1450 SendStopResponsivenessTimer stopper;
1452 m_pendingNavigationID = loadParameters.navigationID;
1453 m_pendingWebsitePolicies = WTFMove(loadParameters.websitePolicies);
1455 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), WTFMove(loadParameters.sandboxExtensionHandle));
1457 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1458 // to all the client to set up any needed state.
1459 m_loaderClient->willLoadURLRequest(*this, loadParameters.request, WebProcess::singleton().transformHandlesToObjects(loadParameters.userData.object()).get());
1461 platformDidReceiveLoadParameters(loadParameters);
1463 // Initate the load in WebCore.
1464 FrameLoadRequest frameLoadRequest { *m_mainFrame->coreFrame(), loadParameters.request, ShouldOpenExternalURLsPolicy::ShouldNotAllow };
1465 ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(loadParameters.shouldOpenExternalURLsPolicy);
1466 frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1467 frameLoadRequest.setShouldTreatAsContinuingLoad(loadParameters.shouldTreatAsContinuingLoad);
1468 frameLoadRequest.setLockHistory(loadParameters.lockHistory);
1469 frameLoadRequest.setlockBackForwardList(loadParameters.lockBackForwardList);
1470 frameLoadRequest.setClientRedirectSourceForHistory(loadParameters.clientRedirectSourceForHistory);
1471 frameLoadRequest.setIsRequestFromClientOrUserInput();
1473 corePage()->userInputBridge().loadRequest(WTFMove(frameLoadRequest));
1475 ASSERT(!m_pendingNavigationID);
1476 ASSERT(!m_pendingWebsitePolicies);
1479 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)
1481 SendStopResponsivenessTimer stopper;
1483 m_pendingNavigationID = navigationID;
1484 m_pendingWebsitePolicies = WTFMove(websitePolicies);
1486 ResourceRequest request(baseURL);
1487 ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1488 SubstituteData substituteData(WTFMove(sharedBuffer), unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1490 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1491 // to all the client to set up any needed state.
1492 m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1494 // Initate the load in WebCore.
1495 FrameLoadRequest frameLoadRequest(*m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData);
1496 frameLoadRequest.setShouldTreatAsContinuingLoad(shouldTreatAsContinuingLoad);
1497 m_mainFrame->coreFrame()->loader().load(WTFMove(frameLoadRequest));
1500 void WebPage::loadData(LoadParameters&& loadParameters)
1502 platformDidReceiveLoadParameters(loadParameters);
1504 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1505 URL baseURL = loadParameters.baseURLString.isEmpty() ? WTF::blankURL() : URL(URL(), loadParameters.baseURLString);
1506 loadDataImpl(loadParameters.navigationID, loadParameters.shouldTreatAsContinuingLoad, WTFMove(loadParameters.websitePolicies), WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, URL(), loadParameters.userData);
1509 void WebPage::loadAlternateHTML(LoadParameters&& loadParameters)
1511 platformDidReceiveLoadParameters(loadParameters);
1513 URL baseURL = loadParameters.baseURLString.isEmpty() ? WTF::blankURL() : URL(URL(), loadParameters.baseURLString);
1514 URL unreachableURL = loadParameters.unreachableURLString.isEmpty() ? URL() : URL(URL(), loadParameters.unreachableURLString);
1515 URL provisionalLoadErrorURL = loadParameters.provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), loadParameters.provisionalLoadErrorURLString);
1516 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1517 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1518 loadDataImpl(loadParameters.navigationID, loadParameters.shouldTreatAsContinuingLoad, WTFMove(loadParameters.websitePolicies), WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, unreachableURL, loadParameters.userData);
1519 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1522 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1524 Frame* mainFrame = m_mainFrame->coreFrame();
1525 Document* mainFrameDocument = mainFrame->document();
1526 if (!mainFrameDocument)
1529 const int singleClick = 1;
1530 // FIXME: Set modifier keys.
1531 // FIXME: This should probably set IsSimulated::Yes.
1532 auto mouseEvent = MouseEvent::create(eventNames().clickEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes, Event::IsComposed::Yes,
1533 MonotonicTime::now(), nullptr, singleClick, screenPoint, documentPoint, { }, { }, 0, 0, nullptr, 0, WebCore::NoTap, nullptr);
1535 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.ptr(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1538 void WebPage::stopLoadingFrame(uint64_t frameID)
1540 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1544 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1547 void WebPage::stopLoading()
1549 SendStopResponsivenessTimer stopper;
1551 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1554 bool WebPage::defersLoading() const
1556 return m_page->defersLoading();
1559 void WebPage::setDefersLoading(bool defersLoading)
1561 m_page->setDefersLoading(defersLoading);
1564 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, SandboxExtension::Handle&& sandboxExtensionHandle)
1566 SendStopResponsivenessTimer stopper;
1568 ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1569 m_pendingNavigationID = navigationID;
1571 m_sandboxExtensionTracker.beginReload(m_mainFrame.get(), WTFMove(sandboxExtensionHandle));
1572 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1574 if (m_pendingNavigationID) {
1575 // This can happen if FrameLoader::reload() returns early because the document URL is empty.
1576 // The reload does nothing so we need to reset the pending navigation. See webkit.org/b/153210.
1577 m_pendingNavigationID = 0;
1581 void WebPage::goToBackForwardItem(uint64_t navigationID, const BackForwardItemIdentifier& backForwardItemID, FrameLoadType backForwardType, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad, Optional<WebsitePoliciesData>&& websitePolicies)
1583 SendStopResponsivenessTimer stopper;
1585 ASSERT(isBackForwardLoadType(backForwardType));
1587 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1592 LOG(Loading, "In WebProcess pid %i, WebPage %" PRIu64 " is navigating to back/forward URL %s", getCurrentProcessID(), m_pageID, item->url().string().utf8().data());
1594 ASSERT(!m_pendingNavigationID);
1595 m_pendingNavigationID = navigationID;
1596 m_pendingWebsitePolicies = WTFMove(websitePolicies);
1598 m_page->goToItem(*item, backForwardType, shouldTreatAsContinuingLoad);
1601 void WebPage::tryRestoreScrollPosition()
1603 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1606 void WebPage::layoutIfNeeded()
1608 if (m_mainFrame->coreFrame()->view())
1609 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1612 WebPage* WebPage::fromCorePage(Page* page)
1614 return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1617 void WebPage::setSize(const WebCore::IntSize& viewSize)
1619 if (m_viewSize == viewSize)
1622 m_viewSize = viewSize;
1623 FrameView* view = m_page->mainFrame().view();
1624 view->resize(viewSize);
1625 m_drawingArea->setNeedsDisplay();
1627 #if USE(COORDINATED_GRAPHICS)
1628 if (view->useFixedLayout())
1629 sendViewportAttributesChanged(m_page->viewportArguments());
1633 #if USE(COORDINATED_GRAPHICS)
1634 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1636 FrameView* view = m_page->mainFrame().view();
1637 ASSERT(view && view->useFixedLayout());
1639 // Viewport properties have no impact on zero sized fixed viewports.
1640 if (m_viewSize.isEmpty())
1643 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1644 Settings& settings = m_page->settings();
1646 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1648 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1649 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1650 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1652 ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1654 // If no layout was done yet set contentFixedOrigin to (0,0).
1655 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1657 // Put the width and height to the viewport width and height. In css units however.
1658 // Use FloatSize to avoid truncated values during scale.
1659 FloatSize contentFixedSize = m_viewSize;
1661 #if ENABLE(CSS_DEVICE_ADAPTATION)
1662 // CSS viewport descriptors might be applied to already affected viewport size
1663 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1664 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1667 contentFixedSize.scale(1 / attr.initialScale);
1668 view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1670 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1672 // This also takes care of the relayout.
1673 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1675 #if USE(COORDINATED_GRAPHICS)
1676 m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1678 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1683 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1685 FrameView* frameView = m_page->mainFrame().view();
1687 ScrollPosition scrollPosition = frameView->scrollPosition();
1688 ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1690 // If the current scroll position in a direction is the max scroll position
1691 // we don't want to scroll at all.
1692 IntSize newScrollOffset;
1693 if (scrollPosition.x() < maximumScrollPosition.x())
1694 newScrollOffset.setWidth(scrollOffset.width());
1695 if (scrollPosition.y() < maximumScrollPosition.y())
1696 newScrollOffset.setHeight(scrollOffset.height());
1698 if (newScrollOffset.isZero())
1701 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1704 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1707 FrameView* mainFrameView = m_page->mainFrame().view();
1708 LocalDefaultSystemAppearance localAppearance(mainFrameView ? mainFrameView->useDarkAppearance() : false);
1711 GraphicsContextStateSaver stateSaver(graphicsContext);
1712 graphicsContext.clip(rect);
1714 m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1717 double WebPage::textZoomFactor() const
1719 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1720 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1721 if (pluginView->handlesPageScaleFactor())
1722 return pluginView->pageScaleFactor();
1723 return pageScaleFactor();
1726 Frame* frame = m_mainFrame->coreFrame();
1729 return frame->textZoomFactor();
1732 void WebPage::setTextZoomFactor(double zoomFactor)
1734 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1735 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1736 if (pluginView->handlesPageScaleFactor())
1737 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1739 scalePage(zoomFactor, IntPoint());
1743 Frame* frame = m_mainFrame->coreFrame();
1746 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1749 double WebPage::pageZoomFactor() const
1751 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1752 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1753 if (pluginView->handlesPageScaleFactor())
1754 return pluginView->pageScaleFactor();
1755 return pageScaleFactor();
1758 Frame* frame = m_mainFrame->coreFrame();
1761 return frame->pageZoomFactor();
1764 void WebPage::setPageZoomFactor(double zoomFactor)
1766 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1767 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1768 if (pluginView->handlesPageScaleFactor())
1769 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1771 scalePage(zoomFactor, IntPoint());
1775 Frame* frame = m_mainFrame->coreFrame();
1778 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1781 static void dumpHistoryItem(HistoryItem& item, size_t indent, bool isCurrentItem, StringBuilder& stringBuilder, const String& directoryName)
1784 stringBuilder.appendLiteral("curr-> ");
1786 for (size_t i = 0; i < indent; ++i)
1787 stringBuilder.append(' ');
1790 auto url = item.url();
1791 if (url.protocolIs("file")) {
1792 size_t start = url.string().find(directoryName);
1793 if (start == WTF::notFound)
1796 start += directoryName.length();
1797 stringBuilder.appendLiteral("(file test):");
1798 stringBuilder.append(url.string().substring(start));
1800 stringBuilder.append(url);
1802 auto& target = item.target();
1803 if (target.length()) {
1804 stringBuilder.appendLiteral(" (in frame \"");
1805 stringBuilder.append(target);
1806 stringBuilder.appendLiteral("\")");
1809 if (item.isTargetItem())
1810 stringBuilder.appendLiteral(" **nav target**");
1812 stringBuilder.append('\n');
1814 Vector<Ref<HistoryItem>> children;
1815 children.reserveInitialCapacity(item.children().size());
1816 for (auto& child : item.children())
1817 children.uncheckedAppend(child.copyRef());
1818 std::stable_sort(children.begin(), children.end(), [] (auto& a, auto& b) {
1819 return codePointCompare(a->target(), b->target()) < 0;
1821 for (auto& child : children)
1822 dumpHistoryItem(child, indent + 4, false, stringBuilder, directoryName);
1825 String WebPage::dumpHistoryForTesting(const String& directory)
1830 auto& list = m_page->backForward();
1832 StringBuilder builder;
1833 int begin = -list.backCount();
1834 if (list.itemAtIndex(begin)->url() == WTF::blankURL())
1836 for (int i = begin; i <= static_cast<int>(list.forwardCount()); ++i)
1837 dumpHistoryItem(*list.itemAtIndex(i), 8, !i, builder, directory);
1838 return builder.toString();
1841 void WebPage::clearHistory()
1846 static_cast<WebBackForwardListProxy&>(m_page->backForward().client()).clear();
1849 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1851 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1852 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1853 if (pluginView->handlesPageScaleFactor())
1854 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1856 scalePage(pageZoomFactor, IntPoint());
1860 Frame* frame = m_mainFrame->coreFrame();
1863 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1866 void WebPage::windowScreenDidChange(uint32_t displayID)
1868 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1871 void WebPage::scalePage(double scale, const IntPoint& origin)
1873 double totalScale = scale * viewScaleFactor();
1874 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1876 #if PLATFORM(IOS_FAMILY)
1877 if (willChangeScaleFactor) {
1878 if (!m_inDynamicSizeUpdate)
1879 m_dynamicSizeUpdateHistory.clear();
1880 m_scaleWasSetByUIProcess = false;
1883 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1884 if (pluginView && pluginView->handlesPageScaleFactor()) {
1885 // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1886 // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1887 if (m_page->pageScaleFactor() != 1) {
1888 m_page->setPageScaleFactor(1, origin);
1889 for (auto* pluginView : m_pluginViews)
1890 pluginView->pageScaleFactorDidChange();
1893 pluginView->setPageScaleFactor(totalScale, origin);
1897 m_page->setPageScaleFactor(totalScale, origin);
1899 // We can't early return before setPageScaleFactor because the origin might be different.
1900 if (!willChangeScaleFactor)
1903 for (auto* pluginView : m_pluginViews)
1904 pluginView->pageScaleFactorDidChange();
1906 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1907 m_drawingArea->deviceOrPageScaleFactorChanged();
1910 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1913 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1915 double totalScale = scale * viewScaleFactor();
1916 if (totalScale == totalScaleFactor())
1919 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1920 double scaleRatio = scale / pageScaleFactor();
1921 scrollPositionAtNewScale.scale(scaleRatio);
1922 scalePage(scale, scrollPositionAtNewScale);
1925 double WebPage::totalScaleFactor() const
1927 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1928 if (pluginView && pluginView->handlesPageScaleFactor())
1929 return pluginView->pageScaleFactor();
1931 return m_page->pageScaleFactor();
1934 double WebPage::pageScaleFactor() const
1936 return totalScaleFactor() / viewScaleFactor();
1939 double WebPage::viewScaleFactor() const
1941 return m_page->viewScaleFactor();
1944 void WebPage::scaleView(double scale)
1946 if (viewScaleFactor() == scale)
1949 float pageScale = pageScaleFactor();
1951 IntPoint scrollPositionAtNewScale;
1952 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1953 double scaleRatio = scale / viewScaleFactor();
1954 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1955 scrollPositionAtNewScale.scale(scaleRatio);
1958 m_page->setViewScaleFactor(scale);
1959 scalePage(pageScale, scrollPositionAtNewScale);
1962 void WebPage::setDeviceScaleFactor(float scaleFactor)
1964 if (scaleFactor == m_page->deviceScaleFactor())
1967 m_page->setDeviceScaleFactor(scaleFactor);
1969 // Tell all our plug-in views that the device scale factor changed.
1971 for (auto* pluginView : m_pluginViews)
1972 pluginView->setDeviceScaleFactor(scaleFactor);
1974 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1977 if (findController().isShowingOverlay()) {
1978 // We must have updated layout to get the selection rects right.
1980 findController().deviceScaleFactorDidChange();
1983 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1984 m_drawingArea->deviceOrPageScaleFactorChanged();
1988 float WebPage::deviceScaleFactor() const
1990 return m_page->deviceScaleFactor();
1993 void WebPage::accessibilitySettingsDidChange()
1995 m_page->accessibilitySettingsDidChange();
1998 #if ENABLE(ACCESSIBILITY_EVENTS)
1999 void WebPage::updateAccessibilityEventsEnabled(bool enabled)
2001 m_page->settings().setAccessibilityEventsEnabled(enabled);
2005 void WebPage::setUseFixedLayout(bool fixed)
2007 // Do not overwrite current settings if initially setting it to false.
2008 if (m_useFixedLayout == fixed)
2010 m_useFixedLayout = fixed;
2012 #if !PLATFORM(IOS_FAMILY)
2013 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
2016 FrameView* view = mainFrameView();
2020 view->setUseFixedLayout(fixed);
2022 setFixedLayoutSize(IntSize());
2024 send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
2027 bool WebPage::setFixedLayoutSize(const IntSize& size)
2029 FrameView* view = mainFrameView();
2030 if (!view || view->fixedLayoutSize() == size)
2033 LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " setFixedLayoutSize " << size);
2034 view->setFixedLayoutSize(size);
2036 send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
2040 IntSize WebPage::fixedLayoutSize() const
2042 FrameView* view = mainFrameView();
2045 return view->fixedLayoutSize();
2048 void WebPage::disabledAdaptationsDidChange(const OptionSet<DisabledAdaptations>& disabledAdaptations)
2050 #if PLATFORM(IOS_FAMILY)
2051 if (m_viewportConfiguration.setDisabledAdaptations(disabledAdaptations))
2052 viewportConfigurationChanged();
2054 UNUSED_PARAM(disabledAdaptations);
2058 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
2060 #if PLATFORM(IOS_FAMILY)
2061 if (m_viewportConfiguration.setViewportArguments(viewportArguments))
2062 viewportConfigurationChanged();
2065 #if USE(COORDINATED_GRAPHICS)
2066 FrameView* view = m_page->mainFrame().view();
2067 if (view && view->useFixedLayout())
2068 sendViewportAttributesChanged(viewportArguments);
2070 m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
2073 #if !PLATFORM(IOS_FAMILY) && !USE(COORDINATED_GRAPHICS)
2074 UNUSED_PARAM(viewportArguments);
2078 void WebPage::listenForLayoutMilestones(OptionSet<WebCore::LayoutMilestone> milestones)
2082 m_page->addLayoutMilestones(milestones);
2085 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
2087 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
2090 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
2092 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
2095 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
2097 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
2100 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
2102 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
2103 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
2106 void WebPage::setPaginationMode(uint32_t mode)
2108 Pagination pagination = m_page->pagination();
2109 pagination.mode = static_cast<Pagination::Mode>(mode);
2110 m_page->setPagination(pagination);
2113 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
2115 Pagination pagination = m_page->pagination();
2116 pagination.behavesLikeColumns = behavesLikeColumns;
2117 m_page->setPagination(pagination);
2120 void WebPage::setPageLength(double pageLength)
2122 Pagination pagination = m_page->pagination();
2123 pagination.pageLength = pageLength;
2124 m_page->setPagination(pagination);
2127 void WebPage::setGapBetweenPages(double gap)
2129 Pagination pagination = m_page->pagination();
2130 pagination.gap = gap;
2131 m_page->setPagination(pagination);
2134 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
2136 m_page->setPaginationLineGridEnabled(lineGridEnabled);
2139 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
2141 auto& webProcess = WebProcess::singleton();
2142 InjectedBundle* injectedBundle = webProcess.injectedBundle();
2143 if (!injectedBundle)
2146 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
2149 #if !PLATFORM(IOS_FAMILY)
2151 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
2154 m_headerBanner->detachFromPage();
2156 m_headerBanner = pageBanner;
2159 m_headerBanner->addToPage(PageBanner::Header, this);
2162 PageBanner* WebPage::headerPageBanner()
2164 return m_headerBanner.get();
2167 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
2170 m_footerBanner->detachFromPage();
2172 m_footerBanner = pageBanner;
2175 m_footerBanner->addToPage(PageBanner::Footer, this);
2178 PageBanner* WebPage::footerPageBanner()
2180 return m_footerBanner.get();
2183 void WebPage::hidePageBanners()
2186 m_headerBanner->hide();
2188 m_footerBanner->hide();
2191 void WebPage::showPageBanners()
2194 m_headerBanner->showIfHidden();
2196 m_footerBanner->showIfHidden();
2199 void WebPage::setHeaderBannerHeightForTesting(int height)
2201 corePage()->setHeaderHeight(height);
2204 void WebPage::setFooterBannerHeightForTesting(int height)
2206 corePage()->setFooterHeight(height);
2209 #endif // !PLATFORM(IOS_FAMILY)
2211 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
2213 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
2214 snapshotOptions |= SnapshotOptionsShareable;
2216 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
2218 ShareableBitmap::Handle handle;
2220 image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
2222 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
2225 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
2227 IntRect snapshotRect = rect;
2228 IntSize bitmapSize = snapshotRect.size();
2229 if (options & SnapshotOptionsPrinting) {
2230 ASSERT(additionalScaleFactor == 1);
2231 Frame* coreFrame = m_mainFrame->coreFrame();
2234 bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
2236 double scaleFactor = additionalScaleFactor;
2237 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
2238 scaleFactor *= corePage()->deviceScaleFactor();
2239 bitmapSize.scale(scaleFactor);
2242 return snapshotAtSize(rect, bitmapSize, options);
2245 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
2247 IntRect snapshotRect = rect;
2248 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
2249 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
2250 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
2252 if (options & SnapshotOptionsPrinting) {
2253 PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
2257 Color documentBackgroundColor = frameView.documentBackgroundColor();
2258 Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
2259 graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
2261 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2262 double deviceScaleFactor = frame.page()->deviceScaleFactor();
2263 graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
2264 scaleFactor /= deviceScaleFactor;
2267 graphicsContext.scale(scaleFactor);
2268 graphicsContext.translate(-snapshotRect.location());
2270 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
2271 if (options & SnapshotOptionsExcludeSelectionHighlighting)
2272 shouldPaintSelection = FrameView::ExcludeSelection;
2274 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
2275 if (options & SnapshotOptionsInViewCoordinates)
2276 coordinateSpace = FrameView::ViewCoordinates;
2278 frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
2280 if (options & SnapshotOptionsPaintSelectionRectangle) {
2281 FloatRect selectionRectangle = frame.selection().selectionBounds();
2282 graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
2283 graphicsContext.strokeRect(selectionRectangle, 1);
2287 static ShareableBitmap::Configuration snapshotOptionsToBitmapConfiguration(SnapshotOptions options, WebPage& page)
2289 ShareableBitmap::Configuration configuration;
2291 if (options & SnapshotOptionsUseScreenColorSpace)
2292 configuration.colorSpace.cgColorSpace = screenColorSpace(page.corePage()->mainFrame().view());
2294 return configuration;
2297 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2299 Frame* coreFrame = m_mainFrame->coreFrame();
2303 FrameView* frameView = coreFrame->view();
2307 auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2310 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2312 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2318 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2320 Frame* coreFrame = m_mainFrame->coreFrame();
2324 FrameView* frameView = coreFrame->view();
2328 auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2331 auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2332 auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2333 auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2335 CGPDFContextBeginPage(pdfContext.get(), nullptr);
2337 GraphicsContext graphicsContext { pdfContext.get() };
2338 graphicsContext.scale({ 1, -1 });
2339 graphicsContext.translate(0, -bitmapSize.height());
2340 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2342 CGPDFContextEndPage(pdfContext.get());
2343 CGPDFContextClose(pdfContext.get());
2350 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2352 Frame* coreFrame = m_mainFrame->coreFrame();
2356 FrameView* frameView = coreFrame->view();
2360 if (!node.renderer())
2363 LayoutRect topLevelRect;
2364 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2365 if (snapshotRect.isEmpty())
2368 double scaleFactor = 1;
2369 IntSize snapshotSize = snapshotRect.size();
2370 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2371 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2372 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2373 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2376 auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2379 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2381 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2382 double deviceScaleFactor = corePage()->deviceScaleFactor();
2383 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2384 scaleFactor /= deviceScaleFactor;
2387 graphicsContext->scale(scaleFactor);
2388 graphicsContext->translate(-snapshotRect.location());
2390 Color savedBackgroundColor = frameView->baseBackgroundColor();
2391 frameView->setBaseBackgroundColor(Color::transparent);
2392 frameView->setNodeToDraw(&node);
2394 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2396 frameView->setBaseBackgroundColor(savedBackgroundColor);
2397 frameView->setNodeToDraw(nullptr);
2402 void WebPage::pageDidScroll()
2404 #if PLATFORM(IOS_FAMILY)
2405 if (!m_inDynamicSizeUpdate)
2406 m_dynamicSizeUpdateHistory.clear();
2408 m_uiClient->pageDidScroll(this);
2410 m_pageScrolledHysteresis.impulse();
2412 send(Messages::WebPageProxy::PageDidScroll());
2415 void WebPage::pageStoppedScrolling()
2417 // Maintain the current history item's scroll position up-to-date.
2418 if (Frame* frame = m_mainFrame->coreFrame())
2419 frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2422 #if ENABLE(CONTEXT_MENUS)
2423 WebContextMenu* WebPage::contextMenu()
2426 m_contextMenu = WebContextMenu::create(this);
2427 return m_contextMenu.get();
2430 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2432 corePage()->contextMenuController().clearContextMenu();
2434 // Simulate a mouse click to generate the correct menu.
2435 PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2436 corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2437 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2438 auto* menu = handled ? contextMenu() : nullptr;
2439 PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2440 corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2448 static const WebEvent* g_currentEvent = 0;
2450 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2451 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2452 // platform events passed to the event handler code.
2453 const WebEvent* WebPage::currentEvent()
2455 return g_currentEvent;
2458 void WebPage::freezeLayerTree(LayerTreeFreezeReason reason)
2460 RELEASE_LOG(ProcessSuspension, "%p - WebPage (PageID=%llu) - Adding a reason %d to freeze layer tree; current reasons are %d",
2461 this, m_pageID, static_cast<unsigned>(reason), m_LayerTreeFreezeReasons.toRaw());
2462 m_LayerTreeFreezeReasons.add(reason);
2463 updateDrawingAreaLayerTreeFreezeState();
2466 void WebPage::unfreezeLayerTree(LayerTreeFreezeReason reason)
2468 RELEASE_LOG(ProcessSuspension, "%p - WebPage (PageID=%llu) - Removing a reason %d to freeze layer tree; current reasons are %d",
2469 this, m_pageID, static_cast<unsigned>(reason), m_LayerTreeFreezeReasons.toRaw());
2470 m_LayerTreeFreezeReasons.remove(reason);
2471 updateDrawingAreaLayerTreeFreezeState();
2474 void WebPage::updateDrawingAreaLayerTreeFreezeState()
2478 m_drawingArea->setLayerTreeStateIsFrozen(!!m_LayerTreeFreezeReasons);
2481 void WebPage::callVolatilityCompletionHandlers(bool succeeded)
2483 auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2484 for (auto& completionHandler : completionHandlers)
2485 completionHandler(succeeded);
2488 void WebPage::layerVolatilityTimerFired()
2490 Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2491 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2492 if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2493 m_layerVolatilityTimer.stop();
2495 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Succeeded in marking layers as volatile", this);
2497 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Failed to mark layers as volatile within %gms", this, maximumLayerVolatilityTimerInterval.milliseconds());
2498 callVolatilityCompletionHandlers(didSucceed);
2502 RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.milliseconds());
2503 m_layerVolatilityTimer.startRepeating(newInterval);
2506 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2508 return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2511 void WebPage::markLayersVolatile(WTF::Function<void (bool)>&& completionHandler)
2513 RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2515 if (m_layerVolatilityTimer.isActive())
2516 m_layerVolatilityTimer.stop();
2518 if (completionHandler)
2519 m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2521 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2522 if (didSucceed || m_isSuspendedUnderLock) {
2524 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2526 // 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.
2527 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2529 callVolatilityCompletionHandlers(didSucceed);
2533 RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.milliseconds());
2534 m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2537 void WebPage::cancelMarkLayersVolatile()
2539 RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2540 m_layerVolatilityTimer.stop();
2541 m_markLayersAsVolatileCompletionHandlers.clear();
2544 class CurrentEvent {
2546 explicit CurrentEvent(const WebEvent& event)
2547 : m_previousCurrentEvent(g_currentEvent)
2549 g_currentEvent = &event;
2554 g_currentEvent = m_previousCurrentEvent;
2558 const WebEvent* m_previousCurrentEvent;
2561 #if ENABLE(CONTEXT_MENUS)
2562 static bool isContextClick(const PlatformMouseEvent& event)
2565 return WebEventFactory::shouldBeHandledAsContextClick(event);
2567 return event.button() == WebCore::RightButton;
2571 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2573 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2574 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2576 Frame* frame = &page->corePage()->mainFrame();
2577 if (result.innerNonSharedNode())
2578 frame = result.innerNonSharedNode()->document().frame();
2580 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2582 page->contextMenu()->show();
2587 void WebPage::contextMenuForKeyEvent()
2589 corePage()->contextMenuController().clearContextMenu();
2591 Frame& frame = m_page->focusController().focusedOrMainFrame();
2592 bool handled = frame.eventHandler().sendContextMenuEventForKey();
2594 contextMenu()->show();
2598 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2600 Frame& frame = page->corePage()->mainFrame();
2604 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2606 switch (platformMouseEvent.type()) {
2607 case PlatformEvent::MousePressed: {
2608 #if ENABLE(CONTEXT_MENUS)
2609 if (isContextClick(platformMouseEvent))
2610 page->corePage()->contextMenuController().clearContextMenu();
2613 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2614 #if ENABLE(CONTEXT_MENUS)
2615 if (isContextClick(platformMouseEvent))
2616 handled = handleContextMenuEvent(platformMouseEvent, page);
2620 case PlatformEvent::MouseReleased:
2621 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2623 case PlatformEvent::MouseMoved:
2625 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2626 // button is currently pressed. It is possible that neither of those things will be true since on
2627 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2628 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2629 // efficient scrollbars-only version of the event.
2630 if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2631 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2633 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2635 case PlatformEvent::MouseForceChanged:
2636 case PlatformEvent::MouseForceDown:
2637 case PlatformEvent::MouseForceUp:
2638 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2641 ASSERT_NOT_REACHED();
2646 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2648 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2650 m_userActivityHysteresis.impulse();
2652 bool shouldHandleEvent = true;
2654 #if ENABLE(CONTEXT_MENUS)
2655 // Don't try to handle any pending mouse events if a context menu is showing.
2656 if (m_isShowingContextMenu)
2657 shouldHandleEvent = false;
2659 #if ENABLE(DRAG_SUPPORT)
2660 if (m_isStartingDrag)
2661 shouldHandleEvent = false;
2664 if (!shouldHandleEvent) {
2665 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2669 bool handled = false;
2671 #if !PLATFORM(IOS_FAMILY)
2672 if (!handled && m_headerBanner)
2673 handled = m_headerBanner->mouseEvent(mouseEvent);
2674 if (!handled && m_footerBanner)
2675 handled = m_footerBanner->mouseEvent(mouseEvent);
2676 #endif // !PLATFORM(IOS_FAMILY)
2679 CurrentEvent currentEvent(mouseEvent);
2680 handled = handleMouseEvent(mouseEvent, this);
2683 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2686 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2688 Frame& frame = page->mainFrame();
2692 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2693 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2696 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2698 m_userActivityHysteresis.impulse();
2700 CurrentEvent currentEvent(wheelEvent);
2702 bool handled = handleWheelEvent(wheelEvent, m_page.get());
2704 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2707 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2709 if (!page->mainFrame().view())
2712 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2713 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2714 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2717 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2719 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2721 m_userActivityHysteresis.impulse();
2723 PlatformKeyboardEvent::setCurrentModifierState(platform(keyboardEvent).modifiers());
2725 CurrentEvent currentEvent(keyboardEvent);
2727 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2728 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2730 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2732 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2735 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2737 bool isEnabled = false;
2739 Frame& frame = m_page->focusController().focusedOrMainFrame();
2740 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2741 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2743 Editor::Command command = frame.editor().command(commandName);
2744 state = command.state();
2745 isEnabled = command.isSupported() && command.isEnabled();
2748 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2751 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2753 executeEditingCommand(commandName, argument);
2756 void WebPage::setNeedsFontAttributes(bool needsFontAttributes)
2758 if (m_needsFontAttributes == needsFontAttributes)
2761 m_needsFontAttributes = needsFontAttributes;
2763 if (m_needsFontAttributes)
2764 sendPartialEditorStateAndSchedulePostLayoutUpdate();
2767 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest, WebBackForwardListProxy::OverwriteExistingItem overwrite)
2769 // Since we're merely restoring HistoryItems from the UIProcess, there is no need to send HistoryItem update notifications back to the UIProcess.
2770 // Also, with process-swap on navigation, these updates may actually overwrite important state in the UIProcess such as the scroll position.
2771 SetForScope<void (*)(WebCore::HistoryItem&)> bypassHistoryItemUpdateNotifications(WebCore::notifyHistoryItemChanged, [](WebCore::HistoryItem&){});
2772 for (const auto& itemState : itemStates) {
2773 auto historyItem = toHistoryItem(itemState);
2774 historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2775 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, overwrite);
2779 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2781 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes, WebBackForwardListProxy::OverwriteExistingItem::No);
2784 void WebPage::updateBackForwardListForReattach(const Vector<WebKit::BackForwardListItemState>& itemStates)
2786 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2789 void WebPage::setCurrentHistoryItemForReattach(WebKit::BackForwardListItemState&& itemState)
2791 auto historyItem = toHistoryItem(itemState);
2792 auto& historyItemRef = historyItem.get();
2793 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2794 corePage()->mainFrame().loader().history().setCurrentItem(historyItemRef);
2797 void WebPage::requestFontAttributesAtSelectionStart(CallbackID callbackID)
2799 auto attributes = m_page->focusController().focusedOrMainFrame().editor().fontAttributesAtSelectionStart();
2800 send(Messages::WebPageProxy::FontAttributesCallback(attributes, callbackID));
2803 void WebPage::cancelGesturesBlockedOnSynchronousReplies()
2805 #if ENABLE(IOS_TOUCH_EVENTS)
2806 if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2810 #if PLATFORM(IOS_FAMILY)
2811 if (auto reply = WTFMove(m_pendingSynchronousPositionInformationReply))
2812 reply(InteractionInformationAtPosition::invalidInformation());
2816 #if ENABLE(TOUCH_EVENTS)
2817 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2819 if (!page->mainFrame().view())
2822 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2826 #if ENABLE(IOS_TOUCH_EVENTS)
2827 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2829 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2831 auto oldFocusedFrame = makeRefPtr(m_page->focusController().focusedFrame());
2832 auto oldFocusedElement = makeRefPtr(oldFocusedFrame ? oldFocusedFrame->document()->focusedElement() : nullptr);
2834 m_lastInteractionLocation = touchEvent.position();
2835 CurrentEvent currentEvent(touchEvent);
2836 handled = handleTouchEvent(touchEvent, m_page.get());
2837 updatePotentialTapSecurityOrigin(touchEvent, handled);
2839 if (handled && oldFocusedElement) {
2840 auto newFocusedFrame = makeRefPtr(m_page->focusController().focusedFrame());
2841 auto newFocusedElement = makeRefPtr(newFocusedFrame ? newFocusedFrame->document()->focusedElement() : nullptr);
2842 if (oldFocusedElement == newFocusedElement)
2843 elementDidRefocus(*newFocusedElement);
2847 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, CompletionHandler<void(bool)>&& reply)
2849 m_pendingSynchronousTouchEventReply = WTFMove(reply);
2851 EventDispatcher::TouchEventQueue queuedEvents;
2852 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2853 dispatchAsynchronousTouchEvents(queuedEvents);
2855 bool handled = true;
2856 dispatchTouchEvent(touchEvent, handled);
2858 if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2862 void WebPage::updatePotentialTapSecurityOrigin(const WebTouchEvent& touchEvent, bool wasHandled)
2867 if (!touchEvent.isPotentialTap())
2870 if (touchEvent.type() != WebEvent::TouchStart)
2873 auto& mainFrame = m_page->mainFrame();
2874 auto document = mainFrame.document();
2878 if (!document->handlingTouchEvent())
2881 Frame* touchEventTargetFrame = &mainFrame;
2882 while (auto subframe = touchEventTargetFrame->eventHandler().touchEventTargetSubframe())
2883 touchEventTargetFrame = subframe;
2885 auto& touches = touchEventTargetFrame->eventHandler().touches();
2886 if (touches.isEmpty())
2889 ASSERT(touches.size() == 1);
2891 if (auto targetDocument = touchEventTargetFrame->document())
2892 m_potentialTapSecurityOrigin = &targetDocument->securityOrigin();
2894 #elif ENABLE(TOUCH_EVENTS)
2895 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2897 CurrentEvent currentEvent(touchEvent);
2899 bool handled = handleTouchEvent(touchEvent, m_page.get());
2901 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2905 #if ENABLE(POINTER_EVENTS)
2906 void WebPage::cancelPointer(WebCore::PointerID pointerId, const WebCore::IntPoint& documentPoint)
2908 m_page->pointerCaptureController().cancelPointer(pointerId, documentPoint);
2912 #if ENABLE(MAC_GESTURE_EVENTS)
2913 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2915 if (!page->mainFrame().view())
2918 return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2921 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2923 CurrentEvent currentEvent(gestureEvent);
2924 bool handled = handleGestureEvent(gestureEvent, m_page.get());
2925 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2929 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2931 return page->userInputBridge().scrollRecursively(direction, granularity);
2934 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2936 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2939 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2941 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2944 void WebPage::centerSelectionInVisibleArea()
2946 Frame& frame = m_page->focusController().focusedOrMainFrame();
2947 frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2948 findController().showFindIndicatorInSelection();
2951 bool WebPage::isControlledByAutomation() const
2953 return m_page->isControlledByAutomation();
2956 void WebPage::setControlledByAutomation(bool controlled)
2958 m_page->setControlledByAutomation(controlled);
2961 void WebPage::connectInspector(const String& targetId, Inspector::FrontendChannel::ConnectionType connectionType)
2963 m_inspectorTargetController->connectInspector(targetId, connectionType);
2966 void WebPage::disconnectInspector(const String& targetId)
2968 m_inspectorTargetController->disconnectInspector(targetId);
2971 void WebPage::sendMessageToTargetBackend(const String& targetId, const String& message)
2973 m_inspectorTargetController->sendMessageToTargetBackend(targetId, message);
2976 void WebPage::insertNewlineInQuotedContent()
2978 Frame& frame = m_page->focusController().focusedOrMainFrame();
2979 if (frame.selection().isNone())
2981 frame.editor().insertParagraphSeparatorInQuotedContent();
2984 #if ENABLE(REMOTE_INSPECTOR)
2985 void WebPage::setIndicating(bool indicating)
2987 m_page->inspectorController().setIndicating(indicating);
2991 void WebPage::setBackgroundColor(const Optional<WebCore::Color>& backgroundColor)
2993 if (m_backgroundColor == backgroundColor)
2996 m_backgroundColor = backgroundColor;
2998 if (FrameView* frameView = mainFrameView())
2999 frameView->updateBackgroundRecursively(backgroundColor);
3001 m_drawingArea->setNeedsDisplay();
3005 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
3007 if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
3008 LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
3012 m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
3014 setTopContentInset(contentInset);
3016 deallocateSendRightSafely(fencePort.port());
3020 void WebPage::setTopContentInset(float contentInset)
3022 if (contentInset == m_page->topContentInset())
3025 m_page->setTopContentInset(contentInset);
3027 for (auto* pluginView : m_pluginViews)
3028 pluginView->topContentInsetDidChange();
3031 void WebPage::viewWillStartLiveResize()
3036 // FIXME: This should propagate to all ScrollableAreas.
3037 Frame& frame = m_page->focusController().focusedOrMainFrame();
3038 if (FrameView* view = frame.view())
3039 view->willStartLiveResize();
3042 void WebPage::viewWillEndLiveResize()
3047 // FIXME: This should propagate to all ScrollableAreas.
3048 Frame& frame = m_page->focusController().focusedOrMainFrame();
3049 if (FrameView* view = frame.view())
3050 view->willEndLiveResize();
3053 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
3058 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
3060 Frame& frame = m_page->focusController().focusedOrMainFrame();
3061 frame.document()->setFocusedElement(0);
3063 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
3064 PlatformKeyboardEvent platformEvent(platform(event));
3065 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
3066 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
3068 send(Messages::WebPageProxy::VoidCallback(callbackID));
3072 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
3073 send(Messages::WebPageProxy::VoidCallback(callbackID));
3076 void WebPage::setCanStartMediaTimerFired()
3079 m_page->setCanStartMedia(true);
3082 void WebPage::updateIsInWindow(bool isInitialState)
3084 bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
3087 m_setCanStartMediaTimer.stop();
3088 m_page->setCanStartMedia(false);
3090 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
3091 if (!isInitialState)
3092 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
3094 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
3095 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
3096 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
3097 if (m_mayStartMediaWhenInWindow)
3098 m_setCanStartMediaTimer.startOneShot(0_s);
3100 WebProcess::singleton().pageDidEnterWindow(m_pageID);
3107 void WebPage::visibilityDidChange()
3109 bool isVisible = m_activityState.contains(ActivityState::IsVisible);
3111 // We save the document / scroll state when backgrounding a tab so that we are able to restore it
3112 // if it gets terminated while in the background.
3113 if (auto* frame = m_mainFrame->coreFrame())
3114 frame->loader().history().saveDocumentAndScrollState();
3118 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
3120 LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
3122 auto changed = m_activityState ^ activityState;
3123 m_activityState = activityState;
3126 updateThrottleState();
3128 ASSERT_WITH_MESSAGE(m_page, "setActivityState called on %" PRIu64 " but WebCore page was null", pageID());
3130 SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
3131 m_page->setActivityState(activityState);
3134 for (auto* pluginView : m_pluginViews)
3135 pluginView->activityStateDidChange(changed);
3137 m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
3138 WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
3140 if (changed & ActivityState::IsInWindow)
3143 if (changed & ActivityState::IsVisible)
3144 visibilityDidChange();
3147 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
3149 m_layerHostingMode = layerHostingMode;
3151 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
3153 for (auto* pluginView : m_pluginViews)
3154 pluginView->setLayerHostingMode(m_layerHostingMode);
3157 void WebPage::setSessionID(PAL::SessionID sessionID)
3159 m_page->setSessionID(sessionID);
3162 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyCheckIdentifier identifier, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, Optional<WebsitePoliciesData>&& websitePolicies)
3164 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3167 frame->didReceivePolicyDecision(listenerID, identifier, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
3170 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
3172 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3175 frame->continueWillSubmitForm(listenerID);
3178 void WebPage::didStartPageTransition()
3180 freezeLayerTree(LayerTreeFreezeReason::PageTransition);
3183 bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
3185 m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
3186 m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
3188 if (hasPreviouslyFocusedDueToUserInteraction)
3189 send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
3190 if (m_isTouchBarUpdateSupressedForHiddenContentEditable) {
3191 m_isTouchBarUpdateSupressedForHiddenContentEditable = false;
3192 send(Messages::WebPageProxy::SetIsTouchBarUpdateSupressedForHiddenContentEditable(m_isTouchBarUpdateSupressedForHiddenContentEditable));
3194 if (m_isNeverRichlyEditableForTouchBar) {
3195 m_isNeverRichlyEditableForTouchBar = false;
3196 send(Messages::WebPageProxy::SetIsNeverRichlyEditableForTouchBar(m_isNeverRichlyEditableForTouchBar));
3199 #if PLATFORM(IOS_FAMILY)
3200 m_isShowingInputViewForFocusedElement = false;
3204 void WebPage::didCompletePageTransition()
3206 unfreezeLayerTree(LayerTreeFreezeReason::PageTransition);
3208 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did complete page transition", this);
3210 bool isInitialEmptyDocument = !m_mainFrame;
3211 if (!isInitialEmptyDocument)
3212 unfreezeLayerTree(LayerTreeFreezeReason::ProcessSwap);
3215 void WebPage::show()
3217 send(Messages::WebPageProxy::ShowPage());
3220 String WebPage::userAgent(const URL& webCoreURL) const
3222 String userAgent = platformUserAgent(webCoreURL);
3223 if (!userAgent.isEmpty())
3228 void WebPage::setUserAgent(const String& userAgent)
3230 if (m_userAgent == userAgent)
3233 m_userAgent = userAgent;
3236 m_page->userAgentChanged();
3239 void WebPage::suspendActiveDOMObjectsAndAnimations()
3241 m_page->suspendActiveDOMObjectsAndAnimations();
3244 void WebPage::resumeActiveDOMObjectsAndAnimations()
3246 m_page->resumeActiveDOMObjectsAndAnimations();
3249 IntPoint WebPage::screenToRootView(const IntPoint& point)
3251 IntPoint windowPoint;
3252 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
3256 IntRect WebPage::rootViewToScreen(const IntRect& rect)
3259 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
3263 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
3265 IntPoint windowPoint;
3266 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
3270 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
3273 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
3277 KeyboardUIMode WebPage::keyboardUIMode()
3279 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
3280 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
3283 void WebPage::runJavaScript(const String& script, bool forceUserGesture, Optional<String> worldName, CallbackID callbackID)
3285 // NOTE: We need to be careful when running scripts that the objects we depend on don't
3286 // disappear during script execution.
3288 RefPtr<SerializedScriptValue> serializedResultValue;
3289 JSLockHolder lock(commonVM());
3290 bool hadException = true;
3291 ExceptionDetails details;
3292 auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
3294 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeUserAgentScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
3295 hadException = false;
3296 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
3297 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
3301 IPC::DataReference dataReference;
3302 if (serializedResultValue)
3303 dataReference = serializedResultValue->data();
3304 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
3307 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
3309 runJavaScript(script, forceUserGesture, WTF::nullopt, callbackID);
3312 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
3314 runJavaScript(script, forceUserGesture, worldName, callbackID);
3317 void WebPage::getContentsAsString(CallbackID callbackID)
3319 String resultString = m_mainFrame->contentsAsString();
3320 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3324 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
3326 send(Messages::WebPageProxy::DataCallback({ MHTMLArchive::generateMHTMLData(m_page.get()) }, callbackID));
3330 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3332 String resultString = renderTreeExternalRepresentation();
3333 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3336 static Frame* frameWithSelection(Page* page)
3338 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3339 if (frame->selection().isRange())
3346 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3349 RetainPtr<CFDataRef> data;
3350 if (Frame* frame = frameWithSelection(m_page.get()))
3351 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3354 IPC::SharedBufferDataReference dataReference;
3357 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3359 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3362 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3364 WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3365 String resultString = focusedOrMainFrame->selectionAsString();
3366 if (resultString.isEmpty())
3367 resultString = focusedOrMainFrame->contentsAsString();
3368 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3371 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3373 String resultString;
3374 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3375 resultString = frame->source();
3377 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3380 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3382 RefPtr<SharedBuffer> buffer;
3383 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3384 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3385 buffer = pluginView->liveResourceData();
3387 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3388 buffer = loader->mainResourceData();
3392 IPC::SharedBufferDataReference dataReference;
3394 dataReference = { *buffer };
3395 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3398 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3400 DocumentLoader* loader = frame->loader().documentLoader();
3404 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3408 return &subresource->data();
3411 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3413 RefPtr<SharedBuffer> buffer;
3414 if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3415 URL resourceURL(URL(), resourceURLString);
3416 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3419 IPC::SharedBufferDataReference dataReference;
3421 dataReference = { *buffer };
3422 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3425 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3428 RetainPtr<CFDataRef> data;
3429 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3430 data = frame->webArchiveData(nullptr, nullptr);
3432 UNUSED_PARAM(frameID);
3435 IPC::SharedBufferDataReference dataReference;
3438 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3440 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3443 void WebPage::forceRepaintWithoutCallback()
3445 m_drawingArea->forceRepaint();
3448 void WebPage::forceRepaint(CallbackID callbackID)
3450 if (m_drawingArea->forceRepaintAsync(callbackID))
3453 forceRepaintWithoutCallback();
3454 send(Messages::WebPageProxy::VoidCallback(callbackID));
3457 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3459 WebPreferencesStore::removeTestRunnerOverrides();
3460 updatePreferences(store);
3463 void WebPage::updatePreferences(const WebPreferencesStore& store)
3465 updatePreferencesGenerated(store);
3467 Settings& settings = m_page->settings();
3470 if (!settings.acceleratedCompositingEnabled()) {
3471 RELEASE_LOG_IF_ALLOWED("%p - WebPage - acceleratedCompositingEnabled setting was false. WebKit cannot function in this mode; changing setting to true", this);
3472 settings.setAcceleratedCompositingEnabled(true);
3476 bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3477 settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3478 settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3479 settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3480 settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3481 settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3482 settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3483 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3484 settings.setFrameFlattening(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()) ? WebCore::FrameFlattening::FullyEnabled : WebCore::FrameFlattening::Disabled);
3485 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3486 #if ENABLE(DATA_DETECTION)
3487 settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3490 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3492 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3493 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3494 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3495 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3497 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3498 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3500 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3501 setSessionID(PAL::SessionID::legacyPrivateSessionID());
3502 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3503 setSessionID(PAL::SessionID::defaultSessionID());
3505 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3506 if (m_processSuppressionEnabled != processSuppressionEnabled) {
3507 m_processSuppressionEnabled = processSuppressionEnabled;
3508 updateThrottleState();
3512 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3514 #if ENABLE(PAYMENT_REQUEST)
3515 settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3518 // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3519 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3521 #if PLATFORM(IOS_FAMILY)
3522 m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3523 m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3524 setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3526 settings.setUseImageDocumentForSubframePDF(true);
3528 DeprecatedGlobalSettings::setAVKitEnabled(true);
3532 #if ENABLE(SERVICE_WORKER)
3533 if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3534 ASSERT(parentProcessHasServiceWorkerEntitlement());
3535 if (!parentProcessHasServiceWorkerEntitlement())
3536 RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3540 settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3543 m_drawingArea->updatePreferences(store);
3546 #if ENABLE(DATA_DETECTION)
3548 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3550 DataDetectionResult dataDetectionResult;
3551 dataDetectionResult.results = detectionResults;
3552 send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3555 void WebPage::removeDataDetectedLinks(CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3557 for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3558 auto document = makeRefPtr(frame->document());
3562 DataDetection::removeDataDetectedLinksInDocument(*document);
3563 frame->setDataDetectionResults(nullptr);
3565 completionHandler({ m_page->mainFrame().dataDetectionResults() });
3568 void WebPage::detectDataInAllFrames(uint64_t types, CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3570 auto dataDetectorTypes = static_cast<WebCore::DataDetectorTypes>(types);
3571 for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3572 auto document = makeRefPtr(frame->document());
3576 RefPtr<Range> range = Range::create(*document, Position { document.get(), Position::PositionIsBeforeChildren }, Position { document.get(), Position::PositionIsAfterChildren });
3577 frame->setDataDetectionResults(DataDetection::detectContentInRange(range, dataDetectorTypes, m_dataDetectionContext.get()));
3579 completionHandler({ m_page->mainFrame().dataDetectionResults() });
3582 #endif // ENABLE(DATA_DETECTION)
3585 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3587 FrameView* frameView = corePage()->mainFrame().view();
3591 layerTransaction.setContentsSize(frameView->contentsSize());
3592 layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3593 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3594 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3595 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3597 layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3598 layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3599 layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3601 #if PLATFORM(IOS_FAMILY)
3602 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3603 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3604 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3605 layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3606 layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3607 layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3608 layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3609 layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3610 layerTransaction.setIsInStableState(m_isInStableState);
3611 layerTransaction.setAllowsUserScaling(allowsUserScaling());
3612 if (m_pendingDynamicViewportSizeUpdateID) {
3613 layerTransaction.setDynamicViewportSizeUpdateID(*m_pendingDynamicViewportSizeUpdateID);
3614 m_pendingDynamicViewportSizeUpdateID = WTF::nullopt;
3616 if (m_lastTransactionPageScaleFactor != layerTransaction.pageScaleFactor()) {
3617 m_lastTransactionPageScaleFactor = layerTransaction.pageScaleFactor();
3618 m_lastTransactionIDWithScaleChange = layerTransaction.transactionID();
3622 layerTransaction.setScrollPosition(frameView->scrollPosition());
3624 if (m_hasPendingEditorStateUpdate) {
3625 layerTransaction.setEditorState(editorState());
3626 m_hasPendingEditorStateUpdate = false;
3630 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3632 #if PLATFORM(IOS_FAMILY)
3633 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3634 Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3635 m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3637 m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3640 UNUSED_PARAM(timestamp);
3645 void WebPage::willDisplayPage()
3647 m_page->willDisplayPage();
3650 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3654 if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3655 m_inspector = WebInspector::create(this);
3656 return m_inspector.get();
3659 WebInspectorUI* WebPage::inspectorUI()
3664 m_inspectorUI = WebInspectorUI::create(*this);
3665 return m_inspectorUI.get();
3668 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3672 if (!m_remoteInspectorUI)
3673 m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3674 return m_remoteInspectorUI.get();
3677 void WebPage::inspectorFrontendCountChanged(unsigned count)
3679 send(Messages::WebPageProxy::DidChangeInspectorFrontendCount(count));
3682 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3683 PlaybackSessionManager& WebPage::playbackSessionManager()
3685 if (!m_playbackSessionManager)
3686 m_playbackSessionManager = PlaybackSessionManager::create(*this);
3687 return *m_playbackSessionManager;
3690 VideoFullscreenManager& WebPage::videoFullscreenManager()
3692 if (!m_videoFullscreenManager)
3693 m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3694 return *m_videoFullscreenManager;
3697 void WebPage::videoControlsManagerDidChange()
3699 #if ENABLE(FULLSCREEN_API)
3700 if (auto* manager = fullScreenManager())
3701 manager->videoControlsManagerDidChange();
3707 #if PLATFORM(IOS_FAMILY)
3708 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3710 m_page->setAllowsMediaDocumentInlinePlayback(allows);
3714 #if ENABLE(FULLSCREEN_API)
3715 WebFullScreenManager* WebPage::fullScreenManager()
3717 if (!m_fullScreenManager)
3718 m_fullScreenManager = WebFullScreenManager::create(this);
3719 return m_fullScreenManager.get();
3723 void WebPage::addConsoleMessage(uint64_t frameID, MessageSource messageSource, MessageLevel messageLevel, const String& message, uint64_t requestID)
3725 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3726 frame->addConsoleMessage(messageSource, messageLevel, message, requestID);
3729 void WebPage::sendCSPViolationReport(uint64_t frameID, const URL& reportURL, IPC::FormDataReference&& reportData)
3731 auto report = reportData.takeData();
3734 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3735 PingLoader::sendViolationReport(*frame->coreFrame(), reportURL, report.releaseNonNull(), ViolationReportType::ContentSecurityPolicy);
3738 void WebPage::enqueueSecurityPolicyViolationEvent(uint64_t frameID, SecurityPolicyViolationEvent::Init&& eventInit)
3740 auto* frame = WebProcess::singleton().webFrame(frameID);
3743 auto* coreFrame = frame->coreFrame();
3746 if (auto* document = coreFrame->document())
3747 document->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
3750 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3752 if (m_notificationPermissionRequestManager)
3753 return m_notificationPermissionRequestManager.get();
3755 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3756 return m_notificationPermissionRequestManager.get();
3759 #if ENABLE(DRAG_SUPPORT)
3762 void WebPage::performDragControllerAction(DragControllerAction action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3765 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3769 DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3771 case DragControllerAction::Entered: {
3772 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3773 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3776 case DragControllerAction::Updated: {
3777 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3778 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3781 case DragControllerAction::Exited:
3782 m_page->dragController().dragExited(dragData);
3785 case DragControllerAction::PerformDragOperation: {
3786 m_page->dragController().performDragOperation(dragData);
3790 ASSERT_NOT_REACHED();
3793 void WebPage::performDragControllerAction(DragControllerAction action, const WebCore::DragData& dragData, SandboxExtension::Handle&& sandboxExtensionHandle, SandboxExtension::HandleArray&& sandboxExtensionsHandleArray)
3796 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3801 case DragControllerAction::Entered: {
3802 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3803 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()));
3806 case DragControllerAction::Updated: {
3807 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3808 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()));
3811 case DragControllerAction::Exited:
3812 m_page->dragController().dragExited(dragData);
3813 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3816 case DragControllerAction::PerformDragOperation: {
3817 ASSERT(!m_pendingDropSandboxExtension);
3819 m_pendingDropSandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
3820 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3821 if (auto extension = SandboxExtension::create(WTFMove(sandboxExtensionsHandleArray[i])))
3822 m_pendingDropExtensionsForFileUpload.append(extension);
3825 bool handled = m_page->dragController().performDragOperation(dragData);
3827 // If we started loading a local file, the sandbox extension tracker would have adopted this
3828 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3829 m_pendingDropSandboxExtension = nullptr;
3831 m_pendingDropExtensionsForFileUpload.clear();
3832 send(Messages::WebPageProxy::DidPerformDragOperation(handled));
3836 ASSERT_NOT_REACHED();
3840 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3842 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3843 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3845 m_page->dragController().dragEnded();
3846 FrameView* view = m_page->mainFrame().view();
3849 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3850 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), 0, WebCore::NoTap);
3851 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3853 send(Messages::WebPageProxy::DidEndDragging());
3856 void WebPage::willPerformLoadDragDestinationAction()
3858 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(WTFMove(m_pendingDropSandboxExtension));
3861 void WebPage::mayPerformUploadDragDestinationAction()
3863 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3864 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3865 m_pendingDropExtensionsForFileUpload.clear();
3868 void WebPage::didStartDrag()
3870 m_isStartingDrag = false;
3871 m_page->mainFrame().eventHandler().didStartDrag();
3874 void WebPage::dragCancelled()
3876 m_isStartingDrag = false;
3877 m_page->mainFrame().eventHandler().dragCancelled();
3880 #endif // ENABLE(DRAG_SUPPORT)
3882 WebUndoStep* WebPage::webUndoStep(WebUndoStepID stepID)
3884 return m_undoStepMap.get(stepID);
3887 void WebPage::addWebUndoStep(WebUndoStepID stepID, Ref<WebUndoStep>&& entry)
3889 auto addResult = m_undoStepMap.set(stepID, WTFMove(entry));
3890 ASSERT_UNUSED(addResult, addResult.isNewEntry);
3893 void WebPage::removeWebEditCommand(WebUndoStepID stepID)
3895 if (auto undoStep = m_undoStepMap.take(stepID))
3896 undoStep->didRemoveFromUndoManager();
3899 bool WebPage::isAlwaysOnLoggingAllowed() const
3901 return corePage() && corePage()->isAlwaysOnLoggingAllowed();
3904 void WebPage::unapplyEditCommand(WebUndoStepID stepID)
3906 auto* step = webUndoStep(stepID);
3910 step->step().unapply();
3913 void WebPage::reapplyEditCommand(WebUndoStepID stepID)
3915 auto* step = webUndoStep(stepID);
3920 step->step().reapply();
3924 void WebPage::didRemoveEditCommand(WebUndoStepID commandID)
3926 removeWebEditCommand(commandID);
3929 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3931 m_activePopupMenu = menu;
3934 #if ENABLE(INPUT_TYPE_COLOR)
3936 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3938 m_activeColorChooser = colorChooser;
3941 void WebPage::didEndColorPicker()
3943 m_activeColorChooser->didEndChooser();
3946 void WebPage::didChooseColor(const WebCore::Color& color)
3948 m_activeColorChooser->didChooseColor(color);
3953 #if ENABLE(DATALIST_ELEMENT)
3955 void WebPage::setActiveDataListSuggestionPicker(WebDataListSuggestionPicker* dataListSuggestionPicker)
3957 m_activeDataListSuggestionPicker = makeWeakPtr(dataListSuggestionPicker);
3960 void WebPage::didSelectDataListOption(const String& selectedOption)
3962 if (m_activeDataListSuggestionPicker)
3963 m_activeDataListSuggestionPicker->didSelectOption(selectedOption);
3966 void WebPage::didCloseSuggestions()
3968 if (auto picker = std::exchange(m_activeDataListSuggestionPicker, nullptr))
3969 picker->didCloseSuggestions();
3974 void WebPage::setActiveOpenPanelResultListener(Ref<WebOpenPanelResultListener>&& openPanelResultListener)
3976 m_activeOpenPanelResultListener = WTFMove(openPanelResultListener);
3979 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3981 return m_page->findString(target, core(options));
3984 void WebPage::findStringMatchesFromInjectedBundle(const String& target, FindOptions options)
3986 findController().findStringMatches(target, options, 0);
3989 void WebPage::replaceStringMatchesFromInjectedBundle(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly)
3991 findController().replaceMatches(matchIndices, replacementText, selectionOnly);
3994 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3996 findController().findString(string, static_cast<FindOptions>(options), maxMatchCount);
3999 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
4001 findController().findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
4004 void WebPage::getImageForFindMatch(uint32_t matchIndex)
4006 findController().getImageForFindMatch(matchIndex);
4009 void WebPage::selectFindMatch(uint32_t matchIndex)
4011 findController().selectFindMatch(matchIndex);
4014 void WebPage::hideFindUI()
4016 findController().hideFindUI();
4019 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
4021 findController().countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
4024 void WebPage::replaceMatches(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly, CallbackID callbackID)
4026 auto numberOfReplacements = findController().replaceMatches(matchIndices, replacementText, selectionOnly);
4027 send(Messages::WebPageProxy::UnsignedCallback(numberOfReplacements, callbackID));
4030 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
4032 changeSelectedIndex(newIndex);
4033 m_activePopupMenu = nullptr;
4036 void WebPage::changeSelectedIndex(int32_t index)
4038 if (!m_activePopupMenu)
4041 m_activePopupMenu->didChangeSelectedIndex(index);
4044 #if PLATFORM(IOS_FAMILY)
4045 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
4047 if (!m_activeOpenPanelResultListener)
4051 if (!iconData.isEmpty()) {
4052 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
4053 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
4054 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
4055 icon = Icon::createIconForImage(imageRef.get());
4058 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
4059 m_activeOpenPanelResultListener = nullptr;
4063 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
4065 if (!m_activeOpenPanelResultListener)
4068 m_activeOpenPanelResultListener->didChooseFiles(files);
4069 m_activeOpenPanelResultListener = nullptr;
4072 void WebPage::didCancelForOpenPanel()
4074 m_activeOpenPanelResultListener = nullptr;
4077 #if ENABLE(SANDBOX_EXTENSIONS)
4078 void WebPage::extendSandboxForFilesFromOpenPanel(SandboxExtension::HandleArray&& handles)
4080 for (size_t i = 0; i < handles.size(); ++i) {
4081 bool result = SandboxExtension::consumePermanently(handles[i]);
4083 // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
4084 WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
4090 #if ENABLE(GEOLOCATION)
4091 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
4093 geolocationPermissionRequestManager().didReceiveGeolocationPermissionDecision(geolocationID, allowed);
4097 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
4099 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
4102 #if ENABLE(MEDIA_STREAM)
4104 void WebPage::userMediaAccessWasGranted(uint64_t userMediaID, WebCore::CaptureDevice&& audioDevice, WebCore::CaptureDevice&& videoDevice, String&& mediaDeviceIdentifierHashSalt)
4106 m_userMediaPermissionRequestManager->userMediaAccessWasGranted(userMediaID, WTFMove(audioDevice), WTFMove(videoDevice), WTFMove(mediaDeviceIdentifierHashSalt));
4109 void WebPage::userMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String&& invalidConstraint)
4111 m_userMediaPermissionRequestManager->userMediaAccessWasDenied(userMediaID, static_cast<UserMediaRequest::MediaAccessDenialReason>(reason), WTFMove(invalidConstraint));
4114 void WebPage::didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vector<CaptureDevice>& devices, String&& deviceIdentifierHashSalt, bool originHasPersistentAccess)
4116 m_userMediaPermissionRequestManager->didCompleteMediaDeviceEnumeration(userMediaID, devices, WTFMove(deviceIdentifierHashSalt), originHasPersistentAccess);
4119 void WebPage::captureDevicesChanged()
4121 m_userMediaPermissionRequestManager->captureDevicesChanged();
4126 #if !PLATFORM(IOS_FAMILY)
4127 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
4129 Frame& frame = m_page->focusController().focusedOrMainFrame();
4130 frame.editor().advanceToNextMisspelling(startBeforeSelection);
4134 bool WebPage::hasRichlyEditableSelection() const
4136 auto& frame = m_page->focusController().focusedOrMainFrame();
4137 if (m_page->dragCaretController().isContentRichlyEditable())
4140 return frame.selection().selection().isContentRichlyEditable();
4143 void WebPage::changeSpellingToWord(const String& word)
4145 replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
4148 void WebPage::unmarkAllMisspellings()
4150 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {