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 "RemoteObjectRegistry.h"
258 #include "RemoteObjectRegistryMessages.h"
259 #include "TextCheckingControllerProxy.h"
260 #include "TouchBarMenuData.h"
261 #include "TouchBarMenuItemData.h"
262 #include "VideoFullscreenManager.h"
263 #include "WKStringCF.h"
264 #include <WebCore/LegacyWebArchive.h>
265 #include <WebCore/UTIRegistry.h>
266 #include <wtf/MachSendRight.h>
270 #include "WebPrintOperationGtk.h"
271 #include "WebSelectionData.h"
275 #if PLATFORM(IOS_FAMILY)
276 #include "InteractionInformationAtPosition.h"
277 #include "InteractionInformationRequest.h"
278 #include "RemoteLayerTreeDrawingArea.h"
279 #include "WebAutocorrectionContext.h"
280 #include <CoreGraphics/CoreGraphics.h>
281 #include <WebCore/Icon.h>
282 #include <pal/spi/cocoa/CoreTextSPI.h>
286 #include <WebCore/LocalDefaultSystemAppearance.h>
287 #include <pal/spi/cf/CFUtilitiesSPI.h>
291 #include <wtf/RefCountedLeakCounter.h>
294 #if ENABLE(DATA_DETECTION)
295 #include <WebCore/DataDetection.h>
298 #if ENABLE(VIDEO) && USE(GSTREAMER)
299 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
302 #if ENABLE(WEB_AUTHN)
303 #include "WebAuthenticatorCoordinator.h"
304 #include <WebCore/AuthenticatorCoordinator.h>
309 using namespace WebCore;
311 static const Seconds pageScrollHysteresisDuration { 300_ms };
312 static const Seconds initialLayerVolatilityTimerInterval { 20_ms };
313 static const Seconds maximumLayerVolatilityTimerInterval { 2_s };
315 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
316 #define RELEASE_LOG_ERROR_IF_ALLOWED(...) RELEASE_LOG_ERROR_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
318 class SendStopResponsivenessTimer {
320 ~SendStopResponsivenessTimer()
322 WebProcess::singleton().parentProcessConnection()->send(Messages::WebProcessProxy::StopResponsivenessTimer(), 0);
326 class DeferredPageDestructor {
328 static void createDeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
330 new DeferredPageDestructor(WTFMove(page), webPage);
334 DeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
335 : m_page(WTFMove(page))
341 void tryDestruction()
343 if (m_page->insideNestedRunLoop()) {
344 m_page->whenUnnested([this] { tryDestruction(); });
353 std::unique_ptr<Page> m_page;
354 RefPtr<WebPage> m_webPage;
357 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
359 Ref<WebPage> WebPage::create(uint64_t pageID, WebPageCreationParameters&& parameters)
361 Ref<WebPage> page = adoptRef(*new WebPage(pageID, WTFMove(parameters)));
363 if (WebProcess::singleton().injectedBundle())
364 WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
369 WebPage::WebPage(uint64_t pageID, WebPageCreationParameters&& parameters)
371 , m_viewSize(parameters.viewSize)
372 , m_alwaysShowsHorizontalScroller { parameters.alwaysShowsHorizontalScroller }
373 , m_alwaysShowsVerticalScroller { parameters.alwaysShowsVerticalScroller }
374 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
375 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
377 , m_layerHostingMode(parameters.layerHostingMode)
378 #if ENABLE(PLATFORM_DRIVEN_TEXT_CHECKING)
379 , m_textCheckingControllerProxy(makeUniqueRef<TextCheckingControllerProxy>(*this))
381 #if PLATFORM(COCOA) || PLATFORM(GTK)
382 , m_viewGestureGeometryCollector(std::make_unique<ViewGestureGeometryCollector>(*this))
383 #elif HAVE(ACCESSIBILITY) && PLATFORM(GTK)
384 , m_accessibilityObject(nullptr)
386 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
387 #if ENABLE(CONTEXT_MENUS)
388 , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
390 , m_editorClient { std::make_unique<API::InjectedBundle::EditorClient>() }
391 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
392 , m_loaderClient(std::make_unique<API::InjectedBundle::PageLoaderClient>())
393 , m_resourceLoadClient(std::make_unique<API::InjectedBundle::ResourceLoadClient>())
394 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
395 , m_findController(makeUniqueRef<FindController>(this))
396 , m_inspectorTargetController(std::make_unique<WebPageInspectorTargetController>(*this))
397 , m_userContentController(WebUserContentController::getOrCreate(parameters.userContentControllerID))
398 #if ENABLE(GEOLOCATION)
399 , m_geolocationPermissionRequestManager(makeUniqueRef<GeolocationPermissionRequestManager>(*this))
401 #if ENABLE(MEDIA_STREAM)
402 , m_userMediaPermissionRequestManager { makeUniqueRef<UserMediaPermissionRequestManager>(*this) }
404 , m_pageScrolledHysteresis([this](PAL::HysteresisState state) { if (state == PAL::HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisDuration)
405 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
406 , m_canRunModal(parameters.canRunModal)
407 #if PLATFORM(IOS_FAMILY)
408 , m_forceAlwaysUserScalable(parameters.ignoresViewportScaleLimits)
409 , m_screenSize(parameters.screenSize)
410 , m_availableScreenSize(parameters.availableScreenSize)
411 , m_overrideScreenSize(parameters.overrideScreenSize)
412 , m_deviceOrientation(parameters.deviceOrientation)
413 , m_keyboardIsAttached(parameters.keyboardIsAttached)
415 , m_layerVolatilityTimer(*this, &WebPage::layerVolatilityTimerFired)
416 , m_activityState(parameters.activityState)
417 , m_processSuppressionEnabled(true)
418 , m_userActivity("Process suppression disabled for page.")
419 , m_userActivityHysteresis([this](PAL::HysteresisState) { updateUserActivity(); })
420 , m_userInterfaceLayoutDirection(parameters.userInterfaceLayoutDirection)
421 , m_overrideContentSecurityPolicy { parameters.overrideContentSecurityPolicy }
422 , m_cpuLimit(parameters.cpuLimit)
424 , m_hostFileDescriptor(WTFMove(parameters.hostFileDescriptor))
429 m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
431 #if PLATFORM(IOS_FAMILY)
432 DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(true);
435 PageConfiguration pageConfiguration(
436 makeUniqueRef<WebEditorClient>(this),
437 WebSocketProvider::create(),
438 makeUniqueRef<WebKit::LibWebRTCProvider>(),
439 WebProcess::singleton().cacheStorageProvider(),
440 WebBackForwardListProxy::create(*this),
441 WebCookieJar::create()
443 pageConfiguration.chromeClient = new WebChromeClient(*this);
444 #if ENABLE(CONTEXT_MENUS)
445 pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
447 #if ENABLE(DRAG_SUPPORT)
448 pageConfiguration.dragClient = new WebDragClient(this);
450 pageConfiguration.inspectorClient = new WebInspectorClient(this);
451 #if USE(AUTOCORRECTION_PANEL)
452 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
455 pageConfiguration.plugInClient = new WebPlugInClient(*this);
456 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
457 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
458 pageConfiguration.diagnosticLoggingClient = std::make_unique<WebDiagnosticLoggingClient>(*this);
459 pageConfiguration.performanceLoggingClient = std::make_unique<WebPerformanceLoggingClient>(*this);
461 pageConfiguration.webGLStateTracker = std::make_unique<WebGLStateTracker>([this](bool isUsingHighPerformanceWebGL) {
462 send(Messages::WebPageProxy::SetIsUsingHighPerformanceWebGL(isUsingHighPerformanceWebGL));
465 #if ENABLE(SPEECH_SYNTHESIS)
466 pageConfiguration.speechSynthesisClient = std::make_unique<WebSpeechSynthesisClient>(*this);
470 pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(*this);
473 pageConfiguration.applicationCacheStorage = &WebProcess::singleton().applicationCacheStorage();
474 pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
475 pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
476 pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
477 pageConfiguration.userContentProvider = m_userContentController.ptr();
478 pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
480 #if ENABLE(APPLE_PAY)
481 pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinator(*this);
484 #if ENABLE(WEB_AUTHN)
485 pageConfiguration.authenticatorCoordinatorClient = std::make_unique<WebAuthenticatorCoordinator>(*this);
488 #if ENABLE(APPLICATION_MANIFEST)
489 pageConfiguration.applicationManifest = parameters.applicationManifest;
492 m_page = std::make_unique<Page>(WTFMove(pageConfiguration));
494 // Set the sessionID *before* updating the preferences as the privateBrowsingEnabled preferences may need to override it.
495 if (parameters.sessionID.isValid())
496 setSessionID(parameters.sessionID);
498 updatePreferences(parameters.store);
500 m_drawingArea = DrawingArea::create(*this, parameters);
501 m_drawingArea->setPaintingEnabled(false);
502 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
504 if (parameters.isProcessSwap)
505 freezeLayerTree(LayerTreeFreezeReason::ProcessSwap);
507 #if ENABLE(ASYNC_SCROLLING)
508 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
509 if (!m_drawingArea->supportsAsyncScrolling())
510 m_useAsyncScrolling = false;
511 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
514 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
515 m_drawingArea->updatePreferences(parameters.store);
517 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
518 setPageAndTextZoomFactors(parameters.pageZoomFactor, parameters.textZoomFactor);
520 #if ENABLE(GEOLOCATION)
521 WebCore::provideGeolocationTo(m_page.get(), *new WebGeolocationClient(*this));
523 #if ENABLE(NOTIFICATIONS)
524 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
526 #if ENABLE(MEDIA_STREAM)
527 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
530 m_page->setControlledByAutomation(parameters.controlledByAutomation);
532 m_page->setCanStartMedia(false);
533 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
535 m_page->setGroupName(m_pageGroup->identifier());
536 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
537 m_page->setUserInterfaceLayoutDirection(m_userInterfaceLayoutDirection);
538 #if PLATFORM(IOS_FAMILY)
539 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
542 platformInitialize();
544 setUseFixedLayout(parameters.useFixedLayout);
546 setUnderlayColor(parameters.underlayColor);
548 setPaginationMode(parameters.paginationMode);
549 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
550 setPageLength(parameters.pageLength);
551 setGapBetweenPages(parameters.gapBetweenPages);
552 setPaginationLineGridEnabled(parameters.paginationLineGridEnabled);
554 setUseDarkAppearance(parameters.useDarkAppearance);
556 if (parameters.isEditable)
560 setUseSystemAppearance(parameters.useSystemAppearance);
563 // If the page is created off-screen, its visibilityState should be prerender.
564 m_page->setActivityState(m_activityState);
566 m_page->setIsPrerender();
568 updateIsInWindow(true);
570 setViewLayoutSize(parameters.viewLayoutSize);
571 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
572 setViewportSizeForCSSViewportUnits(parameters.viewportSizeForCSSViewportUnits);
574 setScrollPinningBehavior(parameters.scrollPinningBehavior);
575 if (parameters.scrollbarOverlayStyle)
576 m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
578 m_scrollbarOverlayStyle = Optional<ScrollbarOverlayStyle>();
580 setTopContentInset(parameters.topContentInset);
582 m_userAgent = parameters.userAgent;
584 if (!parameters.itemStates.isEmpty())
585 restoreSessionInternal(parameters.itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
587 m_drawingArea->setPaintingEnabled(true);
589 setMediaVolume(parameters.mediaVolume);
591 setMuted(parameters.muted);
593 // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
594 m_page->addLayoutMilestones({ DidFirstLayout, DidFirstVisuallyNonEmptyLayout });
596 auto& webProcess = WebProcess::singleton();
597 webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
599 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
600 webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
601 webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
602 webProcess.addMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID, *this);
603 #if ENABLE(FULLSCREEN_API)
604 webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
608 webPageCounter.increment();
611 #if ENABLE(ASYNC_SCROLLING)
612 if (m_useAsyncScrolling)
613 webProcess.eventDispatcher().addScrollingTreeForPage(this);
616 for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
617 m_mimeTypesWithCustomContentProviders.add(mimeType);
620 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
621 if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
622 m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
624 m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
626 if (parameters.viewScaleFactor != 1)
627 scaleView(parameters.viewScaleFactor);
629 m_page->addLayoutMilestones(parameters.observedLayoutMilestones);
632 m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
633 setSmartInsertDeleteEnabled(parameters.smartInsertDeleteEnabled);
634 WebCore::setAdditionalSupportedImageTypes(parameters.additionalSupportedImageTypes);
637 #if ENABLE(SERVICE_WORKER)
638 if (parameters.hasRegisteredServiceWorkers)
639 ServiceWorkerProvider::singleton().setMayHaveRegisteredServiceWorkers();
642 m_needsFontAttributes = parameters.needsFontAttributes;
645 if (!parameters.iceCandidateFilteringEnabled)
646 disableICECandidateFiltering();
648 if (parameters.enumeratingAllNetworkInterfacesEnabled)
649 enableEnumeratingAllNetworkInterfaces();
653 for (const auto& iterator : parameters.urlSchemeHandlers)
654 registerURLSchemeHandler(iterator.value, iterator.key);
656 m_userContentController->addUserContentWorlds(parameters.userContentWorlds);
657 m_userContentController->addUserScripts(WTFMove(parameters.userScripts), InjectUserScriptImmediately::No);
658 m_userContentController->addUserStyleSheets(parameters.userStyleSheets);
659 m_userContentController->addUserScriptMessageHandlers(parameters.messageHandlers);
660 #if ENABLE(CONTENT_EXTENSIONS)
661 m_userContentController->addContentRuleLists(WTFMove(parameters.contentRuleLists));
664 #if PLATFORM(IOS_FAMILY)
665 setViewportConfigurationViewLayoutSize(parameters.viewportConfigurationViewLayoutSize, parameters.viewportConfigurationLayoutSizeScaleFactor, parameters.viewportConfigurationMinimumEffectiveDeviceWidth);
666 setMaximumUnobscuredSize(parameters.maximumUnobscuredSize);
669 #if USE(AUDIO_SESSION)
670 PlatformMediaSessionManager::setShouldDeactivateAudioSession(true);
673 setBackgroundColor(parameters.backgroundColor);
677 void WebPage::disableICECandidateFiltering()
679 m_page->disableICECandidateFiltering();
682 void WebPage::enableICECandidateFiltering()
684 m_page->enableICECandidateFiltering();
688 void WebPage::disableEnumeratingAllNetworkInterfaces()
690 m_page->libWebRTCProvider().disableEnumeratingAllNetworkInterfaces();
693 void WebPage::enableEnumeratingAllNetworkInterfaces()
695 m_page->libWebRTCProvider().enableEnumeratingAllNetworkInterfaces();
700 void WebPage::stopAllMediaPlayback()
702 m_page->stopAllMediaPlayback();
705 void WebPage::suspendAllMediaPlayback()
707 m_page->suspendAllMediaPlayback();
710 void WebPage::resumeAllMediaPlayback()
712 m_page->resumeAllMediaPlayback();
715 void WebPage::suspendAllMediaBuffering()
717 m_page->suspendAllMediaBuffering();
720 void WebPage::resumeAllMediaBuffering()
722 m_page->resumeAllMediaBuffering();
726 void WebPage::reinitializeWebPage(WebPageCreationParameters&& parameters)
728 ASSERT(m_drawingArea);
730 setSize(parameters.viewSize);
732 // If the UIProcess created a new DrawingArea, then we need to do the same.
733 if (m_drawingArea->identifier() != parameters.drawingAreaIdentifier) {
734 auto oldDrawingArea = std::exchange(m_drawingArea, nullptr);
735 oldDrawingArea->removeMessageReceiverIfNeeded();
737 m_drawingArea = DrawingArea::create(*this, parameters);
738 m_drawingArea->setPaintingEnabled(false);
739 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
740 m_drawingArea->updatePreferences(parameters.store);
741 m_drawingArea->setPaintingEnabled(true);
743 m_drawingArea->adoptLayersFromDrawingArea(*oldDrawingArea);
745 unfreezeLayerTree(LayerTreeFreezeReason::PageSuspended);
748 setViewLayoutSize(parameters.viewLayoutSize);
750 if (m_activityState != parameters.activityState)
751 setActivityState(parameters.activityState, ActivityStateChangeAsynchronous, Vector<CallbackID>());
752 if (m_layerHostingMode != parameters.layerHostingMode)
753 setLayerHostingMode(parameters.layerHostingMode);
755 platformReinitialize();
758 void WebPage::updateThrottleState()
760 bool isActive = m_activityState.containsAny({ ActivityState::IsLoading, ActivityState::IsAudible, ActivityState::IsCapturingMedia, ActivityState::WindowIsActive });
761 bool isVisuallyIdle = m_activityState.contains(ActivityState::IsVisuallyIdle);
762 bool pageSuppressed = m_processSuppressionEnabled && !isActive && isVisuallyIdle;
764 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
765 if (!pageSuppressed) {
766 // App nap must be manually enabled when not running the NSApplication run loop.
767 static std::once_flag onceKey;
768 std::call_once(onceKey, [] {
769 __CFRunLoopSetOptionsReason(__CFRunLoopOptionsEnableAppNap, CFSTR("Finished checkin as application - enable app nap"));
773 // The UserActivity keeps the processes runnable. So if the page should be suppressed, stop the activity.
774 // If the page should not be supressed, start it.
776 m_userActivityHysteresis.stop();
778 m_userActivityHysteresis.start();
781 void WebPage::updateUserActivity()
783 if (m_userActivityHysteresis.state() == PAL::HysteresisState::Started)
784 m_userActivity.start();
786 m_userActivity.stop();
795 m_sandboxExtensionTracker.invalidate();
797 for (auto* pluginView : m_pluginViews)
798 pluginView->webPageDestroyed();
800 #if !PLATFORM(IOS_FAMILY)
802 m_headerBanner->detachFromPage();
804 m_footerBanner->detachFromPage();
805 #endif // !PLATFORM(IOS_FAMILY)
808 webPageCounter.decrement();
811 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
812 if (m_playbackSessionManager)
813 m_playbackSessionManager->invalidate();
815 if (m_videoFullscreenManager)
816 m_videoFullscreenManager->invalidate();
820 IPC::Connection* WebPage::messageSenderConnection() const
822 return WebProcess::singleton().parentProcessConnection();
825 uint64_t WebPage::messageSenderDestinationID() const
830 #if ENABLE(CONTEXT_MENUS)
831 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>&& contextMenuClient)
833 if (!contextMenuClient) {
834 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
838 m_contextMenuClient = WTFMove(contextMenuClient);
842 void WebPage::setInjectedBundleEditorClient(std::unique_ptr<API::InjectedBundle::EditorClient>&& editorClient)
845 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
849 m_editorClient = WTFMove(editorClient);
852 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>&& formClient)
855 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
859 m_formClient = WTFMove(formClient);
862 void WebPage::setInjectedBundlePageLoaderClient(std::unique_ptr<API::InjectedBundle::PageLoaderClient>&& loaderClient)
865 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
869 m_loaderClient = WTFMove(loaderClient);
871 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
872 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
873 // for backwards compatibility.
874 if (auto milestones = m_loaderClient->layoutMilestones())
875 listenForLayoutMilestones(milestones);
878 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
880 m_policyClient.initialize(client);
883 void WebPage::setInjectedBundleResourceLoadClient(std::unique_ptr<API::InjectedBundle::ResourceLoadClient>&& client)
885 if (!m_resourceLoadClient)
886 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
888 m_resourceLoadClient = WTFMove(client);
891 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>&& uiClient)
894 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
898 m_uiClient = WTFMove(uiClient);
901 #if ENABLE(FULLSCREEN_API)
902 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
904 m_fullScreenClient.initialize(client);
908 #if ENABLE(NETSCAPE_PLUGIN_API)
910 constexpr int smallPluginDimensionThreshold = 5;
912 static bool pluginIsSmall(WebCore::HTMLPlugInElement& pluginElement)
914 auto* renderer = pluginElement.renderer();
915 if (!is<RenderEmbeddedObject>(*renderer))
918 auto& box = downcast<RenderBox>(*renderer);
919 return box.contentWidth() <= smallPluginDimensionThreshold && box.contentHeight() <= smallPluginDimensionThreshold;
922 RefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
924 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
925 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
927 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
928 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
929 unsigned pluginArea = 0;
930 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
932 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
935 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
937 uint64_t pluginProcessToken;
938 uint32_t pluginLoadPolicy;
939 String unavailabilityDescription;
941 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)))
944 PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
945 bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
947 if (isUnsupported || isBlockedPlugin || !pluginProcessToken) {
948 #if ENABLE(PDFKIT_PLUGIN)
949 String path = parameters.url.path();
950 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWithIgnoringASCIICase(".pdf") || path.endsWithIgnoringASCIICase(".ps")))))
951 return PDFPlugin::create(*frame);
956 pluginElement->setReplacement(RenderEmbeddedObject::UnsupportedPlugin, unavailabilityDescription);
960 if (isBlockedPlugin) {
961 bool isReplacementObscured = pluginElement->setReplacement(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
962 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, isReplacementObscured));
966 if (!pluginProcessToken)
969 if (m_page->settings().blockingOfSmallPluginsEnabled() && pluginIsSmall(*pluginElement)) {
970 RELEASE_LOG(Plugins, "Blocking a plugin because it is too small");
971 pluginElement->setReplacement(RenderEmbeddedObject::PluginTooSmall, pluginTooSmallText());
975 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
976 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
978 #endif // ENABLE(NETSCAPE_PLUGIN_API)
980 #if ENABLE(WEBGL) && !PLATFORM(MAC)
981 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const URL&)
983 return WebGLAllowCreation;
986 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const URL&)
988 return WebGLAllowCreation;
992 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
994 Frame& frame = m_page->focusController().focusedOrMainFrame();
998 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
999 if (!pluginView->getSelectionString().isNull()) {
1000 result.selectionIsNone = false;
1001 result.selectionIsRange = true;
1002 result.isInPlugin = true;
1007 const VisibleSelection& selection = frame.selection().selection();
1008 const Editor& editor = frame.editor();
1010 result.selectionIsNone = selection.isNone();
1011 result.selectionIsRange = selection.isRange();
1012 result.isContentEditable = selection.isContentEditable();
1013 result.isContentRichlyEditable = selection.isContentRichlyEditable();
1014 result.isInPasswordField = selection.isInPasswordField();
1015 result.hasComposition = editor.hasComposition();
1016 result.shouldIgnoreSelectionChanges = editor.ignoreSelectionChanges();
1018 if (auto* document = frame.document())
1019 result.originIdentifierForPasteboard = document->originIdentifierForPasteboard();
1021 bool canIncludePostLayoutData = frame.view() && !frame.view()->needsLayout();
1022 if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && canIncludePostLayoutData) {
1023 auto& postLayoutData = result.postLayoutData();
1024 postLayoutData.canCut = editor.canCut();
1025 postLayoutData.canCopy = editor.canCopy();
1026 postLayoutData.canPaste = editor.canPaste();
1028 if (m_needsFontAttributes)
1029 postLayoutData.fontAttributes = editor.fontAttributesAtSelectionStart();
1032 if (result.isContentEditable && !selection.isNone()) {
1033 if (auto editingStyle = EditingStyle::styleAtSelectionStart(selection)) {
1034 if (editingStyle->hasStyle(CSSPropertyFontWeight, "bold"))
1035 postLayoutData.typingAttributes |= AttributeBold;
1037 if (editingStyle->hasStyle(CSSPropertyFontStyle, "italic") || editingStyle->hasStyle(CSSPropertyFontStyle, "oblique"))
1038 postLayoutData.typingAttributes |= AttributeItalics;
1040 if (editingStyle->hasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline"))
1041 postLayoutData.typingAttributes |= AttributeUnderline;
1043 if (auto* styleProperties = editingStyle->style()) {
1044 bool isLeftToRight = styleProperties->propertyAsValueID(CSSPropertyDirection) == CSSValueLtr;
1045 switch (styleProperties->propertyAsValueID(CSSPropertyTextAlign)) {
1047 case CSSValueWebkitRight:
1048 postLayoutData.textAlignment = RightAlignment;
1051 case CSSValueWebkitLeft:
1052 postLayoutData.textAlignment = LeftAlignment;
1054 case CSSValueCenter:
1055 case CSSValueWebkitCenter:
1056 postLayoutData.textAlignment = CenterAlignment;
1058 case CSSValueJustify:
1059 postLayoutData.textAlignment = JustifiedAlignment;
1062 postLayoutData.textAlignment = isLeftToRight ? LeftAlignment : RightAlignment;
1065 postLayoutData.textAlignment = isLeftToRight ? RightAlignment : LeftAlignment;
1070 if (auto textColor = styleProperties->propertyAsColor(CSSPropertyColor))
1071 postLayoutData.textColor = *textColor;
1075 if (auto* enclosingListElement = enclosingList(selection.start().containerNode())) {
1076 if (is<HTMLUListElement>(*enclosingListElement))
1077 postLayoutData.enclosingListType = UnorderedList;
1078 else if (is<HTMLOListElement>(*enclosingListElement))
1079 postLayoutData.enclosingListType = OrderedList;
1081 ASSERT_NOT_REACHED();
1084 postLayoutData.baseWritingDirection = editor.baseWritingDirectionForSelectionStart();
1089 platformEditorState(frame, result, shouldIncludePostLayoutData);
1091 m_lastEditorStateWasContentEditable = result.isContentEditable ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1096 void WebPage::changeFontAttributes(WebCore::FontAttributeChanges&& changes)
1098 auto& frame = m_page->focusController().focusedOrMainFrame();
1099 if (frame.selection().selection().isContentEditable())
1100 frame.editor().applyStyleToSelection(changes.createEditingStyle(), changes.editAction(), Editor::ColorFilterMode::InvertColor);
1103 void WebPage::changeFont(WebCore::FontChanges&& changes)
1105 auto& frame = m_page->focusController().focusedOrMainFrame();
1106 if (frame.selection().selection().isContentEditable())
1107 frame.editor().applyStyleToSelection(changes.createEditingStyle(), EditAction::SetFont, Editor::ColorFilterMode::InvertColor);
1110 void WebPage::executeEditCommandWithCallback(const String& commandName, const String& argument, CallbackID callbackID)
1112 executeEditCommand(commandName, argument);
1113 send(Messages::WebPageProxy::VoidCallback(callbackID));
1116 void WebPage::updateEditorStateAfterLayoutIfEditabilityChanged()
1118 // FIXME: We should update EditorStateIsContentEditable to track whether the state is richly
1119 // editable or plainttext-only.
1120 if (m_lastEditorStateWasContentEditable == EditorStateIsContentEditable::Unset)
1123 Frame& frame = m_page->focusController().focusedOrMainFrame();
1124 EditorStateIsContentEditable editorStateIsContentEditable = frame.selection().selection().isContentEditable() ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1125 if (m_lastEditorStateWasContentEditable != editorStateIsContentEditable)
1126 sendPartialEditorStateAndSchedulePostLayoutUpdate();
1129 String WebPage::renderTreeExternalRepresentation() const
1131 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
1134 String WebPage::renderTreeExternalRepresentationForPrinting() const
1136 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
1139 uint64_t WebPage::renderTreeSize() const
1143 return m_page->renderTreeSize();
1146 void WebPage::setTracksRepaints(bool trackRepaints)
1148 if (FrameView* view = mainFrameView())
1149 view->setTracksRepaints(trackRepaints);
1152 bool WebPage::isTrackingRepaints() const
1154 if (FrameView* view = mainFrameView())
1155 return view->isTrackingRepaints();
1160 void WebPage::resetTrackedRepaints()
1162 if (FrameView* view = mainFrameView())
1163 view->resetTrackedRepaints();
1166 Ref<API::Array> WebPage::trackedRepaintRects()
1168 FrameView* view = mainFrameView();
1170 return API::Array::create();
1172 Vector<RefPtr<API::Object>> repaintRects;
1173 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
1175 for (const auto& repaintRect : view->trackedRepaintRects())
1176 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
1178 return API::Array::create(WTFMove(repaintRects));
1181 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
1183 if (!is<PluginDocument>(frame.document()))
1186 auto& pluginDocument = downcast<PluginDocument>(*frame.document());
1187 if (pluginDocument.focusedElement() != pluginDocument.pluginElement())
1190 return pluginViewForFrame(&frame);
1193 PluginView* WebPage::pluginViewForFrame(Frame* frame)
1195 if (!frame || !is<PluginDocument>(frame->document()))
1198 auto& document = downcast<PluginDocument>(*frame->document());
1199 return static_cast<PluginView*>(document.pluginWidget());
1202 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
1204 Frame& frame = m_page->focusController().focusedOrMainFrame();
1206 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
1207 pluginView->handleEditingCommand(commandName, argument);
1211 frame.editor().command(commandName).execute(argument);
1214 void WebPage::setEditable(bool editable)
1216 m_page->setEditable(editable);
1217 m_page->setTabKeyCyclesThroughElements(!editable);
1218 Frame& frame = m_page->focusController().focusedOrMainFrame();
1220 frame.editor().applyEditingStyleToBodyElement();
1221 // If the page is made editable and the selection is empty, set it to something.
1222 if (frame.selection().isNone())
1223 frame.selection().setSelectionFromNone();
1227 void WebPage::increaseListLevel()
1229 m_page->focusController().focusedOrMainFrame().editor().increaseSelectionListLevel();
1232 void WebPage::decreaseListLevel()
1234 m_page->focusController().focusedOrMainFrame().editor().decreaseSelectionListLevel();
1237 void WebPage::changeListType()
1239 m_page->focusController().focusedOrMainFrame().editor().changeSelectionListType();
1242 void WebPage::setBaseWritingDirection(WritingDirection direction)
1244 m_page->focusController().focusedOrMainFrame().editor().setBaseWritingDirection(direction);
1247 bool WebPage::isEditingCommandEnabled(const String& commandName)
1249 Frame& frame = m_page->focusController().focusedOrMainFrame();
1251 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1252 return pluginView->isEditingCommandEnabled(commandName);
1254 Editor::Command command = frame.editor().command(commandName);
1255 return command.isSupported() && command.isEnabled();
1258 void WebPage::clearMainFrameName()
1260 if (Frame* frame = mainFrame())
1261 frame->tree().clearName();
1264 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
1266 m_drawingArea->setRootCompositingLayer(layer);
1269 void WebPage::exitAcceleratedCompositingMode()
1271 m_drawingArea->setRootCompositingLayer(nullptr);
1274 void WebPage::close()
1279 #if ENABLE(RESOURCE_LOAD_STATISTICS)
1280 WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::ClearPageSpecificDataForResourceLoadStatistics(sessionID(), m_pageID), 0);
1285 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1286 if (!mainWebFrame()->url().isEmpty())
1287 reportUsedFeatures();
1289 if (WebProcess::singleton().injectedBundle())
1290 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1293 m_inspector->disconnectFromPage();
1294 m_inspector = nullptr;
1297 m_page->inspectorController().disconnectAllFrontends();
1299 #if ENABLE(FULLSCREEN_API)
1300 m_fullScreenManager = nullptr;
1303 if (m_activePopupMenu) {
1304 m_activePopupMenu->disconnectFromPage();
1305 m_activePopupMenu = nullptr;
1308 if (m_activeOpenPanelResultListener) {
1309 m_activeOpenPanelResultListener->disconnectFromPage();
1310 m_activeOpenPanelResultListener = nullptr;
1313 #if ENABLE(INPUT_TYPE_COLOR)
1314 if (m_activeColorChooser) {
1315 m_activeColorChooser->disconnectFromPage();
1316 m_activeColorChooser = nullptr;
1321 if (m_printOperation) {
1322 m_printOperation->disconnectFromPage();
1323 m_printOperation = nullptr;
1327 #if ENABLE(VIDEO) && USE(GSTREAMER)
1328 if (m_installMediaPluginsCallback) {
1329 m_installMediaPluginsCallback->invalidate();
1330 m_installMediaPluginsCallback = nullptr;
1334 m_sandboxExtensionTracker.invalidate();
1336 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1337 m_determinePrimarySnapshottedPlugInTimer.stop();
1340 #if ENABLE(CONTEXT_MENUS)
1341 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1343 m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
1344 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1345 m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
1346 m_policyClient.initialize(0);
1347 m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
1348 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1349 #if ENABLE(FULLSCREEN_API)
1350 m_fullScreenClient.initialize(0);
1353 m_printContext = nullptr;
1354 m_mainFrame->coreFrame()->loader().detachFromParent();
1355 m_drawingArea = nullptr;
1357 DeferredPageDestructor::createDeferredPageDestructor(WTFMove(m_page), this);
1359 bool isRunningModal = m_isRunningModal;
1360 m_isRunningModal = false;
1362 auto& webProcess = WebProcess::singleton();
1364 if (m_remoteObjectRegistry)
1365 m_remoteObjectRegistry->close();
1367 #if ENABLE(ASYNC_SCROLLING)
1368 if (m_useAsyncScrolling)
1369 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
1371 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
1372 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
1373 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
1374 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
1375 webProcess.removeMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID);
1376 #if ENABLE(FULLSCREEN_API)
1377 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
1379 #if PLATFORM(COCOA) || PLATFORM(GTK)
1380 m_viewGestureGeometryCollector = nullptr;
1383 // The WebPage can be destroyed by this call.
1384 WebProcess::singleton().removeWebPage(m_pageID);
1386 WebProcess::singleton().updateActivePages();
1389 RunLoop::main().stop();
1392 void WebPage::tryClose()
1394 SendStopResponsivenessTimer stopper;
1396 if (!corePage()->userInputBridge().tryClosePage())
1399 send(Messages::WebPageProxy::ClosePage(true));
1402 void WebPage::sendClose()
1404 send(Messages::WebPageProxy::ClosePage(false));
1407 void WebPage::suspendForProcessSwap()
1409 auto failedToSuspend = [this, protectedThis = makeRef(*this)] {
1410 send(Messages::WebPageProxy::DidFailToSuspendAfterProcessSwap());
1413 auto* currentHistoryItem = m_mainFrame->coreFrame()->loader().history().currentItem();
1414 if (!currentHistoryItem) {
1419 if (!PageCache::singleton().addIfCacheable(*currentHistoryItem, corePage())) {
1424 send(Messages::WebPageProxy::DidSuspendAfterProcessSwap());
1427 void WebPage::loadURLInFrame(URL&& url, uint64_t frameID)
1429 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1433 frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(url), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1436 void WebPage::loadDataInFrame(IPC::DataReference&& data, String&& MIMEType, String&& encodingName, URL&& baseURL, uint64_t frameID)
1438 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1442 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
1443 ResourceResponse response(baseURL, MIMEType, sharedBuffer->size(), encodingName);
1444 SubstituteData substituteData(WTFMove(sharedBuffer), baseURL, WTFMove(response), SubstituteData::SessionHistoryVisibility::Hidden);
1445 frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(baseURL), ShouldOpenExternalURLsPolicy::ShouldNotAllow, WTFMove(substituteData)));
1448 #if !PLATFORM(COCOA)
1449 void WebPage::platformDidReceiveLoadParameters(const LoadParameters& loadParameters)
1454 void WebPage::loadRequest(LoadParameters&& loadParameters)
1456 SendStopResponsivenessTimer stopper;
1458 m_pendingNavigationID = loadParameters.navigationID;
1459 m_pendingWebsitePolicies = WTFMove(loadParameters.websitePolicies);
1461 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), WTFMove(loadParameters.sandboxExtensionHandle));
1463 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1464 // to all the client to set up any needed state.
1465 m_loaderClient->willLoadURLRequest(*this, loadParameters.request, WebProcess::singleton().transformHandlesToObjects(loadParameters.userData.object()).get());
1467 platformDidReceiveLoadParameters(loadParameters);
1469 // Initate the load in WebCore.
1470 FrameLoadRequest frameLoadRequest { *m_mainFrame->coreFrame(), loadParameters.request, ShouldOpenExternalURLsPolicy::ShouldNotAllow };
1471 ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(loadParameters.shouldOpenExternalURLsPolicy);
1472 frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1473 frameLoadRequest.setShouldTreatAsContinuingLoad(loadParameters.shouldTreatAsContinuingLoad);
1474 frameLoadRequest.setLockHistory(loadParameters.lockHistory);
1475 frameLoadRequest.setlockBackForwardList(loadParameters.lockBackForwardList);
1476 frameLoadRequest.setClientRedirectSourceForHistory(loadParameters.clientRedirectSourceForHistory);
1477 frameLoadRequest.setIsRequestFromClientOrUserInput();
1479 corePage()->userInputBridge().loadRequest(WTFMove(frameLoadRequest));
1481 ASSERT(!m_pendingNavigationID);
1482 ASSERT(!m_pendingWebsitePolicies);
1485 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)
1487 SendStopResponsivenessTimer stopper;
1489 m_pendingNavigationID = navigationID;
1490 m_pendingWebsitePolicies = WTFMove(websitePolicies);
1492 ResourceRequest request(baseURL);
1493 ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1494 SubstituteData substituteData(WTFMove(sharedBuffer), unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1496 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1497 // to all the client to set up any needed state.
1498 m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1500 // Initate the load in WebCore.
1501 FrameLoadRequest frameLoadRequest(*m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData);
1502 frameLoadRequest.setShouldTreatAsContinuingLoad(shouldTreatAsContinuingLoad);
1503 m_mainFrame->coreFrame()->loader().load(WTFMove(frameLoadRequest));
1506 void WebPage::loadData(LoadParameters&& loadParameters)
1508 platformDidReceiveLoadParameters(loadParameters);
1510 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1511 URL baseURL = loadParameters.baseURLString.isEmpty() ? WTF::blankURL() : URL(URL(), loadParameters.baseURLString);
1512 loadDataImpl(loadParameters.navigationID, loadParameters.shouldTreatAsContinuingLoad, WTFMove(loadParameters.websitePolicies), WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, URL(), loadParameters.userData);
1515 void WebPage::loadAlternateHTML(LoadParameters&& loadParameters)
1517 platformDidReceiveLoadParameters(loadParameters);
1519 URL baseURL = loadParameters.baseURLString.isEmpty() ? WTF::blankURL() : URL(URL(), loadParameters.baseURLString);
1520 URL unreachableURL = loadParameters.unreachableURLString.isEmpty() ? URL() : URL(URL(), loadParameters.unreachableURLString);
1521 URL provisionalLoadErrorURL = loadParameters.provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), loadParameters.provisionalLoadErrorURLString);
1522 auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1523 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1524 loadDataImpl(loadParameters.navigationID, loadParameters.shouldTreatAsContinuingLoad, WTFMove(loadParameters.websitePolicies), WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, unreachableURL, loadParameters.userData);
1525 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1528 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1530 Frame* mainFrame = m_mainFrame->coreFrame();
1531 Document* mainFrameDocument = mainFrame->document();
1532 if (!mainFrameDocument)
1535 const int singleClick = 1;
1536 // FIXME: Set modifier keys.
1537 // FIXME: This should probably set IsSimulated::Yes.
1538 auto mouseEvent = MouseEvent::create(eventNames().clickEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes, Event::IsComposed::Yes,
1539 MonotonicTime::now(), nullptr, singleClick, screenPoint, documentPoint, { }, { }, 0, 0, nullptr, 0, WebCore::NoTap, nullptr);
1541 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.ptr(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1544 void WebPage::stopLoadingFrame(uint64_t frameID)
1546 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1550 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1553 void WebPage::stopLoading()
1555 SendStopResponsivenessTimer stopper;
1557 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1560 bool WebPage::defersLoading() const
1562 return m_page->defersLoading();
1565 void WebPage::setDefersLoading(bool defersLoading)
1567 m_page->setDefersLoading(defersLoading);
1570 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, SandboxExtension::Handle&& sandboxExtensionHandle)
1572 SendStopResponsivenessTimer stopper;
1574 ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1575 m_pendingNavigationID = navigationID;
1577 m_sandboxExtensionTracker.beginReload(m_mainFrame.get(), WTFMove(sandboxExtensionHandle));
1578 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1580 if (m_pendingNavigationID) {
1581 // This can happen if FrameLoader::reload() returns early because the document URL is empty.
1582 // The reload does nothing so we need to reset the pending navigation. See webkit.org/b/153210.
1583 m_pendingNavigationID = 0;
1587 void WebPage::goToBackForwardItem(uint64_t navigationID, const BackForwardItemIdentifier& backForwardItemID, FrameLoadType backForwardType, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad, Optional<WebsitePoliciesData>&& websitePolicies)
1589 SendStopResponsivenessTimer stopper;
1591 ASSERT(isBackForwardLoadType(backForwardType));
1593 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1598 LOG(Loading, "In WebProcess pid %i, WebPage %" PRIu64 " is navigating to back/forward URL %s", getCurrentProcessID(), m_pageID, item->url().string().utf8().data());
1600 ASSERT(!m_pendingNavigationID);
1601 m_pendingNavigationID = navigationID;
1602 m_pendingWebsitePolicies = WTFMove(websitePolicies);
1604 m_page->goToItem(*item, backForwardType, shouldTreatAsContinuingLoad);
1607 void WebPage::tryRestoreScrollPosition()
1609 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1612 void WebPage::layoutIfNeeded()
1614 if (m_mainFrame->coreFrame()->view())
1615 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1618 WebPage* WebPage::fromCorePage(Page* page)
1620 return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1623 void WebPage::setSize(const WebCore::IntSize& viewSize)
1625 if (m_viewSize == viewSize)
1628 m_viewSize = viewSize;
1629 FrameView* view = m_page->mainFrame().view();
1630 view->resize(viewSize);
1631 m_drawingArea->setNeedsDisplay();
1633 #if USE(COORDINATED_GRAPHICS)
1634 if (view->useFixedLayout())
1635 sendViewportAttributesChanged(m_page->viewportArguments());
1639 #if USE(COORDINATED_GRAPHICS)
1640 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1642 FrameView* view = m_page->mainFrame().view();
1643 ASSERT(view && view->useFixedLayout());
1645 // Viewport properties have no impact on zero sized fixed viewports.
1646 if (m_viewSize.isEmpty())
1649 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1650 Settings& settings = m_page->settings();
1652 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1654 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1655 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1656 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1658 ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1660 // If no layout was done yet set contentFixedOrigin to (0,0).
1661 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1663 // Put the width and height to the viewport width and height. In css units however.
1664 // Use FloatSize to avoid truncated values during scale.
1665 FloatSize contentFixedSize = m_viewSize;
1667 #if ENABLE(CSS_DEVICE_ADAPTATION)
1668 // CSS viewport descriptors might be applied to already affected viewport size
1669 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1670 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1673 contentFixedSize.scale(1 / attr.initialScale);
1674 view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1676 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1678 // This also takes care of the relayout.
1679 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1681 #if USE(COORDINATED_GRAPHICS)
1682 m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1684 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1689 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1691 FrameView* frameView = m_page->mainFrame().view();
1693 ScrollPosition scrollPosition = frameView->scrollPosition();
1694 ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1696 // If the current scroll position in a direction is the max scroll position
1697 // we don't want to scroll at all.
1698 IntSize newScrollOffset;
1699 if (scrollPosition.x() < maximumScrollPosition.x())
1700 newScrollOffset.setWidth(scrollOffset.width());
1701 if (scrollPosition.y() < maximumScrollPosition.y())
1702 newScrollOffset.setHeight(scrollOffset.height());
1704 if (newScrollOffset.isZero())
1707 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1710 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1713 FrameView* mainFrameView = m_page->mainFrame().view();
1714 LocalDefaultSystemAppearance localAppearance(mainFrameView ? mainFrameView->useDarkAppearance() : false);
1717 GraphicsContextStateSaver stateSaver(graphicsContext);
1718 graphicsContext.clip(rect);
1720 m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1723 double WebPage::textZoomFactor() const
1725 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1726 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1727 if (pluginView->handlesPageScaleFactor())
1728 return pluginView->pageScaleFactor();
1729 return pageScaleFactor();
1732 Frame* frame = m_mainFrame->coreFrame();
1735 return frame->textZoomFactor();
1738 void WebPage::setTextZoomFactor(double zoomFactor)
1740 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1741 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1742 if (pluginView->handlesPageScaleFactor())
1743 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1745 scalePage(zoomFactor, IntPoint());
1749 Frame* frame = m_mainFrame->coreFrame();
1752 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1755 double WebPage::pageZoomFactor() const
1757 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1758 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1759 if (pluginView->handlesPageScaleFactor())
1760 return pluginView->pageScaleFactor();
1761 return pageScaleFactor();
1764 Frame* frame = m_mainFrame->coreFrame();
1767 return frame->pageZoomFactor();
1770 void WebPage::setPageZoomFactor(double zoomFactor)
1772 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1773 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1774 if (pluginView->handlesPageScaleFactor())
1775 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1777 scalePage(zoomFactor, IntPoint());
1781 Frame* frame = m_mainFrame->coreFrame();
1784 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1787 static void dumpHistoryItem(HistoryItem& item, size_t indent, bool isCurrentItem, StringBuilder& stringBuilder, const String& directoryName)
1790 stringBuilder.appendLiteral("curr-> ");
1792 for (size_t i = 0; i < indent; ++i)
1793 stringBuilder.append(' ');
1796 auto url = item.url();
1797 if (url.protocolIs("file")) {
1798 size_t start = url.string().find(directoryName);
1799 if (start == WTF::notFound)
1802 start += directoryName.length();
1803 stringBuilder.appendLiteral("(file test):");
1804 stringBuilder.append(url.string().substring(start));
1806 stringBuilder.append(url);
1808 auto& target = item.target();
1809 if (target.length()) {
1810 stringBuilder.appendLiteral(" (in frame \"");
1811 stringBuilder.append(target);
1812 stringBuilder.appendLiteral("\")");
1815 if (item.isTargetItem())
1816 stringBuilder.appendLiteral(" **nav target**");
1818 stringBuilder.append('\n');
1820 Vector<Ref<HistoryItem>> children;
1821 children.reserveInitialCapacity(item.children().size());
1822 for (auto& child : item.children())
1823 children.uncheckedAppend(child.copyRef());
1824 std::stable_sort(children.begin(), children.end(), [] (auto& a, auto& b) {
1825 return codePointCompare(a->target(), b->target()) < 0;
1827 for (auto& child : children)
1828 dumpHistoryItem(child, indent + 4, false, stringBuilder, directoryName);
1831 String WebPage::dumpHistoryForTesting(const String& directory)
1836 auto& list = m_page->backForward();
1838 StringBuilder builder;
1839 int begin = -list.backCount();
1840 if (list.itemAtIndex(begin)->url() == WTF::blankURL())
1842 for (int i = begin; i <= static_cast<int>(list.forwardCount()); ++i)
1843 dumpHistoryItem(*list.itemAtIndex(i), 8, !i, builder, directory);
1844 return builder.toString();
1847 void WebPage::clearHistory()
1852 static_cast<WebBackForwardListProxy&>(m_page->backForward().client()).clear();
1855 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1857 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1858 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1859 if (pluginView->handlesPageScaleFactor())
1860 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1862 scalePage(pageZoomFactor, IntPoint());
1866 Frame* frame = m_mainFrame->coreFrame();
1869 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1872 void WebPage::windowScreenDidChange(uint32_t displayID)
1874 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1877 void WebPage::scalePage(double scale, const IntPoint& origin)
1879 double totalScale = scale * viewScaleFactor();
1880 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1882 #if PLATFORM(IOS_FAMILY)
1883 if (willChangeScaleFactor) {
1884 if (!m_inDynamicSizeUpdate)
1885 m_dynamicSizeUpdateHistory.clear();
1886 m_scaleWasSetByUIProcess = false;
1889 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1890 if (pluginView && pluginView->handlesPageScaleFactor()) {
1891 // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1892 // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1893 if (m_page->pageScaleFactor() != 1) {
1894 m_page->setPageScaleFactor(1, origin);
1895 for (auto* pluginView : m_pluginViews)
1896 pluginView->pageScaleFactorDidChange();
1899 pluginView->setPageScaleFactor(totalScale, origin);
1903 m_page->setPageScaleFactor(totalScale, origin);
1905 // We can't early return before setPageScaleFactor because the origin might be different.
1906 if (!willChangeScaleFactor)
1909 for (auto* pluginView : m_pluginViews)
1910 pluginView->pageScaleFactorDidChange();
1912 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1913 m_drawingArea->deviceOrPageScaleFactorChanged();
1916 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1919 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1921 double totalScale = scale * viewScaleFactor();
1922 if (totalScale == totalScaleFactor())
1925 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1926 double scaleRatio = scale / pageScaleFactor();
1927 scrollPositionAtNewScale.scale(scaleRatio);
1928 scalePage(scale, scrollPositionAtNewScale);
1931 double WebPage::totalScaleFactor() const
1933 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1934 if (pluginView && pluginView->handlesPageScaleFactor())
1935 return pluginView->pageScaleFactor();
1937 return m_page->pageScaleFactor();
1940 double WebPage::pageScaleFactor() const
1942 return totalScaleFactor() / viewScaleFactor();
1945 double WebPage::viewScaleFactor() const
1947 return m_page->viewScaleFactor();
1950 void WebPage::scaleView(double scale)
1952 if (viewScaleFactor() == scale)
1955 float pageScale = pageScaleFactor();
1957 IntPoint scrollPositionAtNewScale;
1958 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1959 double scaleRatio = scale / viewScaleFactor();
1960 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1961 scrollPositionAtNewScale.scale(scaleRatio);
1964 m_page->setViewScaleFactor(scale);
1965 scalePage(pageScale, scrollPositionAtNewScale);
1968 void WebPage::setDeviceScaleFactor(float scaleFactor)
1970 if (scaleFactor == m_page->deviceScaleFactor())
1973 m_page->setDeviceScaleFactor(scaleFactor);
1975 // Tell all our plug-in views that the device scale factor changed.
1977 for (auto* pluginView : m_pluginViews)
1978 pluginView->setDeviceScaleFactor(scaleFactor);
1980 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1983 if (findController().isShowingOverlay()) {
1984 // We must have updated layout to get the selection rects right.
1986 findController().deviceScaleFactorDidChange();
1989 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1990 m_drawingArea->deviceOrPageScaleFactorChanged();
1994 float WebPage::deviceScaleFactor() const
1996 return m_page->deviceScaleFactor();
1999 void WebPage::accessibilitySettingsDidChange()
2001 m_page->accessibilitySettingsDidChange();
2004 #if ENABLE(ACCESSIBILITY_EVENTS)
2005 void WebPage::updateAccessibilityEventsEnabled(bool enabled)
2007 m_page->settings().setAccessibilityEventsEnabled(enabled);
2011 void WebPage::setUseFixedLayout(bool fixed)
2013 // Do not overwrite current settings if initially setting it to false.
2014 if (m_useFixedLayout == fixed)
2016 m_useFixedLayout = fixed;
2018 #if !PLATFORM(IOS_FAMILY)
2019 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
2022 FrameView* view = mainFrameView();
2026 view->setUseFixedLayout(fixed);
2028 setFixedLayoutSize(IntSize());
2030 send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
2033 bool WebPage::setFixedLayoutSize(const IntSize& size)
2035 FrameView* view = mainFrameView();
2036 if (!view || view->fixedLayoutSize() == size)
2039 LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " setFixedLayoutSize " << size);
2040 view->setFixedLayoutSize(size);
2042 send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
2046 IntSize WebPage::fixedLayoutSize() const
2048 FrameView* view = mainFrameView();
2051 return view->fixedLayoutSize();
2054 void WebPage::disabledAdaptationsDidChange(const OptionSet<DisabledAdaptations>& disabledAdaptations)
2056 #if PLATFORM(IOS_FAMILY)
2057 if (m_viewportConfiguration.setDisabledAdaptations(disabledAdaptations))
2058 viewportConfigurationChanged();
2060 UNUSED_PARAM(disabledAdaptations);
2064 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
2066 #if PLATFORM(IOS_FAMILY)
2067 if (m_viewportConfiguration.setViewportArguments(viewportArguments))
2068 viewportConfigurationChanged();
2071 #if USE(COORDINATED_GRAPHICS)
2072 FrameView* view = m_page->mainFrame().view();
2073 if (view && view->useFixedLayout())
2074 sendViewportAttributesChanged(viewportArguments);
2076 m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
2079 #if !PLATFORM(IOS_FAMILY) && !USE(COORDINATED_GRAPHICS)
2080 UNUSED_PARAM(viewportArguments);
2084 void WebPage::listenForLayoutMilestones(OptionSet<WebCore::LayoutMilestone> milestones)
2088 m_page->addLayoutMilestones(milestones);
2091 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
2093 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
2096 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
2098 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
2101 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
2103 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
2106 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
2108 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
2109 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
2112 void WebPage::setPaginationMode(uint32_t mode)
2114 Pagination pagination = m_page->pagination();
2115 pagination.mode = static_cast<Pagination::Mode>(mode);
2116 m_page->setPagination(pagination);
2119 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
2121 Pagination pagination = m_page->pagination();
2122 pagination.behavesLikeColumns = behavesLikeColumns;
2123 m_page->setPagination(pagination);
2126 void WebPage::setPageLength(double pageLength)
2128 Pagination pagination = m_page->pagination();
2129 pagination.pageLength = pageLength;
2130 m_page->setPagination(pagination);
2133 void WebPage::setGapBetweenPages(double gap)
2135 Pagination pagination = m_page->pagination();
2136 pagination.gap = gap;
2137 m_page->setPagination(pagination);
2140 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
2142 m_page->setPaginationLineGridEnabled(lineGridEnabled);
2145 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
2147 auto& webProcess = WebProcess::singleton();
2148 InjectedBundle* injectedBundle = webProcess.injectedBundle();
2149 if (!injectedBundle)
2152 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
2155 #if !PLATFORM(IOS_FAMILY)
2157 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
2160 m_headerBanner->detachFromPage();
2162 m_headerBanner = pageBanner;
2165 m_headerBanner->addToPage(PageBanner::Header, this);
2168 PageBanner* WebPage::headerPageBanner()
2170 return m_headerBanner.get();
2173 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
2176 m_footerBanner->detachFromPage();
2178 m_footerBanner = pageBanner;
2181 m_footerBanner->addToPage(PageBanner::Footer, this);
2184 PageBanner* WebPage::footerPageBanner()
2186 return m_footerBanner.get();
2189 void WebPage::hidePageBanners()
2192 m_headerBanner->hide();
2194 m_footerBanner->hide();
2197 void WebPage::showPageBanners()
2200 m_headerBanner->showIfHidden();
2202 m_footerBanner->showIfHidden();
2205 void WebPage::setHeaderBannerHeightForTesting(int height)
2207 corePage()->setHeaderHeight(height);
2210 void WebPage::setFooterBannerHeightForTesting(int height)
2212 corePage()->setFooterHeight(height);
2215 #endif // !PLATFORM(IOS_FAMILY)
2217 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
2219 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
2220 snapshotOptions |= SnapshotOptionsShareable;
2222 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
2224 ShareableBitmap::Handle handle;
2226 image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
2228 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
2231 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
2233 IntRect snapshotRect = rect;
2234 IntSize bitmapSize = snapshotRect.size();
2235 if (options & SnapshotOptionsPrinting) {
2236 ASSERT(additionalScaleFactor == 1);
2237 Frame* coreFrame = m_mainFrame->coreFrame();
2240 bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
2242 double scaleFactor = additionalScaleFactor;
2243 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
2244 scaleFactor *= corePage()->deviceScaleFactor();
2245 bitmapSize.scale(scaleFactor);
2248 return snapshotAtSize(rect, bitmapSize, options);
2251 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
2253 IntRect snapshotRect = rect;
2254 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
2255 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
2256 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
2258 if (options & SnapshotOptionsPrinting) {
2259 PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
2263 Color documentBackgroundColor = frameView.documentBackgroundColor();
2264 Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
2265 graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
2267 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2268 double deviceScaleFactor = frame.page()->deviceScaleFactor();
2269 graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
2270 scaleFactor /= deviceScaleFactor;
2273 graphicsContext.scale(scaleFactor);
2274 graphicsContext.translate(-snapshotRect.location());
2276 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
2277 if (options & SnapshotOptionsExcludeSelectionHighlighting)
2278 shouldPaintSelection = FrameView::ExcludeSelection;
2280 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
2281 if (options & SnapshotOptionsInViewCoordinates)
2282 coordinateSpace = FrameView::ViewCoordinates;
2284 frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
2286 if (options & SnapshotOptionsPaintSelectionRectangle) {
2287 FloatRect selectionRectangle = frame.selection().selectionBounds();
2288 graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
2289 graphicsContext.strokeRect(selectionRectangle, 1);
2293 static ShareableBitmap::Configuration snapshotOptionsToBitmapConfiguration(SnapshotOptions options, WebPage& page)
2295 ShareableBitmap::Configuration configuration;
2297 if (options & SnapshotOptionsUseScreenColorSpace)
2298 configuration.colorSpace.cgColorSpace = screenColorSpace(page.corePage()->mainFrame().view());
2300 return configuration;
2303 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2305 Frame* coreFrame = m_mainFrame->coreFrame();
2309 FrameView* frameView = coreFrame->view();
2313 auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2316 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2318 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2324 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2326 Frame* coreFrame = m_mainFrame->coreFrame();
2330 FrameView* frameView = coreFrame->view();
2334 auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2337 auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2338 auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2339 auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2341 CGPDFContextBeginPage(pdfContext.get(), nullptr);
2343 GraphicsContext graphicsContext { pdfContext.get() };
2344 graphicsContext.scale({ 1, -1 });
2345 graphicsContext.translate(0, -bitmapSize.height());
2346 paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2348 CGPDFContextEndPage(pdfContext.get());
2349 CGPDFContextClose(pdfContext.get());
2356 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2358 Frame* coreFrame = m_mainFrame->coreFrame();
2362 FrameView* frameView = coreFrame->view();
2366 if (!node.renderer())
2369 LayoutRect topLevelRect;
2370 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2371 if (snapshotRect.isEmpty())
2374 double scaleFactor = 1;
2375 IntSize snapshotSize = snapshotRect.size();
2376 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2377 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2378 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2379 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2382 auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2385 auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2387 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2388 double deviceScaleFactor = corePage()->deviceScaleFactor();
2389 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2390 scaleFactor /= deviceScaleFactor;
2393 graphicsContext->scale(scaleFactor);
2394 graphicsContext->translate(-snapshotRect.location());
2396 Color savedBackgroundColor = frameView->baseBackgroundColor();
2397 frameView->setBaseBackgroundColor(Color::transparent);
2398 frameView->setNodeToDraw(&node);
2400 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2402 frameView->setBaseBackgroundColor(savedBackgroundColor);
2403 frameView->setNodeToDraw(nullptr);
2408 void WebPage::pageDidScroll()
2410 #if PLATFORM(IOS_FAMILY)
2411 if (!m_inDynamicSizeUpdate)
2412 m_dynamicSizeUpdateHistory.clear();
2414 m_uiClient->pageDidScroll(this);
2416 m_pageScrolledHysteresis.impulse();
2418 send(Messages::WebPageProxy::PageDidScroll());
2421 void WebPage::pageStoppedScrolling()
2423 // Maintain the current history item's scroll position up-to-date.
2424 if (Frame* frame = m_mainFrame->coreFrame())
2425 frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2428 #if ENABLE(CONTEXT_MENUS)
2429 WebContextMenu* WebPage::contextMenu()
2432 m_contextMenu = WebContextMenu::create(this);
2433 return m_contextMenu.get();
2436 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2438 corePage()->contextMenuController().clearContextMenu();
2440 // Simulate a mouse click to generate the correct menu.
2441 PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2442 corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2443 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2444 auto* menu = handled ? contextMenu() : nullptr;
2445 PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2446 corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2454 static const WebEvent* g_currentEvent = 0;
2456 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2457 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2458 // platform events passed to the event handler code.
2459 const WebEvent* WebPage::currentEvent()
2461 return g_currentEvent;
2464 void WebPage::freezeLayerTree(LayerTreeFreezeReason reason)
2466 RELEASE_LOG(ProcessSuspension, "%p - WebPage (PageID=%llu) - Adding a reason %d to freeze layer tree; current reasons are %d",
2467 this, m_pageID, static_cast<unsigned>(reason), m_LayerTreeFreezeReasons.toRaw());
2468 m_LayerTreeFreezeReasons.add(reason);
2469 updateDrawingAreaLayerTreeFreezeState();
2472 void WebPage::unfreezeLayerTree(LayerTreeFreezeReason reason)
2474 RELEASE_LOG(ProcessSuspension, "%p - WebPage (PageID=%llu) - Removing a reason %d to freeze layer tree; current reasons are %d",
2475 this, m_pageID, static_cast<unsigned>(reason), m_LayerTreeFreezeReasons.toRaw());
2476 m_LayerTreeFreezeReasons.remove(reason);
2477 updateDrawingAreaLayerTreeFreezeState();
2480 void WebPage::updateDrawingAreaLayerTreeFreezeState()
2484 m_drawingArea->setLayerTreeStateIsFrozen(!!m_LayerTreeFreezeReasons);
2487 void WebPage::callVolatilityCompletionHandlers(bool succeeded)
2489 auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2490 for (auto& completionHandler : completionHandlers)
2491 completionHandler(succeeded);
2494 void WebPage::layerVolatilityTimerFired()
2496 Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2497 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2498 if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2499 m_layerVolatilityTimer.stop();
2501 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Succeeded in marking layers as volatile", this);
2503 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Failed to mark layers as volatile within %gms", this, maximumLayerVolatilityTimerInterval.milliseconds());
2504 callVolatilityCompletionHandlers(didSucceed);
2508 RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.milliseconds());
2509 m_layerVolatilityTimer.startRepeating(newInterval);
2512 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2514 return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2517 void WebPage::markLayersVolatile(WTF::Function<void (bool)>&& completionHandler)
2519 RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2521 if (m_layerVolatilityTimer.isActive())
2522 m_layerVolatilityTimer.stop();
2524 if (completionHandler)
2525 m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2527 bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2528 if (didSucceed || m_isSuspendedUnderLock) {
2530 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2532 // 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.
2533 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2535 callVolatilityCompletionHandlers(didSucceed);
2539 RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.milliseconds());
2540 m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2543 void WebPage::cancelMarkLayersVolatile()
2545 RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2546 m_layerVolatilityTimer.stop();
2547 m_markLayersAsVolatileCompletionHandlers.clear();
2550 class CurrentEvent {
2552 explicit CurrentEvent(const WebEvent& event)
2553 : m_previousCurrentEvent(g_currentEvent)
2555 g_currentEvent = &event;
2560 g_currentEvent = m_previousCurrentEvent;
2564 const WebEvent* m_previousCurrentEvent;
2567 #if ENABLE(CONTEXT_MENUS)
2568 static bool isContextClick(const PlatformMouseEvent& event)
2571 return WebEventFactory::shouldBeHandledAsContextClick(event);
2573 return event.button() == WebCore::RightButton;
2577 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2579 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2580 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2582 Frame* frame = &page->corePage()->mainFrame();
2583 if (result.innerNonSharedNode())
2584 frame = result.innerNonSharedNode()->document().frame();
2586 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2588 page->contextMenu()->show();
2593 void WebPage::contextMenuForKeyEvent()
2595 corePage()->contextMenuController().clearContextMenu();
2597 Frame& frame = m_page->focusController().focusedOrMainFrame();
2598 bool handled = frame.eventHandler().sendContextMenuEventForKey();
2600 contextMenu()->show();
2604 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2606 Frame& frame = page->corePage()->mainFrame();
2610 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2612 switch (platformMouseEvent.type()) {
2613 case PlatformEvent::MousePressed: {
2614 #if ENABLE(CONTEXT_MENUS)
2615 if (isContextClick(platformMouseEvent))
2616 page->corePage()->contextMenuController().clearContextMenu();
2619 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2620 #if ENABLE(CONTEXT_MENUS)
2621 if (isContextClick(platformMouseEvent))
2622 handled = handleContextMenuEvent(platformMouseEvent, page);
2626 case PlatformEvent::MouseReleased:
2627 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2629 case PlatformEvent::MouseMoved:
2631 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2632 // button is currently pressed. It is possible that neither of those things will be true since on
2633 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2634 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2635 // efficient scrollbars-only version of the event.
2636 if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2637 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2639 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2641 case PlatformEvent::MouseForceChanged:
2642 case PlatformEvent::MouseForceDown:
2643 case PlatformEvent::MouseForceUp:
2644 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2647 ASSERT_NOT_REACHED();
2652 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2654 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2656 m_userActivityHysteresis.impulse();
2658 bool shouldHandleEvent = true;
2660 #if ENABLE(CONTEXT_MENUS)
2661 // Don't try to handle any pending mouse events if a context menu is showing.
2662 if (m_isShowingContextMenu)
2663 shouldHandleEvent = false;
2665 #if ENABLE(DRAG_SUPPORT)
2666 if (m_isStartingDrag)
2667 shouldHandleEvent = false;
2670 if (!shouldHandleEvent) {
2671 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2675 bool handled = false;
2677 #if !PLATFORM(IOS_FAMILY)
2678 if (!handled && m_headerBanner)
2679 handled = m_headerBanner->mouseEvent(mouseEvent);
2680 if (!handled && m_footerBanner)
2681 handled = m_footerBanner->mouseEvent(mouseEvent);
2682 #endif // !PLATFORM(IOS_FAMILY)
2685 CurrentEvent currentEvent(mouseEvent);
2686 handled = handleMouseEvent(mouseEvent, this);
2689 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2692 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2694 Frame& frame = page->mainFrame();
2698 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2699 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2702 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2704 m_userActivityHysteresis.impulse();
2706 CurrentEvent currentEvent(wheelEvent);
2708 bool handled = handleWheelEvent(wheelEvent, m_page.get());
2710 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2713 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2715 if (!page->mainFrame().view())
2718 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2719 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2720 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2723 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2725 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2727 m_userActivityHysteresis.impulse();
2729 PlatformKeyboardEvent::setCurrentModifierState(platform(keyboardEvent).modifiers());
2731 CurrentEvent currentEvent(keyboardEvent);
2733 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2734 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2736 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2738 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2741 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2743 bool isEnabled = false;
2745 Frame& frame = m_page->focusController().focusedOrMainFrame();
2746 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2747 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2749 Editor::Command command = frame.editor().command(commandName);
2750 state = command.state();
2751 isEnabled = command.isSupported() && command.isEnabled();
2754 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2757 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2759 executeEditingCommand(commandName, argument);
2762 void WebPage::setNeedsFontAttributes(bool needsFontAttributes)
2764 if (m_needsFontAttributes == needsFontAttributes)
2767 m_needsFontAttributes = needsFontAttributes;
2769 if (m_needsFontAttributes)
2770 sendPartialEditorStateAndSchedulePostLayoutUpdate();
2773 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest, WebBackForwardListProxy::OverwriteExistingItem overwrite)
2775 // Since we're merely restoring HistoryItems from the UIProcess, there is no need to send HistoryItem update notifications back to the UIProcess.
2776 // Also, with process-swap on navigation, these updates may actually overwrite important state in the UIProcess such as the scroll position.
2777 SetForScope<void (*)(WebCore::HistoryItem&)> bypassHistoryItemUpdateNotifications(WebCore::notifyHistoryItemChanged, [](WebCore::HistoryItem&){});
2778 for (const auto& itemState : itemStates) {
2779 auto historyItem = toHistoryItem(itemState);
2780 historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2781 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, overwrite);
2785 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2787 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes, WebBackForwardListProxy::OverwriteExistingItem::No);
2790 void WebPage::updateBackForwardListForReattach(const Vector<WebKit::BackForwardListItemState>& itemStates)
2792 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2795 void WebPage::setCurrentHistoryItemForReattach(WebKit::BackForwardListItemState&& itemState)
2797 auto historyItem = toHistoryItem(itemState);
2798 auto& historyItemRef = historyItem.get();
2799 static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2800 corePage()->mainFrame().loader().history().setCurrentItem(historyItemRef);
2803 void WebPage::requestFontAttributesAtSelectionStart(CallbackID callbackID)
2805 auto attributes = m_page->focusController().focusedOrMainFrame().editor().fontAttributesAtSelectionStart();
2806 send(Messages::WebPageProxy::FontAttributesCallback(attributes, callbackID));
2809 void WebPage::cancelGesturesBlockedOnSynchronousReplies()
2811 #if ENABLE(IOS_TOUCH_EVENTS)
2812 if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2816 #if PLATFORM(IOS_FAMILY)
2817 if (auto reply = WTFMove(m_pendingSynchronousPositionInformationReply))
2818 reply(InteractionInformationAtPosition::invalidInformation());
2822 #if ENABLE(TOUCH_EVENTS)
2823 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2825 if (!page->mainFrame().view())
2828 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2832 #if ENABLE(IOS_TOUCH_EVENTS)
2833 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2835 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2837 auto oldFocusedFrame = makeRefPtr(m_page->focusController().focusedFrame());
2838 auto oldFocusedElement = makeRefPtr(oldFocusedFrame ? oldFocusedFrame->document()->focusedElement() : nullptr);
2840 m_lastInteractionLocation = touchEvent.position();
2841 CurrentEvent currentEvent(touchEvent);
2842 handled = handleTouchEvent(touchEvent, m_page.get());
2843 updatePotentialTapSecurityOrigin(touchEvent, handled);
2845 if (handled && oldFocusedElement) {
2846 auto newFocusedFrame = makeRefPtr(m_page->focusController().focusedFrame());
2847 auto newFocusedElement = makeRefPtr(newFocusedFrame ? newFocusedFrame->document()->focusedElement() : nullptr);
2848 if (oldFocusedElement == newFocusedElement)
2849 elementDidRefocus(*newFocusedElement);
2853 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, CompletionHandler<void(bool)>&& reply)
2855 m_pendingSynchronousTouchEventReply = WTFMove(reply);
2857 EventDispatcher::TouchEventQueue queuedEvents;
2858 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2859 dispatchAsynchronousTouchEvents(queuedEvents);
2861 bool handled = true;
2862 dispatchTouchEvent(touchEvent, handled);
2864 if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2868 void WebPage::updatePotentialTapSecurityOrigin(const WebTouchEvent& touchEvent, bool wasHandled)
2873 if (!touchEvent.isPotentialTap())
2876 if (touchEvent.type() != WebEvent::TouchStart)
2879 auto& mainFrame = m_page->mainFrame();
2880 auto document = mainFrame.document();
2884 if (!document->handlingTouchEvent())
2887 Frame* touchEventTargetFrame = &mainFrame;
2888 while (auto subframe = touchEventTargetFrame->eventHandler().touchEventTargetSubframe())
2889 touchEventTargetFrame = subframe;
2891 auto& touches = touchEventTargetFrame->eventHandler().touches();
2892 if (touches.isEmpty())
2895 ASSERT(touches.size() == 1);
2897 if (auto targetDocument = touchEventTargetFrame->document())
2898 m_potentialTapSecurityOrigin = &targetDocument->securityOrigin();
2900 #elif ENABLE(TOUCH_EVENTS)
2901 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2903 CurrentEvent currentEvent(touchEvent);
2905 bool handled = handleTouchEvent(touchEvent, m_page.get());
2907 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2911 #if ENABLE(POINTER_EVENTS)
2912 void WebPage::cancelPointer(WebCore::PointerID pointerId, const WebCore::IntPoint& documentPoint)
2914 m_page->pointerCaptureController().cancelPointer(pointerId, documentPoint);
2918 #if ENABLE(MAC_GESTURE_EVENTS)
2919 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2921 if (!page->mainFrame().view())
2924 return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2927 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2929 CurrentEvent currentEvent(gestureEvent);
2930 bool handled = handleGestureEvent(gestureEvent, m_page.get());
2931 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2935 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2937 return page->userInputBridge().scrollRecursively(direction, granularity);
2940 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2942 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2945 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2947 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2950 void WebPage::centerSelectionInVisibleArea()
2952 Frame& frame = m_page->focusController().focusedOrMainFrame();
2953 frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2954 findController().showFindIndicatorInSelection();
2957 bool WebPage::isControlledByAutomation() const
2959 return m_page->isControlledByAutomation();
2962 void WebPage::setControlledByAutomation(bool controlled)
2964 m_page->setControlledByAutomation(controlled);
2967 void WebPage::connectInspector(const String& targetId, Inspector::FrontendChannel::ConnectionType connectionType)
2969 m_inspectorTargetController->connectInspector(targetId, connectionType);
2972 void WebPage::disconnectInspector(const String& targetId)
2974 m_inspectorTargetController->disconnectInspector(targetId);
2977 void WebPage::sendMessageToTargetBackend(const String& targetId, const String& message)
2979 m_inspectorTargetController->sendMessageToTargetBackend(targetId, message);
2982 void WebPage::insertNewlineInQuotedContent()
2984 Frame& frame = m_page->focusController().focusedOrMainFrame();
2985 if (frame.selection().isNone())
2987 frame.editor().insertParagraphSeparatorInQuotedContent();
2990 #if ENABLE(REMOTE_INSPECTOR)
2991 void WebPage::setIndicating(bool indicating)
2993 m_page->inspectorController().setIndicating(indicating);
2997 void WebPage::setBackgroundColor(const Optional<WebCore::Color>& backgroundColor)
2999 if (m_backgroundColor == backgroundColor)
3002 m_backgroundColor = backgroundColor;
3004 if (FrameView* frameView = mainFrameView())
3005 frameView->updateBackgroundRecursively(backgroundColor);
3007 m_drawingArea->setNeedsDisplay();
3011 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
3013 if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
3014 LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
3018 m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
3020 setTopContentInset(contentInset);
3022 deallocateSendRightSafely(fencePort.port());
3026 void WebPage::setTopContentInset(float contentInset)
3028 if (contentInset == m_page->topContentInset())
3031 m_page->setTopContentInset(contentInset);
3033 for (auto* pluginView : m_pluginViews)
3034 pluginView->topContentInsetDidChange();
3037 void WebPage::viewWillStartLiveResize()
3042 // FIXME: This should propagate to all ScrollableAreas.
3043 Frame& frame = m_page->focusController().focusedOrMainFrame();
3044 if (FrameView* view = frame.view())
3045 view->willStartLiveResize();
3048 void WebPage::viewWillEndLiveResize()
3053 // FIXME: This should propagate to all ScrollableAreas.
3054 Frame& frame = m_page->focusController().focusedOrMainFrame();
3055 if (FrameView* view = frame.view())
3056 view->willEndLiveResize();
3059 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
3064 SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
3066 Frame& frame = m_page->focusController().focusedOrMainFrame();
3067 frame.document()->setFocusedElement(0);
3069 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
3070 PlatformKeyboardEvent platformEvent(platform(event));
3071 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
3072 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
3074 send(Messages::WebPageProxy::VoidCallback(callbackID));
3078 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
3079 send(Messages::WebPageProxy::VoidCallback(callbackID));
3082 void WebPage::setCanStartMediaTimerFired()
3085 m_page->setCanStartMedia(true);
3088 void WebPage::updateIsInWindow(bool isInitialState)
3090 bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
3093 m_setCanStartMediaTimer.stop();
3094 m_page->setCanStartMedia(false);
3096 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
3097 if (!isInitialState)
3098 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
3100 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
3101 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
3102 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
3103 if (m_mayStartMediaWhenInWindow)
3104 m_setCanStartMediaTimer.startOneShot(0_s);
3106 WebProcess::singleton().pageDidEnterWindow(m_pageID);
3113 void WebPage::visibilityDidChange()
3115 bool isVisible = m_activityState.contains(ActivityState::IsVisible);
3117 // We save the document / scroll state when backgrounding a tab so that we are able to restore it
3118 // if it gets terminated while in the background.
3119 if (auto* frame = m_mainFrame->coreFrame())
3120 frame->loader().history().saveDocumentAndScrollState();
3124 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
3126 LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
3128 auto changed = m_activityState ^ activityState;
3129 m_activityState = activityState;
3132 updateThrottleState();
3134 ASSERT_WITH_MESSAGE(m_page, "setActivityState called on %" PRIu64 " but WebCore page was null", pageID());
3136 SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
3137 m_page->setActivityState(activityState);
3140 for (auto* pluginView : m_pluginViews)
3141 pluginView->activityStateDidChange(changed);
3143 m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
3144 WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
3146 if (changed & ActivityState::IsInWindow)
3149 if (changed & ActivityState::IsVisible)
3150 visibilityDidChange();
3153 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
3155 m_layerHostingMode = layerHostingMode;
3157 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
3159 for (auto* pluginView : m_pluginViews)
3160 pluginView->setLayerHostingMode(m_layerHostingMode);
3163 void WebPage::setSessionID(PAL::SessionID sessionID)
3165 m_page->setSessionID(sessionID);
3168 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyCheckIdentifier identifier, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, Optional<WebsitePoliciesData>&& websitePolicies)
3170 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3173 frame->didReceivePolicyDecision(listenerID, identifier, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
3176 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
3178 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3181 frame->continueWillSubmitForm(listenerID);
3184 void WebPage::didStartPageTransition()
3186 freezeLayerTree(LayerTreeFreezeReason::PageTransition);
3189 bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
3191 m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
3192 m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
3194 if (hasPreviouslyFocusedDueToUserInteraction)
3195 send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
3196 if (m_isTouchBarUpdateSupressedForHiddenContentEditable) {
3197 m_isTouchBarUpdateSupressedForHiddenContentEditable = false;
3198 send(Messages::WebPageProxy::SetIsTouchBarUpdateSupressedForHiddenContentEditable(m_isTouchBarUpdateSupressedForHiddenContentEditable));
3200 if (m_isNeverRichlyEditableForTouchBar) {
3201 m_isNeverRichlyEditableForTouchBar = false;
3202 send(Messages::WebPageProxy::SetIsNeverRichlyEditableForTouchBar(m_isNeverRichlyEditableForTouchBar));
3205 #if PLATFORM(IOS_FAMILY)
3206 m_isShowingInputViewForFocusedElement = false;
3210 void WebPage::didCompletePageTransition()
3212 unfreezeLayerTree(LayerTreeFreezeReason::PageTransition);
3214 RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did complete page transition", this);
3216 bool isInitialEmptyDocument = !m_mainFrame;
3217 if (!isInitialEmptyDocument)
3218 unfreezeLayerTree(LayerTreeFreezeReason::ProcessSwap);
3221 void WebPage::show()
3223 send(Messages::WebPageProxy::ShowPage());
3226 String WebPage::userAgent(const URL& webCoreURL) const
3228 String userAgent = platformUserAgent(webCoreURL);
3229 if (!userAgent.isEmpty())
3234 void WebPage::setUserAgent(const String& userAgent)
3236 if (m_userAgent == userAgent)
3239 m_userAgent = userAgent;
3242 m_page->userAgentChanged();
3245 void WebPage::suspendActiveDOMObjectsAndAnimations()
3247 m_page->suspendActiveDOMObjectsAndAnimations();
3250 void WebPage::resumeActiveDOMObjectsAndAnimations()
3252 m_page->resumeActiveDOMObjectsAndAnimations();
3255 IntPoint WebPage::screenToRootView(const IntPoint& point)
3257 IntPoint windowPoint;
3258 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
3262 IntRect WebPage::rootViewToScreen(const IntRect& rect)
3265 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
3269 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
3271 IntPoint windowPoint;
3272 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
3276 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
3279 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
3283 KeyboardUIMode WebPage::keyboardUIMode()
3285 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
3286 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
3289 void WebPage::runJavaScript(const String& script, bool forceUserGesture, Optional<String> worldName, CallbackID callbackID)
3291 // NOTE: We need to be careful when running scripts that the objects we depend on don't
3292 // disappear during script execution.
3294 RefPtr<SerializedScriptValue> serializedResultValue;
3295 JSLockHolder lock(commonVM());
3296 bool hadException = true;
3297 ExceptionDetails details;
3298 auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
3300 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeUserAgentScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
3301 hadException = false;
3302 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
3303 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
3307 IPC::DataReference dataReference;
3308 if (serializedResultValue)
3309 dataReference = serializedResultValue->data();
3310 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
3313 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
3315 runJavaScript(script, forceUserGesture, WTF::nullopt, callbackID);
3318 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
3320 runJavaScript(script, forceUserGesture, worldName, callbackID);
3323 void WebPage::getContentsAsString(CallbackID callbackID)
3325 String resultString = m_mainFrame->contentsAsString();
3326 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3330 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
3332 send(Messages::WebPageProxy::DataCallback({ MHTMLArchive::generateMHTMLData(m_page.get()) }, callbackID));
3336 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3338 String resultString = renderTreeExternalRepresentation();
3339 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3342 static Frame* frameWithSelection(Page* page)
3344 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3345 if (frame->selection().isRange())
3352 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3355 RetainPtr<CFDataRef> data;
3356 if (Frame* frame = frameWithSelection(m_page.get()))
3357 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3360 IPC::SharedBufferDataReference dataReference;
3363 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3365 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3368 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3370 WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3371 String resultString = focusedOrMainFrame->selectionAsString();
3372 if (resultString.isEmpty())
3373 resultString = focusedOrMainFrame->contentsAsString();
3374 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3377 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3379 String resultString;
3380 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3381 resultString = frame->source();
3383 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3386 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3388 RefPtr<SharedBuffer> buffer;
3389 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3390 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3391 buffer = pluginView->liveResourceData();
3393 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3394 buffer = loader->mainResourceData();
3398 IPC::SharedBufferDataReference dataReference;
3400 dataReference = { *buffer };
3401 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3404 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3406 DocumentLoader* loader = frame->loader().documentLoader();
3410 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3414 return &subresource->data();
3417 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3419 RefPtr<SharedBuffer> buffer;
3420 if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3421 URL resourceURL(URL(), resourceURLString);
3422 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3425 IPC::SharedBufferDataReference dataReference;
3427 dataReference = { *buffer };
3428 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3431 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3434 RetainPtr<CFDataRef> data;
3435 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3436 data = frame->webArchiveData(nullptr, nullptr);
3438 UNUSED_PARAM(frameID);
3441 IPC::SharedBufferDataReference dataReference;
3444 dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3446 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3449 void WebPage::forceRepaintWithoutCallback()
3451 m_drawingArea->forceRepaint();
3454 void WebPage::forceRepaint(CallbackID callbackID)
3456 if (m_drawingArea->forceRepaintAsync(callbackID))
3459 forceRepaintWithoutCallback();
3460 send(Messages::WebPageProxy::VoidCallback(callbackID));
3463 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3465 WebPreferencesStore::removeTestRunnerOverrides();
3466 updatePreferences(store);
3469 void WebPage::updatePreferences(const WebPreferencesStore& store)
3471 updatePreferencesGenerated(store);
3473 Settings& settings = m_page->settings();
3476 if (!settings.acceleratedCompositingEnabled()) {
3477 RELEASE_LOG_IF_ALLOWED("%p - WebPage - acceleratedCompositingEnabled setting was false. WebKit cannot function in this mode; changing setting to true", this);
3478 settings.setAcceleratedCompositingEnabled(true);
3482 bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3483 settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3484 settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3485 settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3486 settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3487 settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3488 settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3489 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3490 settings.setFrameFlattening(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()) ? WebCore::FrameFlattening::FullyEnabled : WebCore::FrameFlattening::Disabled);
3491 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3492 #if ENABLE(DATA_DETECTION)
3493 settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3496 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3498 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3499 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3500 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3501 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3503 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3504 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3506 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3507 setSessionID(PAL::SessionID::legacyPrivateSessionID());
3508 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3509 setSessionID(PAL::SessionID::defaultSessionID());
3511 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3512 if (m_processSuppressionEnabled != processSuppressionEnabled) {
3513 m_processSuppressionEnabled = processSuppressionEnabled;
3514 updateThrottleState();
3518 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3520 #if ENABLE(PAYMENT_REQUEST)
3521 settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3524 // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3525 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3527 #if PLATFORM(IOS_FAMILY)
3528 m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3529 m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3530 setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3532 settings.setUseImageDocumentForSubframePDF(true);
3534 DeprecatedGlobalSettings::setAVKitEnabled(true);
3538 #if ENABLE(SERVICE_WORKER)
3539 if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3540 ASSERT(parentProcessHasServiceWorkerEntitlement());
3541 if (!parentProcessHasServiceWorkerEntitlement())
3542 RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3546 settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3549 m_drawingArea->updatePreferences(store);
3552 #if ENABLE(DATA_DETECTION)
3554 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3556 DataDetectionResult dataDetectionResult;
3557 dataDetectionResult.results = detectionResults;
3558 send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3561 void WebPage::removeDataDetectedLinks(CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3563 for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3564 auto document = makeRefPtr(frame->document());
3568 DataDetection::removeDataDetectedLinksInDocument(*document);
3569 frame->setDataDetectionResults(nullptr);
3571 completionHandler({ m_page->mainFrame().dataDetectionResults() });
3574 void WebPage::detectDataInAllFrames(uint64_t types, CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3576 auto dataDetectorTypes = static_cast<WebCore::DataDetectorTypes>(types);
3577 for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3578 auto document = makeRefPtr(frame->document());
3582 RefPtr<Range> range = Range::create(*document, Position { document.get(), Position::PositionIsBeforeChildren }, Position { document.get(), Position::PositionIsAfterChildren });
3583 frame->setDataDetectionResults(DataDetection::detectContentInRange(range, dataDetectorTypes, m_dataDetectionContext.get()));
3585 completionHandler({ m_page->mainFrame().dataDetectionResults() });
3588 #endif // ENABLE(DATA_DETECTION)
3591 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3593 FrameView* frameView = corePage()->mainFrame().view();
3597 layerTransaction.setContentsSize(frameView->contentsSize());
3598 layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3599 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3600 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3601 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3603 layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3604 layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3605 layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3607 #if PLATFORM(IOS_FAMILY)
3608 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3609 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3610 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3611 layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3612 layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3613 layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3614 layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3615 layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3616 layerTransaction.setIsInStableState(m_isInStableState);
3617 layerTransaction.setAllowsUserScaling(allowsUserScaling());
3618 if (m_pendingDynamicViewportSizeUpdateID) {
3619 layerTransaction.setDynamicViewportSizeUpdateID(*m_pendingDynamicViewportSizeUpdateID);
3620 m_pendingDynamicViewportSizeUpdateID = WTF::nullopt;
3622 if (m_lastTransactionPageScaleFactor != layerTransaction.pageScaleFactor()) {
3623 m_lastTransactionPageScaleFactor = layerTransaction.pageScaleFactor();
3624 m_lastTransactionIDWithScaleChange = layerTransaction.transactionID();
3628 layerTransaction.setScrollPosition(frameView->scrollPosition());
3630 if (m_hasPendingEditorStateUpdate) {
3631 layerTransaction.setEditorState(editorState());
3632 m_hasPendingEditorStateUpdate = false;
3636 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3638 #if PLATFORM(IOS_FAMILY)
3639 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3640 Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3641 m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3643 m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3646 UNUSED_PARAM(timestamp);
3651 void WebPage::willDisplayPage()
3653 m_page->willDisplayPage();
3656 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3660 if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3661 m_inspector = WebInspector::create(this);
3662 return m_inspector.get();
3665 WebInspectorUI* WebPage::inspectorUI()
3670 m_inspectorUI = WebInspectorUI::create(*this);
3671 return m_inspectorUI.get();
3674 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3678 if (!m_remoteInspectorUI)
3679 m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3680 return m_remoteInspectorUI.get();
3683 void WebPage::inspectorFrontendCountChanged(unsigned count)
3685 send(Messages::WebPageProxy::DidChangeInspectorFrontendCount(count));
3688 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3689 PlaybackSessionManager& WebPage::playbackSessionManager()
3691 if (!m_playbackSessionManager)
3692 m_playbackSessionManager = PlaybackSessionManager::create(*this);
3693 return *m_playbackSessionManager;
3696 VideoFullscreenManager& WebPage::videoFullscreenManager()
3698 if (!m_videoFullscreenManager)
3699 m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3700 return *m_videoFullscreenManager;
3703 void WebPage::videoControlsManagerDidChange()
3705 #if ENABLE(FULLSCREEN_API)
3706 if (auto* manager = fullScreenManager())
3707 manager->videoControlsManagerDidChange();
3713 #if PLATFORM(IOS_FAMILY)
3714 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3716 m_page->setAllowsMediaDocumentInlinePlayback(allows);
3720 #if ENABLE(FULLSCREEN_API)
3721 WebFullScreenManager* WebPage::fullScreenManager()
3723 if (!m_fullScreenManager)
3724 m_fullScreenManager = WebFullScreenManager::create(this);
3725 return m_fullScreenManager.get();
3729 void WebPage::addConsoleMessage(uint64_t frameID, MessageSource messageSource, MessageLevel messageLevel, const String& message, uint64_t requestID)
3731 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3732 frame->addConsoleMessage(messageSource, messageLevel, message, requestID);
3735 void WebPage::sendCSPViolationReport(uint64_t frameID, const URL& reportURL, IPC::FormDataReference&& reportData)
3737 auto report = reportData.takeData();
3740 if (auto* frame = WebProcess::singleton().webFrame(frameID))
3741 PingLoader::sendViolationReport(*frame->coreFrame(), reportURL, report.releaseNonNull(), ViolationReportType::ContentSecurityPolicy);
3744 void WebPage::enqueueSecurityPolicyViolationEvent(uint64_t frameID, SecurityPolicyViolationEvent::Init&& eventInit)
3746 auto* frame = WebProcess::singleton().webFrame(frameID);
3749 auto* coreFrame = frame->coreFrame();
3752 if (auto* document = coreFrame->document())
3753 document->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
3756 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3758 if (m_notificationPermissionRequestManager)
3759 return m_notificationPermissionRequestManager.get();
3761 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3762 return m_notificationPermissionRequestManager.get();
3765 #if ENABLE(DRAG_SUPPORT)
3768 void WebPage::performDragControllerAction(DragControllerAction action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3771 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3775 DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3777 case DragControllerAction::Entered: {
3778 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3779 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3782 case DragControllerAction::Updated: {
3783 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3784 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3787 case DragControllerAction::Exited:
3788 m_page->dragController().dragExited(dragData);
3791 case DragControllerAction::PerformDragOperation: {
3792 m_page->dragController().performDragOperation(dragData);
3796 ASSERT_NOT_REACHED();
3799 void WebPage::performDragControllerAction(DragControllerAction action, const WebCore::DragData& dragData, SandboxExtension::Handle&& sandboxExtensionHandle, SandboxExtension::HandleArray&& sandboxExtensionsHandleArray)
3802 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3807 case DragControllerAction::Entered: {
3808 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3809 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()));
3812 case DragControllerAction::Updated: {
3813 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3814 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()));
3817 case DragControllerAction::Exited:
3818 m_page->dragController().dragExited(dragData);
3819 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3822 case DragControllerAction::PerformDragOperation: {
3823 ASSERT(!m_pendingDropSandboxExtension);
3825 m_pendingDropSandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
3826 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3827 if (auto extension = SandboxExtension::create(WTFMove(sandboxExtensionsHandleArray[i])))
3828 m_pendingDropExtensionsForFileUpload.append(extension);
3831 bool handled = m_page->dragController().performDragOperation(dragData);
3833 // If we started loading a local file, the sandbox extension tracker would have adopted this
3834 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3835 m_pendingDropSandboxExtension = nullptr;
3837 m_pendingDropExtensionsForFileUpload.clear();
3838 send(Messages::WebPageProxy::DidPerformDragOperation(handled));
3842 ASSERT_NOT_REACHED();
3846 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3848 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3849 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3851 m_page->dragController().dragEnded();
3852 FrameView* view = m_page->mainFrame().view();
3855 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3856 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), 0, WebCore::NoTap);
3857 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3859 send(Messages::WebPageProxy::DidEndDragging());
3862 void WebPage::willPerformLoadDragDestinationAction()
3864 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(WTFMove(m_pendingDropSandboxExtension));
3867 void WebPage::mayPerformUploadDragDestinationAction()
3869 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3870 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3871 m_pendingDropExtensionsForFileUpload.clear();
3874 void WebPage::didStartDrag()
3876 m_isStartingDrag = false;
3877 m_page->mainFrame().eventHandler().didStartDrag();
3880 void WebPage::dragCancelled()
3882 m_isStartingDrag = false;
3883 m_page->mainFrame().eventHandler().dragCancelled();
3886 #endif // ENABLE(DRAG_SUPPORT)
3888 WebUndoStep* WebPage::webUndoStep(WebUndoStepID stepID)
3890 return m_undoStepMap.get(stepID);
3893 void WebPage::addWebUndoStep(WebUndoStepID stepID, Ref<WebUndoStep>&& entry)
3895 auto addResult = m_undoStepMap.set(stepID, WTFMove(entry));
3896 ASSERT_UNUSED(addResult, addResult.isNewEntry);
3899 void WebPage::removeWebEditCommand(WebUndoStepID stepID)
3901 if (auto undoStep = m_undoStepMap.take(stepID))
3902 undoStep->didRemoveFromUndoManager();
3905 bool WebPage::isAlwaysOnLoggingAllowed() const
3907 return corePage() && corePage()->isAlwaysOnLoggingAllowed();
3910 void WebPage::unapplyEditCommand(WebUndoStepID stepID)
3912 auto* step = webUndoStep(stepID);
3916 step->step().unapply();
3919 void WebPage::reapplyEditCommand(WebUndoStepID stepID)
3921 auto* step = webUndoStep(stepID);
3926 step->step().reapply();
3930 void WebPage::didRemoveEditCommand(WebUndoStepID commandID)
3932 removeWebEditCommand(commandID);
3935 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3937 m_activePopupMenu = menu;
3940 #if ENABLE(INPUT_TYPE_COLOR)
3942 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3944 m_activeColorChooser = colorChooser;
3947 void WebPage::didEndColorPicker()
3949 m_activeColorChooser->didEndChooser();
3952 void WebPage::didChooseColor(const WebCore::Color& color)
3954 m_activeColorChooser->didChooseColor(color);
3959 #if ENABLE(DATALIST_ELEMENT)
3961 void WebPage::setActiveDataListSuggestionPicker(WebDataListSuggestionPicker* dataListSuggestionPicker)
3963 m_activeDataListSuggestionPicker = makeWeakPtr(dataListSuggestionPicker);
3966 void WebPage::didSelectDataListOption(const String& selectedOption)
3968 if (m_activeDataListSuggestionPicker)
3969 m_activeDataListSuggestionPicker->didSelectOption(selectedOption);
3972 void WebPage::didCloseSuggestions()
3974 if (auto picker = std::exchange(m_activeDataListSuggestionPicker, nullptr))
3975 picker->didCloseSuggestions();
3980 void WebPage::setActiveOpenPanelResultListener(Ref<WebOpenPanelResultListener>&& openPanelResultListener)
3982 m_activeOpenPanelResultListener = WTFMove(openPanelResultListener);
3985 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3987 return m_page->findString(target, core(options));
3990 void WebPage::findStringMatchesFromInjectedBundle(const String& target, FindOptions options)
3992 findController().findStringMatches(target, options, 0);
3995 void WebPage::replaceStringMatchesFromInjectedBundle(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly)
3997 findController().replaceMatches(matchIndices, replacementText, selectionOnly);
4000 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
4002 findController().findString(string, static_cast<FindOptions>(options), maxMatchCount);
4005 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
4007 findController().findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
4010 void WebPage::getImageForFindMatch(uint32_t matchIndex)
4012 findController().getImageForFindMatch(matchIndex);
4015 void WebPage::selectFindMatch(uint32_t matchIndex)
4017 findController().selectFindMatch(matchIndex);
4020 void WebPage::hideFindUI()
4022 findController().hideFindUI();
4025 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
4027 findController().countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
4030 void WebPage::replaceMatches(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly, CallbackID callbackID)
4032 auto numberOfReplacements = findController().replaceMatches(matchIndices, replacementText, selectionOnly);
4033 send(Messages::WebPageProxy::UnsignedCallback(numberOfReplacements, callbackID));
4036 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
4038 changeSelectedIndex(newIndex);
4039 m_activePopupMenu = nullptr;
4042 void WebPage::changeSelectedIndex(int32_t index)
4044 if (!m_activePopupMenu)
4047 m_activePopupMenu->didChangeSelectedIndex(index);
4050 #if PLATFORM(IOS_FAMILY)
4051 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
4053 if (!m_activeOpenPanelResultListener)
4057 if (!iconData.isEmpty()) {
4058 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
4059 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
4060 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
4061 icon = Icon::createIconForImage(imageRef.get());
4064 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
4065 m_activeOpenPanelResultListener = nullptr;
4069 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
4071 if (!m_activeOpenPanelResultListener)
4074 m_activeOpenPanelResultListener->didChooseFiles(files);
4075 m_activeOpenPanelResultListener = nullptr;
4078 void WebPage::didCancelForOpenPanel()
4080 m_activeOpenPanelResultListener = nullptr;
4083 #if ENABLE(SANDBOX_EXTENSIONS)
4084 void WebPage::extendSandboxForFilesFromOpenPanel(SandboxExtension::HandleArray&& handles)
4086 for (size_t i = 0; i < handles.size(); ++i) {
4087 bool result = SandboxExtension::consumePermanently(handles[i]);
4089 // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
4090 WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
4096 #if ENABLE(GEOLOCATION)
4097 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
4099 geolocationPermissionRequestManager().didReceiveGeolocationPermissionDecision(geolocationID, allowed);
4103 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
4105 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
4108 #if ENABLE(MEDIA_STREAM)
4110 void WebPage::userMediaAccessWasGranted(uint64_t userMediaID, WebCore::CaptureDevice&& audioDevice, WebCore::CaptureDevice&& videoDevice, String&& mediaDeviceIdentifierHashSalt)
4112 m_userMediaPermissionRequestManager->userMediaAccessWasGranted(userMediaID, WTFMove(audioDevice), WTFMove(videoDevice), WTFMove(mediaDeviceIdentifierHashSalt));
4115 void WebPage::userMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String&& invalidConstraint)
4117 m_userMediaPermissionRequestManager->userMediaAccessWasDenied(userMediaID, static_cast<UserMediaRequest::MediaAccessDenialReason>(reason), WTFMove(invalidConstraint));
4120 void WebPage::didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vector<CaptureDevice>& devices, String&& deviceIdentifierHashSalt, bool originHasPersistentAccess)
4122 m_userMediaPermissionRequestManager->didCompleteMediaDeviceEnumeration(userMediaID, devices, WTFMove(deviceIdentifierHashSalt), originHasPersistentAccess);
4125 void WebPage::captureDevicesChanged()
4127 m_userMediaPermissionRequestManager->captureDevicesChanged();
4132 #if !PLATFORM(IOS_FAMILY)
4133 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
4135 Frame& frame = m_page->focusController().focusedOrMainFrame();
4136 frame.editor().advanceToNextMisspelling(startBeforeSelection);
4140 bool WebPage::hasRichlyEditableSelection() const
4142 auto& frame = m_page->focusController().focusedOrMainFrame();
4143 if (m_page->dragCaretController().isContentRichlyEditable())
4146 return frame.selection().selection().isContentRichlyEditable();
4149 void WebPage::changeSpellingToWord(const String& word)