2 * Copyright (C) 2010, 2011, 2012, 2013-2015 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 "Arguments.h"
34 #include "DataReference.h"
35 #include "DragControllerAction.h"
36 #include "DrawingArea.h"
37 #include "DrawingAreaMessages.h"
38 #include "EditingRange.h"
39 #include "EditorState.h"
40 #include "EventDispatcher.h"
41 #include "InjectedBundle.h"
42 #include "InjectedBundleBackForwardList.h"
43 #include "LayerTreeHost.h"
45 #include "NetscapePlugin.h"
46 #include "NotificationPermissionRequestManager.h"
47 #include "PageBanner.h"
48 #include "PluginProcessAttributes.h"
49 #include "PluginProxy.h"
50 #include "PluginView.h"
51 #include "PrintInfo.h"
52 #include "SessionState.h"
53 #include "SessionStateConversion.h"
54 #include "SessionTracker.h"
55 #include "ShareableBitmap.h"
56 #include "VisitedLinkTableController.h"
57 #include "WKBundleAPICast.h"
58 #include "WKRetainPtr.h"
59 #include "WKSharedAPICast.h"
60 #include "WebAlternativeTextClient.h"
61 #include "WebBackForwardListItem.h"
62 #include "WebBackForwardListProxy.h"
63 #include "WebChromeClient.h"
64 #include "WebColorChooser.h"
65 #include "WebContextMenu.h"
66 #include "WebContextMenuClient.h"
67 #include "WebCoreArgumentCoders.h"
68 #include "WebDatabaseProvider.h"
69 #include "WebDiagnosticLoggingClient.h"
70 #include "WebDocumentLoader.h"
71 #include "WebDragClient.h"
72 #include "WebEditorClient.h"
74 #include "WebEventConversion.h"
75 #include "WebEventFactory.h"
77 #include "WebFrameLoaderClient.h"
78 #include "WebFullScreenManager.h"
79 #include "WebFullScreenManagerMessages.h"
80 #include "WebGeolocationClient.h"
82 #include "WebInspector.h"
83 #include "WebInspectorClient.h"
84 #include "WebInspectorMessages.h"
85 #include "WebInspectorUI.h"
86 #include "WebInspectorUIMessages.h"
87 #include "WebMediaKeyStorageManager.h"
88 #include "WebNotificationClient.h"
89 #include "WebOpenPanelResultListener.h"
90 #include "WebPageCreationParameters.h"
91 #include "WebPageGroupProxy.h"
92 #include "WebPageMessages.h"
93 #include "WebPageOverlay.h"
94 #include "WebPageProxyMessages.h"
95 #include "WebPlugInClient.h"
96 #include "WebPopupMenu.h"
97 #include "WebPreferencesDefinitions.h"
98 #include "WebPreferencesKeys.h"
99 #include "WebPreferencesStore.h"
100 #include "WebProcess.h"
101 #include "WebProcessPoolMessages.h"
102 #include "WebProcessProxyMessages.h"
103 #include "WebProgressTrackerClient.h"
104 #include "WebStorageNamespaceProvider.h"
105 #include "WebUndoStep.h"
106 #include "WebUserContentController.h"
107 #include "WebUserMediaClient.h"
108 #include <JavaScriptCore/APICast.h>
109 #include <WebCore/ArchiveResource.h>
110 #include <WebCore/Chrome.h>
111 #include <WebCore/ContextMenuController.h>
112 #include <WebCore/DataTransfer.h>
113 #include <WebCore/DatabaseManager.h>
114 #include <WebCore/DocumentFragment.h>
115 #include <WebCore/DocumentLoader.h>
116 #include <WebCore/DocumentMarkerController.h>
117 #include <WebCore/DragController.h>
118 #include <WebCore/DragData.h>
119 #include <WebCore/ElementIterator.h>
120 #include <WebCore/EventHandler.h>
121 #include <WebCore/FocusController.h>
122 #include <WebCore/FormState.h>
123 #include <WebCore/FrameLoadRequest.h>
124 #include <WebCore/FrameLoaderTypes.h>
125 #include <WebCore/FrameView.h>
126 #include <WebCore/HTMLFormElement.h>
127 #include <WebCore/HTMLInputElement.h>
128 #include <WebCore/HTMLPlugInElement.h>
129 #include <WebCore/HTMLPlugInImageElement.h>
130 #include <WebCore/HistoryController.h>
131 #include <WebCore/HistoryItem.h>
132 #include <WebCore/HitTestResult.h>
133 #include <WebCore/JSDOMWindow.h>
134 #include <WebCore/KeyboardEvent.h>
135 #include <WebCore/MIMETypeRegistry.h>
136 #include <WebCore/MainFrame.h>
137 #include <WebCore/MouseEvent.h>
138 #include <WebCore/Page.h>
139 #include <WebCore/PageConfiguration.h>
140 #include <WebCore/PageThrottler.h>
141 #include <WebCore/PlatformKeyboardEvent.h>
142 #include <WebCore/PluginDocument.h>
143 #include <WebCore/PrintContext.h>
144 #include <WebCore/Range.h>
145 #include <WebCore/RenderLayer.h>
146 #include <WebCore/RenderTreeAsText.h>
147 #include <WebCore/RenderView.h>
148 #include <WebCore/ResourceRequest.h>
149 #include <WebCore/ResourceResponse.h>
150 #include <WebCore/RuntimeEnabledFeatures.h>
151 #include <WebCore/SchemeRegistry.h>
152 #include <WebCore/ScriptController.h>
153 #include <WebCore/SerializedScriptValue.h>
154 #include <WebCore/SessionID.h>
155 #include <WebCore/Settings.h>
156 #include <WebCore/ShadowRoot.h>
157 #include <WebCore/SharedBuffer.h>
158 #include <WebCore/StyleProperties.h>
159 #include <WebCore/SubframeLoader.h>
160 #include <WebCore/SubstituteData.h>
161 #include <WebCore/TextIterator.h>
162 #include <WebCore/UserInputBridge.h>
163 #include <WebCore/VisiblePosition.h>
164 #include <WebCore/VisibleUnits.h>
165 #include <WebCore/markup.h>
166 #include <bindings/ScriptValue.h>
167 #include <profiler/ProfilerDatabase.h>
168 #include <runtime/JSCInlines.h>
169 #include <runtime/JSCJSValue.h>
170 #include <runtime/JSLock.h>
171 #include <wtf/RunLoop.h>
172 #include <wtf/TemporaryChange.h>
175 #include <WebCore/MHTMLArchive.h>
178 #if ENABLE(BATTERY_STATUS)
179 #include "WebBatteryClient.h"
182 #if ENABLE(VIBRATION)
183 #include "WebVibrationClient.h"
186 #if ENABLE(PROXIMITY_EVENTS)
187 #include "WebDeviceProximityClient.h"
191 #include "PDFPlugin.h"
192 #include "RemoteLayerTreeTransaction.h"
193 #include "WKStringCF.h"
194 #include <WebCore/LegacyWebArchive.h>
199 #include "DataObjectGtk.h"
200 #include "WebPrintOperationGtk.h"
204 #include "RemoteLayerTreeDrawingArea.h"
205 #include "WebVideoFullscreenManager.h"
206 #include <CoreGraphics/CoreGraphics.h>
207 #include <WebCore/CoreTextSPI.h>
208 #include <WebCore/Icon.h>
212 #include <wtf/RefCountedLeakCounter.h>
215 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
216 #include "CoordinatedLayerTreeHostMessages.h"
219 #if ENABLE(VIDEO) && USE(GSTREAMER)
220 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
224 using namespace WebCore;
228 static const double pageScrollHysteresisSeconds = 0.3;
230 class SendStopResponsivenessTimer {
232 SendStopResponsivenessTimer(WebPage* page)
237 ~SendStopResponsivenessTimer()
239 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
246 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
248 Ref<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
250 Ref<WebPage> page = adoptRef(*new WebPage(pageID, parameters));
252 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
253 WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
258 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
260 , m_viewSize(parameters.viewSize)
261 , m_hasSeenPlugin(false)
262 , m_useFixedLayout(false)
263 , m_drawsBackground(true)
264 , m_drawsTransparentBackground(false)
267 , m_tabToLinks(false)
268 , m_asynchronousPluginInitializationEnabled(false)
269 , m_asynchronousPluginInitializationEnabledForAllPlugins(false)
270 , m_artificialPluginInitializationDelayEnabled(false)
271 , m_scrollingPerformanceLoggingEnabled(false)
272 , m_mainFrameIsScrollable(true)
273 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
274 , m_readyToFindPrimarySnapshottedPlugin(false)
275 , m_didFindPrimarySnapshottedPlugin(false)
276 , m_numberOfPrimarySnapshotDetectionAttempts(0)
277 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
279 , m_layerHostingMode(parameters.layerHostingMode)
281 , m_pdfPluginEnabled(false)
282 , m_hasCachedWindowFrame(false)
283 , m_viewGestureGeometryCollector(*this)
284 #elif HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL))
285 , m_accessibilityObject(nullptr)
287 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
288 #if ENABLE(CONTEXT_MENUS)
289 , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
291 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
292 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
293 , m_findController(this)
294 #if ENABLE(INPUT_TYPE_COLOR)
295 , m_activeColorChooser(0)
297 , m_userContentController(parameters.userContentControllerID ? WebUserContentController::getOrCreate(parameters.userContentControllerID) : nullptr)
298 #if ENABLE(GEOLOCATION)
299 , m_geolocationPermissionRequestManager(this)
301 #if ENABLE(MEDIA_STREAM)
302 , m_userMediaPermissionRequestManager(*this)
304 , m_pageScrolledHysteresis([this](HysteresisState state) { if (state == HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisSeconds)
305 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
306 , m_canRunModal(parameters.canRunModal)
307 , m_isRunningModal(false)
308 #if ENABLE(DRAG_SUPPORT)
309 , m_isStartingDrag(false)
311 , m_cachedMainFrameIsPinnedToLeftSide(true)
312 , m_cachedMainFrameIsPinnedToRightSide(true)
313 , m_cachedMainFrameIsPinnedToTopSide(true)
314 , m_cachedMainFrameIsPinnedToBottomSide(true)
315 , m_canShortCircuitHorizontalWheelEvents(false)
316 , m_hasWheelEventHandlers(false)
317 , m_cachedPageCount(0)
318 , m_autoSizingShouldExpandToViewHeight(false)
319 #if ENABLE(CONTEXT_MENUS)
320 , m_isShowingContextMenu(false)
323 , m_selectionAnchor(Start)
324 , m_hasReceivedVisibleContentRectsAfterDidCommitLoad(false)
325 , m_scaleWasSetByUIProcess(false)
326 , m_userHasChangedPageScaleFactor(false)
327 , m_hasStablePageScaleFactor(true)
328 , m_userIsInteracting(false)
329 , m_hasPendingBlurNotification(false)
330 , m_useTestingViewportConfiguration(false)
331 , m_isInStableState(true)
332 , m_oldestNonStableUpdateVisibleContentRectsTimestamp(std::chrono::milliseconds::zero())
333 , m_estimatedLatency(std::chrono::milliseconds::zero())
334 , m_screenSize(parameters.screenSize)
335 , m_availableScreenSize(parameters.availableScreenSize)
336 , m_deviceOrientation(0)
337 , m_inDynamicSizeUpdate(false)
338 , m_volatilityTimer(*this, &WebPage::volatilityTimerFired)
340 , m_backgroundColor(Color::white)
341 , m_maximumRenderingSuppressionToken(0)
342 , m_scrollPinningBehavior(DoNotPin)
343 , m_useAsyncScrolling(false)
344 , m_viewState(parameters.viewState)
345 , m_processSuppressionEnabled(true)
346 , m_userActivity("Process suppression disabled for page.")
347 , m_pendingNavigationID(0)
349 , m_systemWebGLPolicy(WebGLAllowCreation)
351 , m_mainFrameProgressCompleted(false)
352 , m_shouldDispatchFakeMouseMoveEvents(true)
356 m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
359 Settings::setShouldManageAudioSessionCategory(true);
362 PageConfiguration pageConfiguration;
363 pageConfiguration.chromeClient = new WebChromeClient(this);
364 #if ENABLE(CONTEXT_MENUS)
365 pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
367 pageConfiguration.editorClient = new WebEditorClient(this);
368 #if ENABLE(DRAG_SUPPORT)
369 pageConfiguration.dragClient = new WebDragClient(this);
371 pageConfiguration.backForwardClient = WebBackForwardListProxy::create(this);
372 pageConfiguration.inspectorClient = new WebInspectorClient(this);
373 #if USE(AUTOCORRECTION_PANEL)
374 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
376 pageConfiguration.plugInClient = new WebPlugInClient(*this);
377 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
378 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
379 pageConfiguration.diagnosticLoggingClient = new WebDiagnosticLoggingClient(*this);
381 pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
382 pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
383 pageConfiguration.userContentController = m_userContentController ? &m_userContentController->userContentController() : &m_pageGroup->userContentController();
384 pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
386 m_page = std::make_unique<Page>(pageConfiguration);
388 m_drawingArea = DrawingArea::create(*this, parameters);
389 m_drawingArea->setPaintingEnabled(false);
390 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
392 #if ENABLE(ASYNC_SCROLLING)
393 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
394 if (!m_drawingArea->supportsAsyncScrolling())
395 m_useAsyncScrolling = false;
396 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
399 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
401 #if ENABLE(BATTERY_STATUS)
402 WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
404 #if ENABLE(GEOLOCATION)
405 WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
407 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
408 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
410 #if ENABLE(VIBRATION)
411 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
413 #if ENABLE(PROXIMITY_EVENTS)
414 WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this));
416 #if ENABLE(MEDIA_STREAM)
417 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
420 #if ENABLE(REMOTE_INSPECTOR)
421 m_page->setRemoteInspectionAllowed(true);
424 m_page->setCanStartMedia(false);
425 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
427 m_page->setGroupName(m_pageGroup->identifier());
428 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
430 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
433 updatePreferences(parameters.store);
434 platformInitialize();
436 setUseFixedLayout(parameters.useFixedLayout);
438 setDrawsBackground(parameters.drawsBackground);
439 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
441 setUnderlayColor(parameters.underlayColor);
443 setPaginationMode(parameters.paginationMode);
444 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
445 setPageLength(parameters.pageLength);
446 setGapBetweenPages(parameters.gapBetweenPages);
448 // If the page is created off-screen, its visibilityState should be prerender.
449 m_page->setViewState(m_viewState);
451 m_page->setIsPrerender();
452 updateUserActivity();
454 updateIsInWindow(true);
456 setMinimumLayoutSize(parameters.minimumLayoutSize);
457 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
459 setScrollPinningBehavior(parameters.scrollPinningBehavior);
460 if (parameters.scrollbarOverlayStyle)
461 m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
463 m_scrollbarOverlayStyle = WTF::Optional<ScrollbarOverlayStyle>();
465 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
467 setTopContentInset(parameters.topContentInset);
469 m_userAgent = parameters.userAgent;
471 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
473 if (!parameters.itemStates.isEmpty())
474 restoreSession(parameters.itemStates);
476 if (parameters.sessionID.isValid())
477 setSessionID(parameters.sessionID);
479 m_drawingArea->setPaintingEnabled(true);
481 setMediaVolume(parameters.mediaVolume);
483 setMuted(parameters.muted);
485 // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
486 m_page->addLayoutMilestones(DidFirstLayout | DidFirstVisuallyNonEmptyLayout);
488 auto& webProcess = WebProcess::singleton();
489 webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
491 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
492 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
493 webProcess.addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this);
495 webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
496 webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
497 #if ENABLE(FULLSCREEN_API)
498 webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
502 webPageCounter.increment();
505 #if ENABLE(ASYNC_SCROLLING)
506 if (m_useAsyncScrolling)
507 webProcess.eventDispatcher().addScrollingTreeForPage(this);
510 for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
511 m_mimeTypesWithCustomContentProviders.add(mimeType);
514 #if ENABLE(ENCRYPTED_MEDIA_V2)
515 if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
516 m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
518 m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
520 if (parameters.viewScaleFactor != 1)
521 scaleView(parameters.viewScaleFactor);
524 m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
528 void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters)
530 if (m_viewState != parameters.viewState)
531 setViewState(parameters.viewState, false, Vector<uint64_t>());
532 if (m_layerHostingMode != parameters.layerHostingMode)
533 setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode));
536 void WebPage::setPageActivityState(PageActivityState::Flags activityState)
538 PageActivityState::Flags changed = m_activityState ^ activityState;
539 m_activityState = activityState;
542 updateUserActivity();
545 void WebPage::updateUserActivity()
547 // Start the activity to prevent AppNap if the page activity is in progress,
548 // the page is visible and non-idle, or process suppression is disabled.
549 if (m_activityState || !(m_viewState & ViewState::IsVisuallyIdle) || !m_processSuppressionEnabled)
550 m_userActivity.start();
552 m_userActivity.stop();
557 if (m_backForwardList)
558 m_backForwardList->detach();
562 auto& webProcess = WebProcess::singleton();
563 #if ENABLE(ASYNC_SCROLLING)
564 if (m_useAsyncScrolling)
565 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
570 m_sandboxExtensionTracker.invalidate();
572 for (auto* pluginView : m_pluginViews)
573 pluginView->webPageDestroyed();
577 m_headerBanner->detachFromPage();
579 m_footerBanner->detachFromPage();
580 #endif // !PLATFORM(IOS)
582 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
584 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
585 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
586 webProcess.removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID);
588 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
589 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
590 #if ENABLE(FULLSCREEN_API)
591 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
595 webPageCounter.decrement();
599 void WebPage::dummy(bool&)
603 IPC::Connection* WebPage::messageSenderConnection()
605 return WebProcess::singleton().parentProcessConnection();
608 uint64_t WebPage::messageSenderDestinationID()
613 #if ENABLE(CONTEXT_MENUS)
614 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient> contextMenuClient)
616 if (!contextMenuClient) {
617 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
621 m_contextMenuClient = WTF::move(contextMenuClient);
625 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* client)
627 m_editorClient.initialize(client);
630 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient> formClient)
633 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
637 m_formClient = WTF::move(formClient);
640 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client)
642 m_loaderClient.initialize(client);
644 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
645 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
646 // for backwards compatibility.
647 LayoutMilestones milestones = 0;
649 if (m_loaderClient.client().didFirstLayoutForFrame)
650 milestones |= WebCore::DidFirstLayout;
651 if (m_loaderClient.client().didFirstVisuallyNonEmptyLayoutForFrame)
652 milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
656 listenForLayoutMilestones(milestones);
659 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
661 m_policyClient.initialize(client);
664 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase* client)
666 m_resourceLoadClient.initialize(client);
669 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient> uiClient)
672 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
676 m_uiClient = WTF::move(uiClient);
679 #if ENABLE(FULLSCREEN_API)
680 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
682 m_fullScreenClient.initialize(client);
686 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase* client)
688 m_logDiagnosticMessageClient.initialize(client);
691 #if ENABLE(NETSCAPE_PLUGIN_API)
692 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
694 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
695 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
697 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
698 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
699 unsigned pluginArea = 0;
700 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
702 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
705 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
707 uint64_t pluginProcessToken;
708 uint32_t pluginLoadPolicy;
709 String unavailabilityDescription;
710 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)))
713 PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
714 bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
716 if (isBlockedPlugin || !pluginProcessToken) {
717 #if ENABLE(PDFKIT_PLUGIN)
718 String path = parameters.url.path();
719 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
720 RefPtr<PDFPlugin> pdfPlugin = PDFPlugin::create(frame);
721 return pdfPlugin.release();
728 if (isBlockedPlugin) {
729 bool replacementObscured = false;
730 if (is<RenderEmbeddedObject>(*pluginElement->renderer())) {
731 auto& renderObject = downcast<RenderEmbeddedObject>(*pluginElement->renderer());
732 renderObject.setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
733 replacementObscured = renderObject.isReplacementObscured();
734 renderObject.setUnavailablePluginIndicatorIsHidden(replacementObscured);
737 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
741 if (!pluginProcessToken)
744 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
745 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
748 #endif // ENABLE(NETSCAPE_PLUGIN_API)
750 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
751 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
753 return WebGLAllowCreation;
756 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
758 return WebGLAllowCreation;
762 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
764 Frame& frame = m_page->focusController().focusedOrMainFrame();
768 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
769 if (!pluginView->getSelectionString().isNull()) {
770 result.selectionIsNone = false;
771 result.selectionIsRange = true;
772 result.isInPlugin = true;
777 const VisibleSelection& selection = frame.selection().selection();
779 result.selectionIsNone = selection.isNone();
780 result.selectionIsRange = selection.isRange();
781 result.isContentEditable = selection.isContentEditable();
782 result.isContentRichlyEditable = selection.isContentRichlyEditable();
783 result.isInPasswordField = selection.isInPasswordField();
784 result.hasComposition = frame.editor().hasComposition();
785 result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange();
787 platformEditorState(frame, result, shouldIncludePostLayoutData);
792 String WebPage::renderTreeExternalRepresentation() const
794 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
797 String WebPage::renderTreeExternalRepresentationForPrinting() const
799 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
802 uint64_t WebPage::renderTreeSize() const
806 return m_page->renderTreeSize();
809 void WebPage::setTracksRepaints(bool trackRepaints)
811 if (FrameView* view = mainFrameView())
812 view->setTracksRepaints(trackRepaints);
815 bool WebPage::isTrackingRepaints() const
817 if (FrameView* view = mainFrameView())
818 return view->isTrackingRepaints();
823 void WebPage::resetTrackedRepaints()
825 if (FrameView* view = mainFrameView())
826 view->resetTrackedRepaints();
829 Ref<API::Array> WebPage::trackedRepaintRects()
831 FrameView* view = mainFrameView();
833 return API::Array::create();
835 Vector<RefPtr<API::Object>> repaintRects;
836 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
838 for (const auto& repaintRect : view->trackedRepaintRects())
839 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
841 return API::Array::create(WTF::move(repaintRects));
844 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
846 if (!frame.document()->isPluginDocument())
849 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
851 if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
854 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
858 PluginView* WebPage::pluginViewForFrame(Frame* frame)
860 if (!frame->document()->isPluginDocument())
863 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
864 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
868 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
870 Frame& frame = m_page->focusController().focusedOrMainFrame();
872 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
873 pluginView->handleEditingCommand(commandName, argument);
877 frame.editor().command(commandName).execute(argument);
880 void WebPage::setEditable(bool editable)
882 m_page->setEditable(editable);
883 m_page->setTabKeyCyclesThroughElements(!editable);
884 Frame& frame = m_page->focusController().focusedOrMainFrame();
886 frame.editor().applyEditingStyleToBodyElement();
887 // If the page is made editable and the selection is empty, set it to something.
888 if (frame.selection().isNone())
889 frame.selection().setSelectionFromNone();
893 bool WebPage::isEditingCommandEnabled(const String& commandName)
895 Frame& frame = m_page->focusController().focusedOrMainFrame();
897 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
898 return pluginView->isEditingCommandEnabled(commandName);
900 Editor::Command command = frame.editor().command(commandName);
901 return command.isSupported() && command.isEnabled();
904 void WebPage::clearMainFrameName()
906 if (Frame* frame = mainFrame())
907 frame->tree().clearName();
910 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
912 m_drawingArea->setRootCompositingLayer(layer);
915 void WebPage::exitAcceleratedCompositingMode()
917 m_drawingArea->setRootCompositingLayer(0);
920 void WebPage::close()
927 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
928 if (!mainWebFrame()->url().isEmpty())
929 reportUsedFeatures();
931 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
932 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
935 m_inspector->disconnectFromPage();
936 m_inspector = nullptr;
939 #if ENABLE(FULLSCREEN_API)
940 m_fullScreenManager = nullptr;
943 if (m_activePopupMenu) {
944 m_activePopupMenu->disconnectFromPage();
945 m_activePopupMenu = nullptr;
948 if (m_activeOpenPanelResultListener) {
949 m_activeOpenPanelResultListener->disconnectFromPage();
950 m_activeOpenPanelResultListener = nullptr;
953 #if ENABLE(INPUT_TYPE_COLOR)
954 if (m_activeColorChooser) {
955 m_activeColorChooser->disconnectFromPage();
956 m_activeColorChooser = nullptr;
961 if (m_printOperation) {
962 m_printOperation->disconnectFromPage();
963 m_printOperation = nullptr;
967 #if ENABLE(VIDEO) && USE(GSTREAMER)
968 if (m_installMediaPluginsCallback) {
969 m_installMediaPluginsCallback->invalidate();
970 m_installMediaPluginsCallback = nullptr;
974 m_sandboxExtensionTracker.invalidate();
976 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
977 m_determinePrimarySnapshottedPlugInTimer.stop();
980 #if ENABLE(CONTEXT_MENUS)
981 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
983 m_editorClient.initialize(0);
984 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
985 m_loaderClient.initialize(0);
986 m_policyClient.initialize(0);
987 m_resourceLoadClient.initialize(0);
988 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
989 #if ENABLE(FULLSCREEN_API)
990 m_fullScreenClient.initialize(0);
992 m_logDiagnosticMessageClient.initialize(0);
994 m_printContext = nullptr;
995 m_mainFrame->coreFrame()->loader().detachFromParent();
997 m_drawingArea = nullptr;
999 bool isRunningModal = m_isRunningModal;
1000 m_isRunningModal = false;
1002 // The WebPage can be destroyed by this call.
1003 WebProcess::singleton().removeWebPage(m_pageID);
1005 WebProcess::singleton().updateActivePages();
1008 RunLoop::main().stop();
1011 void WebPage::tryClose()
1013 SendStopResponsivenessTimer stopper(this);
1015 if (!corePage()->userInputBridge().tryClosePage()) {
1016 send(Messages::WebPageProxy::StopResponsivenessTimer());
1020 send(Messages::WebPageProxy::ClosePage(true));
1023 void WebPage::sendClose()
1025 send(Messages::WebPageProxy::ClosePage(false));
1028 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
1030 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1034 frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url)), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1037 void WebPage::loadRequest(uint64_t navigationID, const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, uint64_t shouldOpenExternalURLsPolicy, const UserData& userData)
1039 SendStopResponsivenessTimer stopper(this);
1041 m_pendingNavigationID = navigationID;
1043 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1045 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1046 // to all the client to set up any needed state.
1047 m_loaderClient.willLoadURLRequest(this, request, WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1049 // Initate the load in WebCore.
1050 FrameLoadRequest frameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1051 ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(shouldOpenExternalURLsPolicy);
1052 frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1054 corePage()->userInputBridge().loadRequest(frameLoadRequest);
1056 ASSERT(!m_pendingNavigationID);
1059 void WebPage::loadDataImpl(uint64_t navigationID, PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1061 SendStopResponsivenessTimer stopper(this);
1063 m_pendingNavigationID = navigationID;
1065 ResourceRequest request(baseURL);
1066 ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1067 SubstituteData substituteData(sharedBuffer, unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1069 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1070 // to all the client to set up any needed state.
1071 m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1073 // Initate the load in WebCore.
1074 m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData));
1077 void WebPage::loadString(uint64_t navigationID, const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1079 if (!htmlString.isNull() && htmlString.is8Bit()) {
1080 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
1081 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, userData);
1083 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
1084 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, userData);
1088 void WebPage::loadData(uint64_t navigationID, const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, const UserData& userData)
1090 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
1091 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1092 loadDataImpl(navigationID, sharedBuffer, MIMEType, encodingName, baseURL, URL(), userData);
1095 void WebPage::loadHTMLString(uint64_t navigationID, const String& htmlString, const String& baseURLString, const UserData& userData)
1097 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1098 loadString(navigationID, htmlString, ASCIILiteral("text/html"), baseURL, URL(), userData);
1101 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, const String& provisionalLoadErrorURLString, const UserData& userData)
1103 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1104 URL unreachableURL = unreachableURLString.isEmpty() ? URL() : URL(URL(), unreachableURLString);
1105 URL provisionalLoadErrorURL = provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), provisionalLoadErrorURLString);
1106 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1107 loadString(0, htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, userData);
1108 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1111 void WebPage::loadPlainTextString(const String& string, const UserData& userData)
1113 loadString(0, string, ASCIILiteral("text/plain"), blankURL(), URL(), userData);
1116 void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, const UserData& userData)
1118 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
1119 loadDataImpl(0, sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), userData);
1122 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1124 Frame* mainFrame = m_mainFrame->coreFrame();
1125 Document* mainFrameDocument = mainFrame->document();
1126 if (!mainFrameDocument)
1129 const int singleClick = 1;
1130 RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, true, true, currentTime(), nullptr, singleClick, screenPoint.x(), screenPoint.y(), documentPoint.x(), documentPoint.y(),
1131 #if ENABLE(POINTER_LOCK)
1134 false, false, false, false, 0, nullptr, 0, nullptr);
1136 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1139 void WebPage::stopLoadingFrame(uint64_t frameID)
1141 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1145 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1148 void WebPage::stopLoading()
1150 SendStopResponsivenessTimer stopper(this);
1152 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1155 bool WebPage::defersLoading() const
1157 return m_page->defersLoading();
1160 void WebPage::setDefersLoading(bool defersLoading)
1162 m_page->setDefersLoading(defersLoading);
1165 void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, bool contentBlockersEnabled, const SandboxExtension::Handle& sandboxExtensionHandle)
1167 SendStopResponsivenessTimer stopper(this);
1169 ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1170 m_pendingNavigationID = navigationID;
1172 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1173 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin, contentBlockersEnabled);
1176 void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID)
1178 SendStopResponsivenessTimer stopper(this);
1180 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1185 ASSERT(!m_pendingNavigationID);
1186 m_pendingNavigationID = navigationID;
1188 m_page->goToItem(*item, FrameLoadType::Forward);
1191 void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID)
1193 SendStopResponsivenessTimer stopper(this);
1195 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1200 ASSERT(!m_pendingNavigationID);
1201 m_pendingNavigationID = navigationID;
1203 m_page->goToItem(*item, FrameLoadType::Back);
1206 void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID)
1208 SendStopResponsivenessTimer stopper(this);
1210 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1215 ASSERT(!m_pendingNavigationID);
1216 m_pendingNavigationID = navigationID;
1218 m_page->goToItem(*item, FrameLoadType::IndexedBackForward);
1221 void WebPage::tryRestoreScrollPosition()
1223 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1226 void WebPage::layoutIfNeeded()
1228 if (m_mainFrame->coreFrame()->view())
1229 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1232 WebPage* WebPage::fromCorePage(Page* page)
1234 return static_cast<WebChromeClient&>(page->chrome().client()).page();
1237 void WebPage::setSize(const WebCore::IntSize& viewSize)
1239 if (m_viewSize == viewSize)
1242 FrameView* view = m_page->mainFrame().view();
1243 view->resize(viewSize);
1244 m_drawingArea->setNeedsDisplay();
1246 m_viewSize = viewSize;
1248 #if USE(COORDINATED_GRAPHICS)
1249 if (view->useFixedLayout())
1250 sendViewportAttributesChanged();
1254 #if USE(COORDINATED_GRAPHICS)
1255 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1257 ASSERT(m_useFixedLayout);
1259 m_page->mainFrame().view()->setFixedVisibleContentRect(rect);
1262 void WebPage::sendViewportAttributesChanged()
1264 ASSERT(m_useFixedLayout);
1266 // Viewport properties have no impact on zero sized fixed viewports.
1267 if (m_viewSize.isEmpty())
1270 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1271 Settings& settings = m_page->settings();
1273 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1275 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1276 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1277 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1279 ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1281 FrameView* view = m_page->mainFrame().view();
1283 // If no layout was done yet set contentFixedOrigin to (0,0).
1284 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1286 // Put the width and height to the viewport width and height. In css units however.
1287 // Use FloatSize to avoid truncated values during scale.
1288 FloatSize contentFixedSize = m_viewSize;
1290 #if ENABLE(CSS_DEVICE_ADAPTATION)
1291 // CSS viewport descriptors might be applied to already affected viewport size
1292 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1293 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1296 contentFixedSize.scale(1 / attr.initialScale);
1297 setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1299 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1301 // This also takes care of the relayout.
1302 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1304 #if USE(COORDINATED_GRAPHICS_THREADED)
1305 if (m_drawingArea->layerTreeHost())
1306 m_drawingArea->layerTreeHost()->didChangeViewportProperties(attr);
1308 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1313 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1315 FrameView* frameView = m_page->mainFrame().view();
1317 IntPoint scrollPosition = frameView->scrollPosition();
1318 IntPoint maximumScrollPosition = frameView->maximumScrollPosition();
1320 // If the current scroll position in a direction is the max scroll position
1321 // we don't want to scroll at all.
1322 IntSize newScrollOffset;
1323 if (scrollPosition.x() < maximumScrollPosition.x())
1324 newScrollOffset.setWidth(scrollOffset.width());
1325 if (scrollPosition.y() < maximumScrollPosition.y())
1326 newScrollOffset.setHeight(scrollOffset.height());
1328 if (newScrollOffset.isZero())
1331 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1334 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1336 GraphicsContextStateSaver stateSaver(graphicsContext);
1337 graphicsContext.clip(rect);
1339 m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1342 double WebPage::textZoomFactor() const
1344 Frame* frame = m_mainFrame->coreFrame();
1347 return frame->textZoomFactor();
1350 void WebPage::setTextZoomFactor(double zoomFactor)
1352 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1353 if (pluginView && pluginView->handlesPageScaleFactor())
1356 Frame* frame = m_mainFrame->coreFrame();
1359 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1362 double WebPage::pageZoomFactor() const
1364 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1365 if (pluginView && pluginView->handlesPageScaleFactor())
1366 return pluginView->pageScaleFactor();
1368 Frame* frame = m_mainFrame->coreFrame();
1371 return frame->pageZoomFactor();
1374 void WebPage::setPageZoomFactor(double zoomFactor)
1376 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1377 if (pluginView && pluginView->handlesPageScaleFactor()) {
1378 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1382 Frame* frame = m_mainFrame->coreFrame();
1385 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1388 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1390 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1391 if (pluginView && pluginView->handlesPageScaleFactor()) {
1392 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1396 Frame* frame = m_mainFrame->coreFrame();
1399 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1402 void WebPage::windowScreenDidChange(uint32_t displayID)
1404 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1407 void WebPage::scalePage(double scale, const IntPoint& origin)
1409 double totalScale = scale * viewScaleFactor();
1410 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1413 if (willChangeScaleFactor) {
1414 if (!m_inDynamicSizeUpdate)
1415 m_dynamicSizeUpdateHistory.clear();
1416 m_scaleWasSetByUIProcess = false;
1419 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1420 if (pluginView && pluginView->handlesPageScaleFactor()) {
1421 // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1422 // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1423 if (m_page->pageScaleFactor() != 1) {
1424 m_page->setPageScaleFactor(1, origin);
1425 for (auto* pluginView : m_pluginViews)
1426 pluginView->pageScaleFactorDidChange();
1429 pluginView->setPageScaleFactor(totalScale, origin);
1433 m_page->setPageScaleFactor(totalScale, origin);
1435 // We can't early return before setPageScaleFactor because the origin might be different.
1436 if (!willChangeScaleFactor)
1439 for (auto* pluginView : m_pluginViews)
1440 pluginView->pageScaleFactorDidChange();
1442 if (m_drawingArea->layerTreeHost())
1443 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1445 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1448 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1450 double totalScale = scale * viewScaleFactor();
1451 if (totalScale == totalScaleFactor())
1454 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1455 double scaleRatio = scale / pageScaleFactor();
1456 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1457 scalePage(scale, scrollPositionAtNewScale);
1460 double WebPage::totalScaleFactor() const
1462 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1463 if (pluginView && pluginView->handlesPageScaleFactor())
1464 return pluginView->pageScaleFactor();
1466 return m_page->pageScaleFactor();
1469 double WebPage::pageScaleFactor() const
1471 return totalScaleFactor() / viewScaleFactor();
1474 double WebPage::viewScaleFactor() const
1476 return m_page->viewScaleFactor();
1479 void WebPage::scaleView(double scale)
1481 if (viewScaleFactor() == scale)
1484 float pageScale = pageScaleFactor();
1486 IntPoint scrollPositionAtNewScale;
1487 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1488 double scaleRatio = scale / viewScaleFactor();
1489 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1490 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1493 m_page->setViewScaleFactor(scale);
1494 scalePage(pageScale, scrollPositionAtNewScale);
1497 void WebPage::setDeviceScaleFactor(float scaleFactor)
1499 if (scaleFactor == m_page->deviceScaleFactor())
1502 m_page->setDeviceScaleFactor(scaleFactor);
1504 // Tell all our plug-in views that the device scale factor changed.
1506 for (auto* pluginView : m_pluginViews)
1507 pluginView->setDeviceScaleFactor(scaleFactor);
1509 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1512 if (m_findController.isShowingOverlay()) {
1513 // We must have updated layout to get the selection rects right.
1515 m_findController.deviceScaleFactorDidChange();
1518 if (m_drawingArea->layerTreeHost())
1519 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1522 float WebPage::deviceScaleFactor() const
1524 return m_page->deviceScaleFactor();
1527 void WebPage::setUseFixedLayout(bool fixed)
1529 // Do not overwrite current settings if initially setting it to false.
1530 if (m_useFixedLayout == fixed)
1532 m_useFixedLayout = fixed;
1535 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1537 #if USE(COORDINATED_GRAPHICS)
1538 m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1539 m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1540 m_page->settings().setDelegatesPageScaling(fixed);
1541 m_page->settings().setScrollingCoordinatorEnabled(fixed);
1544 #if USE(COORDINATED_GRAPHICS) && ENABLE(SMOOTH_SCROLLING)
1545 // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1546 // Ensure we don't do animated scrolling in the WebProcess in that case.
1547 m_page->settings().setScrollAnimatorEnabled(!fixed);
1550 FrameView* view = mainFrameView();
1554 #if USE(COORDINATED_GRAPHICS)
1555 view->setDelegatesScrolling(fixed);
1556 view->setPaintsEntireContents(fixed);
1558 view->setUseFixedLayout(fixed);
1560 setFixedLayoutSize(IntSize());
1562 send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1565 void WebPage::setFixedLayoutSize(const IntSize& size)
1567 FrameView* view = mainFrameView();
1568 if (!view || view->fixedLayoutSize() == size)
1571 view->setFixedLayoutSize(size);
1573 send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1576 IntSize WebPage::fixedLayoutSize() const
1578 FrameView* view = mainFrameView();
1581 return view->fixedLayoutSize();
1584 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1588 m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1591 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1593 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1596 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1598 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1601 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1603 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1606 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1608 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1609 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1612 void WebPage::setPaginationMode(uint32_t mode)
1614 Pagination pagination = m_page->pagination();
1615 pagination.mode = static_cast<Pagination::Mode>(mode);
1616 m_page->setPagination(pagination);
1619 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1621 Pagination pagination = m_page->pagination();
1622 pagination.behavesLikeColumns = behavesLikeColumns;
1623 m_page->setPagination(pagination);
1626 void WebPage::setPageLength(double pageLength)
1628 Pagination pagination = m_page->pagination();
1629 pagination.pageLength = pageLength;
1630 m_page->setPagination(pagination);
1633 void WebPage::setGapBetweenPages(double gap)
1635 Pagination pagination = m_page->pagination();
1636 pagination.gap = gap;
1637 m_page->setPagination(pagination);
1640 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1642 auto& webProcess = WebProcess::singleton();
1643 InjectedBundle* injectedBundle = webProcess.injectedBundle();
1644 if (!injectedBundle)
1647 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1651 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1654 m_headerBanner->detachFromPage();
1656 m_headerBanner = pageBanner;
1659 m_headerBanner->addToPage(PageBanner::Header, this);
1662 PageBanner* WebPage::headerPageBanner()
1664 return m_headerBanner.get();
1667 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1670 m_footerBanner->detachFromPage();
1672 m_footerBanner = pageBanner;
1675 m_footerBanner->addToPage(PageBanner::Footer, this);
1678 PageBanner* WebPage::footerPageBanner()
1680 return m_footerBanner.get();
1683 void WebPage::hidePageBanners()
1686 m_headerBanner->hide();
1688 m_footerBanner->hide();
1691 void WebPage::showPageBanners()
1694 m_headerBanner->showIfHidden();
1696 m_footerBanner->showIfHidden();
1698 #endif // !PLATFORM(IOS)
1700 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1702 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1703 snapshotOptions |= SnapshotOptionsShareable;
1705 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1707 ShareableBitmap::Handle handle;
1709 image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly);
1711 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1714 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1716 IntRect snapshotRect = rect;
1717 IntSize bitmapSize = snapshotRect.size();
1718 if (options & SnapshotOptionsPrinting) {
1719 ASSERT(additionalScaleFactor == 1);
1720 Frame* coreFrame = m_mainFrame->coreFrame();
1723 bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
1725 double scaleFactor = additionalScaleFactor;
1726 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1727 scaleFactor *= corePage()->deviceScaleFactor();
1728 bitmapSize.scale(scaleFactor);
1731 return snapshotAtSize(rect, bitmapSize, options);
1734 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1736 Frame* coreFrame = m_mainFrame->coreFrame();
1740 FrameView* frameView = coreFrame->view();
1744 IntRect snapshotRect = rect;
1745 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1746 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1747 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1749 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1750 if (!snapshot->bitmap())
1753 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1755 if (options & SnapshotOptionsPrinting) {
1756 PrintContext::spoolAllPagesWithBoundaries(*coreFrame, *graphicsContext, snapshotRect.size());
1757 return snapshot.release();
1760 Color documentBackgroundColor = frameView->documentBackgroundColor();
1761 Color backgroundColor = (coreFrame->settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView->baseBackgroundColor();
1762 graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor, ColorSpaceDeviceRGB);
1764 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1765 double deviceScaleFactor = corePage()->deviceScaleFactor();
1766 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1767 scaleFactor /= deviceScaleFactor;
1770 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1771 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1773 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1774 if (options & SnapshotOptionsExcludeSelectionHighlighting)
1775 shouldPaintSelection = FrameView::ExcludeSelection;
1777 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1778 if (options & SnapshotOptionsInViewCoordinates)
1779 coordinateSpace = FrameView::ViewCoordinates;
1781 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
1783 if (options & SnapshotOptionsPaintSelectionRectangle) {
1784 FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1785 graphicsContext->setStrokeColor(Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
1786 graphicsContext->strokeRect(selectionRectangle, 1);
1789 return snapshot.release();
1792 PassRefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
1794 Frame* coreFrame = m_mainFrame->coreFrame();
1798 FrameView* frameView = coreFrame->view();
1802 if (!node.renderer())
1805 LayoutRect topLevelRect;
1806 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
1807 if (snapshotRect.isEmpty())
1810 double scaleFactor = 1;
1811 IntSize snapshotSize = snapshotRect.size();
1812 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
1813 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
1814 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
1815 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
1818 RefPtr<WebImage> snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options));
1819 if (!snapshot->bitmap())
1822 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1824 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1825 double deviceScaleFactor = corePage()->deviceScaleFactor();
1826 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1827 scaleFactor /= deviceScaleFactor;
1830 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1831 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1833 Color savedBackgroundColor = frameView->baseBackgroundColor();
1834 frameView->setBaseBackgroundColor(Color::transparent);
1835 frameView->setNodeToDraw(&node);
1837 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
1839 frameView->setBaseBackgroundColor(savedBackgroundColor);
1840 frameView->setNodeToDraw(nullptr);
1842 return snapshot.release();
1845 void WebPage::pageDidScroll()
1848 if (!m_inDynamicSizeUpdate)
1849 m_dynamicSizeUpdateHistory.clear();
1851 m_uiClient->pageDidScroll(this);
1853 m_pageScrolledHysteresis.impulse();
1855 send(Messages::WebPageProxy::PageDidScroll());
1858 void WebPage::pageStoppedScrolling()
1860 // Maintain the current history item's scroll position up-to-date.
1861 if (Frame* frame = m_mainFrame->coreFrame())
1862 frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
1865 #if USE(COORDINATED_GRAPHICS)
1866 void WebPage::pageDidRequestScroll(const IntPoint& point)
1868 #if USE(COORDINATED_GRAPHICS_THREADED)
1869 drawingArea()->scroll(IntRect(point, IntSize()), IntSize());
1870 #elif USE(COORDINATED_GRAPHICS_MULTIPROCESS)
1871 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1876 #if ENABLE(CONTEXT_MENUS)
1877 WebContextMenu* WebPage::contextMenu()
1880 m_contextMenu = WebContextMenu::create(this);
1881 return m_contextMenu.get();
1884 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1886 corePage()->contextMenuController().clearContextMenu();
1888 // Simulate a mouse click to generate the correct menu.
1889 PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick);
1890 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
1894 return contextMenu();
1900 static const WebEvent* g_currentEvent = 0;
1902 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1903 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1904 // platform events passed to the event handler code.
1905 const WebEvent* WebPage::currentEvent()
1907 return g_currentEvent;
1910 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
1912 auto* drawingArea = this->drawingArea();
1916 drawingArea->setLayerTreeStateIsFrozen(frozen);
1919 bool WebPage::markLayersVolatileImmediatelyIfPossible()
1921 auto* drawingArea = this->drawingArea();
1925 return drawingArea->markLayersVolatileImmediatelyIfPossible();
1928 class CurrentEvent {
1930 explicit CurrentEvent(const WebEvent& event)
1931 : m_previousCurrentEvent(g_currentEvent)
1933 g_currentEvent = &event;
1938 g_currentEvent = m_previousCurrentEvent;
1942 const WebEvent* m_previousCurrentEvent;
1945 #if ENABLE(CONTEXT_MENUS)
1946 static bool isContextClick(const PlatformMouseEvent& event)
1949 return WebEventFactory::shouldBeHandledAsContextClick(event);
1951 return event.button() == WebCore::RightButton;
1955 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1957 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
1958 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
1960 Frame* frame = &page->corePage()->mainFrame();
1961 if (result.innerNonSharedNode())
1962 frame = result.innerNonSharedNode()->document().frame();
1964 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
1966 page->contextMenu()->show();
1972 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1974 Frame& frame = page->corePage()->mainFrame();
1978 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1980 switch (platformMouseEvent.type()) {
1981 case PlatformEvent::MousePressed: {
1982 #if ENABLE(CONTEXT_MENUS)
1983 if (isContextClick(platformMouseEvent))
1984 page->corePage()->contextMenuController().clearContextMenu();
1987 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
1988 #if ENABLE(CONTEXT_MENUS)
1989 if (isContextClick(platformMouseEvent))
1990 handled = handleContextMenuEvent(platformMouseEvent, page);
1994 case PlatformEvent::MouseReleased:
1995 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
1997 case PlatformEvent::MouseMoved:
1998 if (onlyUpdateScrollbars)
1999 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2000 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2002 case PlatformEvent::MouseForceChanged:
2003 case PlatformEvent::MouseForceDown:
2004 case PlatformEvent::MouseForceUp:
2005 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2008 ASSERT_NOT_REACHED();
2013 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2015 m_page->pageThrottler().didReceiveUserInput();
2017 bool shouldHandleEvent = true;
2019 #if ENABLE(CONTEXT_MENUS)
2020 // Don't try to handle any pending mouse events if a context menu is showing.
2021 if (m_isShowingContextMenu)
2022 shouldHandleEvent = false;
2024 #if ENABLE(DRAG_SUPPORT)
2025 if (m_isStartingDrag)
2026 shouldHandleEvent = false;
2029 if (!shouldHandleEvent) {
2030 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2034 bool handled = false;
2037 if (!handled && m_headerBanner)
2038 handled = m_headerBanner->mouseEvent(mouseEvent);
2039 if (!handled && m_footerBanner)
2040 handled = m_footerBanner->mouseEvent(mouseEvent);
2041 #endif // !PLATFORM(IOS)
2043 if (!handled && canHandleUserEvents()) {
2044 CurrentEvent currentEvent(mouseEvent);
2046 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2047 // button is currently pressed. It is possible that neither of those things will be true since on
2048 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2049 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2050 // efficient scrollbars-only version of the event.
2051 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
2052 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
2055 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2058 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2060 Frame& frame = page->mainFrame();
2064 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2065 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2068 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2070 m_page->pageThrottler().didReceiveUserInput();
2072 bool handled = false;
2074 if (canHandleUserEvents()) {
2075 CurrentEvent currentEvent(wheelEvent);
2077 handled = handleWheelEvent(wheelEvent, m_page.get());
2079 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2082 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2084 if (!page->mainFrame().view())
2087 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2088 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2089 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2092 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2094 m_page->pageThrottler().didReceiveUserInput();
2096 bool handled = false;
2098 if (canHandleUserEvents()) {
2099 CurrentEvent currentEvent(keyboardEvent);
2101 handled = handleKeyEvent(keyboardEvent, m_page.get());
2102 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2104 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2106 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2109 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
2111 bool isEnabled = false;
2113 Frame& frame = m_page->focusController().focusedOrMainFrame();
2114 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2115 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2117 Editor::Command command = frame.editor().command(commandName);
2118 state = command.state();
2119 isEnabled = command.isSupported() && command.isEnabled();
2122 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2125 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2127 executeEditingCommand(commandName, argument);
2130 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2132 for (const auto& itemState : itemStates)
2133 WebBackForwardListProxy::addItemFromUIProcess(itemState.identifier, toHistoryItem(itemState.pageState), m_pageID);
2136 #if ENABLE(TOUCH_EVENTS)
2137 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2139 if (!page->mainFrame().view())
2142 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2146 #if ENABLE(IOS_TOUCH_EVENTS)
2147 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2149 m_userIsInteracting = true;
2151 m_lastInteractionLocation = touchEvent.position();
2152 CurrentEvent currentEvent(touchEvent);
2153 handled = handleTouchEvent(touchEvent, m_page.get());
2155 m_userIsInteracting = false;
2158 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2160 EventDispatcher::TouchEventQueue queuedEvents;
2161 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2162 dispatchAsynchronousTouchEvents(queuedEvents);
2164 dispatchTouchEvent(touchEvent, handled);
2166 #elif ENABLE(TOUCH_EVENTS)
2167 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2170 bool handled = false;
2171 if (canHandleUserEvents()) {
2172 CurrentEvent currentEvent(touchEvent);
2174 handled = handleTouchEvent(touchEvent, m_page.get());
2176 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2180 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2182 return page->userInputBridge().scrollRecursively(direction, granularity);
2185 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2187 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2190 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2192 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2195 void WebPage::centerSelectionInVisibleArea()
2197 Frame& frame = m_page->focusController().focusedOrMainFrame();
2198 frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
2199 m_findController.showFindIndicatorInSelection();
2202 #if ENABLE(REMOTE_INSPECTOR)
2203 void WebPage::setAllowsRemoteInspection(bool allow)
2205 m_page->setRemoteInspectionAllowed(allow);
2209 void WebPage::setDrawsBackground(bool drawsBackground)
2211 if (m_drawsBackground == drawsBackground)
2214 m_drawsBackground = drawsBackground;
2216 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2217 if (FrameView* view = coreFrame->view())
2218 view->setTransparent(!drawsBackground);
2221 m_drawingArea->pageBackgroundTransparencyChanged();
2222 m_drawingArea->setNeedsDisplay();
2225 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
2227 if (m_drawsTransparentBackground == drawsTransparentBackground)
2230 m_drawsTransparentBackground = drawsTransparentBackground;
2232 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2233 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2234 if (FrameView* view = coreFrame->view())
2235 view->setBaseBackgroundColor(backgroundColor);
2238 m_drawingArea->pageBackgroundTransparencyChanged();
2239 m_drawingArea->setNeedsDisplay();
2242 void WebPage::setTopContentInset(float contentInset)
2244 if (contentInset == m_page->topContentInset())
2247 m_page->setTopContentInset(contentInset);
2249 for (auto* pluginView : m_pluginViews)
2250 pluginView->topContentInsetDidChange();
2253 void WebPage::viewWillStartLiveResize()
2258 // FIXME: This should propagate to all ScrollableAreas.
2259 Frame& frame = m_page->focusController().focusedOrMainFrame();
2260 if (FrameView* view = frame.view())
2261 view->willStartLiveResize();
2264 void WebPage::viewWillEndLiveResize()
2269 // FIXME: This should propagate to all ScrollableAreas.
2270 Frame& frame = m_page->focusController().focusedOrMainFrame();
2271 if (FrameView* view = frame.view())
2272 view->willEndLiveResize();
2275 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, uint64_t callbackID)
2281 TemporaryChange<bool> userIsInteractingChange { m_userIsInteracting, true };
2284 Frame& frame = m_page->focusController().focusedOrMainFrame();
2285 frame.document()->setFocusedElement(0);
2287 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2288 PlatformKeyboardEvent platformEvent(platform(event));
2289 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2290 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2292 send(Messages::WebPageProxy::VoidCallback(callbackID));
2296 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2297 send(Messages::WebPageProxy::VoidCallback(callbackID));
2300 void WebPage::setCanStartMediaTimerFired()
2303 m_page->setCanStartMedia(true);
2306 inline bool WebPage::canHandleUserEvents() const
2308 #if USE(COORDINATED_GRAPHICS)
2309 // Should apply only if the area was frozen by didStartPageTransition().
2310 return !m_drawingArea->layerTreeStateIsFrozen();
2315 void WebPage::updateIsInWindow(bool isInitialState)
2317 bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2320 m_setCanStartMediaTimer.stop();
2321 m_page->setCanStartMedia(false);
2323 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2324 if (!isInitialState)
2325 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2327 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2328 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2329 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2330 if (m_mayStartMediaWhenInWindow)
2331 m_setCanStartMediaTimer.startOneShot(0);
2333 WebProcess::singleton().pageDidEnterWindow(m_pageID);
2340 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState, const Vector<uint64_t>& callbackIDs)
2342 ViewState::Flags changed = m_viewState ^ viewState;
2343 m_viewState = viewState;
2346 updateUserActivity();
2348 m_page->setViewState(viewState);
2349 for (auto* pluginView : m_pluginViews)
2350 pluginView->viewStateDidChange(changed);
2352 m_drawingArea->viewStateDidChange(changed, wantsDidUpdateViewState, callbackIDs);
2354 if (changed & ViewState::IsInWindow)
2358 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2360 m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2362 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2364 for (auto* pluginView : m_pluginViews)
2365 pluginView->setLayerHostingMode(m_layerHostingMode);
2368 void WebPage::setSessionID(SessionID sessionID)
2370 if (sessionID.isEphemeral())
2371 WebProcess::singleton().ensurePrivateBrowsingSession(sessionID);
2372 m_page->setSessionID(sessionID);
2375 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, uint64_t downloadID)
2377 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2380 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID);
2383 void WebPage::didStartPageTransition()
2385 m_drawingArea->setLayerTreeStateIsFrozen(true);
2387 m_hasFocusedDueToUserInteraction = false;
2391 void WebPage::didCompletePageTransition()
2393 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
2394 // m_mainFrame can be null since r170163.
2395 if (m_mainFrame && m_mainFrame->coreFrame()->view()->delegatesScrolling()) {
2396 // Wait until the UI process sent us the visible rect it wants rendered.
2397 send(Messages::WebPageProxy::PageTransitionViewportReady());
2401 m_drawingArea->setLayerTreeStateIsFrozen(false);
2404 void WebPage::show()
2406 send(Messages::WebPageProxy::ShowPage());
2409 String WebPage::userAgent(const URL& webCoreURL) const
2411 return userAgent(nullptr, webCoreURL);
2414 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2416 if (frame && m_loaderClient.client().userAgentForURL) {
2417 API::String* apiString = m_loaderClient.userAgentForURL(frame, API::URL::create(webcoreURL).ptr());
2419 return apiString->string();
2422 String userAgent = platformUserAgent(webcoreURL);
2423 if (!userAgent.isEmpty())
2428 void WebPage::setUserAgent(const String& userAgent)
2430 m_userAgent = userAgent;
2433 void WebPage::suspendActiveDOMObjectsAndAnimations()
2435 m_page->suspendActiveDOMObjectsAndAnimations();
2438 void WebPage::resumeActiveDOMObjectsAndAnimations()
2440 m_page->resumeActiveDOMObjectsAndAnimations();
2443 IntPoint WebPage::screenToRootView(const IntPoint& point)
2445 IntPoint windowPoint;
2446 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2450 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2453 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2458 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2460 IntPoint windowPoint;
2461 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2465 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2468 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2473 KeyboardUIMode WebPage::keyboardUIMode()
2475 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
2476 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2479 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2481 // NOTE: We need to be careful when running scripts that the objects we depend on don't
2482 // disappear during script execution.
2484 RefPtr<SerializedScriptValue> serializedResultValue;
2485 JSLockHolder lock(JSDOMWindow::commonVM());
2486 bool hadException = true;
2487 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) {
2488 hadException = false;
2489 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
2490 toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr);
2493 IPC::DataReference dataReference;
2494 if (serializedResultValue)
2495 dataReference = serializedResultValue->data();
2496 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, callbackID));
2499 void WebPage::getContentsAsString(uint64_t callbackID)
2501 String resultString = m_mainFrame->contentsAsString();
2502 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2506 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2508 RefPtr<SharedBuffer> buffer = useBinaryEncoding
2509 ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2510 : MHTMLArchive::generateMHTMLData(m_page.get());
2512 // FIXME: Use SharedBufferDataReference.
2513 IPC::DataReference dataReference;
2515 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2516 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2520 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2522 String resultString = renderTreeExternalRepresentation();
2523 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2526 static Frame* frameWithSelection(Page* page)
2528 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2529 if (frame->selection().isRange())
2536 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2539 RetainPtr<CFDataRef> data;
2540 if (Frame* frame = frameWithSelection(m_page.get()))
2541 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
2544 IPC::DataReference dataReference;
2547 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2549 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2552 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2554 String resultString = m_mainFrame->selectionAsString();
2555 if (resultString.isEmpty())
2556 resultString = m_mainFrame->contentsAsString();
2557 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2560 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2562 String resultString;
2563 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2564 resultString = frame->source();
2566 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2569 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2571 RefPtr<SharedBuffer> buffer;
2572 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2573 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
2574 buffer = pluginView->liveResourceData();
2576 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
2577 buffer = loader->mainResourceData();
2581 // FIXME: Use SharedBufferDataReference.
2582 IPC::DataReference dataReference;
2584 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2585 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2588 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2590 DocumentLoader* loader = frame->loader().documentLoader();
2594 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2598 return subresource->data();
2601 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2603 RefPtr<SharedBuffer> buffer;
2604 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2605 URL resourceURL(URL(), resourceURLString);
2606 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2608 // Try to get the resource data from the cache.
2609 buffer = cachedResponseDataForURL(resourceURL);
2613 // FIXME: Use SharedBufferDataReference.
2614 IPC::DataReference dataReference;
2616 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2617 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2620 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2623 RetainPtr<CFDataRef> data;
2624 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2625 data = frame->webArchiveData(nullptr, nullptr);
2627 UNUSED_PARAM(frameID);
2630 IPC::DataReference dataReference;
2633 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2635 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2638 void WebPage::forceRepaintWithoutCallback()
2640 m_drawingArea->forceRepaint();
2643 void WebPage::forceRepaint(uint64_t callbackID)
2645 if (m_drawingArea->forceRepaintAsync(callbackID))
2648 forceRepaintWithoutCallback();
2649 send(Messages::WebPageProxy::VoidCallback(callbackID));
2652 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2654 WebPreferencesStore::removeTestRunnerOverrides();
2655 updatePreferences(store);
2658 void WebPage::updatePreferences(const WebPreferencesStore& store)
2660 Settings& settings = m_page->settings();
2662 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2663 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2664 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2665 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2667 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2670 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2673 // FIXME: This should be generated from macro expansion for all preferences,
2674 // but we currently don't match the naming of WebCore exactly so we are
2675 // handrolling the boolean and integer preferences until that is fixed.
2677 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2679 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2681 #undef INITIALIZE_SETTINGS
2683 settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2684 settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2685 settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2686 settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2687 settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2688 settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2689 settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));
2690 settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2691 settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2692 settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2693 settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2694 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
2695 setSessionID(SessionID::legacyPrivateSessionID());
2696 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
2697 setSessionID(SessionID::defaultSessionID());
2698 settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2699 settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
2700 settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2701 settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2702 settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2703 settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2704 settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2705 settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey()));
2706 #if ENABLE(WEB_ARCHIVE)
2707 settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2709 settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2710 settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2711 settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2712 settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2713 settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2714 settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2715 settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2716 settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2717 settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2718 settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2719 settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2721 settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2722 settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2723 settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2724 settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2725 settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2726 settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2727 settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2728 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2729 settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2731 settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2732 settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
2733 settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
2734 settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
2735 settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2736 settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2737 settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2738 settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey()));
2739 settings.setUseGiantTiles(store.getBoolValueForKey(WebPreferencesKey::useGiantTilesKey()));
2741 settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2742 settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
2743 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
2744 RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey()));
2746 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2747 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2748 settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2749 settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2750 settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2751 settings.setRequiresUserGestureForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey()));
2752 settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey()));
2753 settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute(store.getBoolValueForKey(WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey()));
2754 settings.setMediaDataLoadsAutomatically(store.getBoolValueForKey(WebPreferencesKey::mediaDataLoadsAutomaticallyKey()));
2755 settings.setAllowsPictureInPictureMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey()));
2756 settings.setMediaControlsScaleWithPageZoom(store.getBoolValueForKey(WebPreferencesKey::mediaControlsScaleWithPageZoomKey()));
2757 settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2758 settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2759 settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2760 #if ENABLE(SMOOTH_SCROLLING)
2761 settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2763 settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
2764 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2765 settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2767 settings.setHttpEquivEnabled(store.getBoolValueForKey(WebPreferencesKey::httpEquivEnabledKey()));
2769 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2771 #if ENABLE(FULLSCREEN_API)
2772 settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2775 #if USE(AVFOUNDATION)
2776 settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2780 settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2783 #if PLATFORM(IOS) && HAVE(AVKIT)
2784 settings.setAVKitEnabled(true);
2787 #if ENABLE(IOS_TEXT_AUTOSIZING)
2788 settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2791 #if ENABLE(WEB_AUDIO)
2792 settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2795 #if ENABLE(MEDIA_STREAM)
2796 settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2799 #if ENABLE(SERVICE_CONTROLS)
2800 settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2803 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2804 settings.setAllowsAirPlayForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsAirPlayForMediaPlaybackKey()));
2807 settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2808 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2809 settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2810 settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2811 settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2813 #if ENABLE(VIDEO_TRACK)
2814 settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2815 settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2816 settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2819 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2820 settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2823 settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2824 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2825 settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2827 settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2829 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2831 settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2832 settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2833 settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2834 settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2835 settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2837 #if ENABLE(TEXT_AUTOSIZING)
2838 settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2841 settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2842 settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2844 settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2845 settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2846 settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2848 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2849 settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2852 settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2853 settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2854 settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2855 settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2857 settings.setNewBlockInsideInlineModelEnabled(store.getBoolValueForKey(WebPreferencesKey::newBlockInsideInlineModelEnabledKey()));
2858 settings.setAntialiasedFontDilationEnabled(store.getBoolValueForKey(WebPreferencesKey::antialiasedFontDilationEnabledKey()));
2860 settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
2862 settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2864 #if ENABLE(MEDIA_SOURCE)
2865 settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2868 settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2870 settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2871 settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2872 settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2873 settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2875 settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2876 settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2878 settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2879 settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2881 settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2883 settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
2886 settings.setUseImageDocumentForSubframePDF(true);
2889 settings.setLongMousePressEnabled(store.getBoolValueForKey(WebPreferencesKey::longMousePressEnabledKey()));
2892 RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
2895 #if ENABLE(SERVICE_CONTROLS)
2896 settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
2899 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
2900 if (m_processSuppressionEnabled != processSuppressionEnabled) {
2901 m_processSuppressionEnabled = processSuppressionEnabled;
2902 updateUserActivity();
2905 platformPreferencesDidChange(store);
2908 m_drawingArea->updatePreferences(store);
2911 m_viewportConfiguration.setCanIgnoreScalingConstraints(store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey()));
2912 m_viewportConfiguration.setForceAlwaysUserScalable(store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
2917 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2919 layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2920 layerTransaction.setScrollOrigin(corePage()->mainFrame().view()->scrollOrigin());
2921 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2922 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2923 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2925 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2926 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
2927 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
2928 layerTransaction.setAllowsUserScaling(allowsUserScaling());
2931 layerTransaction.setScrollPosition(corePage()->mainFrame().view()->scrollPosition());
2935 void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp)
2938 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) {
2939 std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
2940 m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero();
2942 m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20));
2945 UNUSED_PARAM(timestamp);
2950 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
2954 if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
2955 m_inspector = WebInspector::create(this);
2956 return m_inspector.get();
2959 WebInspectorUI* WebPage::inspectorUI()
2964 m_inspectorUI = WebInspectorUI::create(*this);
2965 return m_inspectorUI.get();
2969 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
2971 if (!m_videoFullscreenManager)
2972 m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
2973 return m_videoFullscreenManager.get();
2976 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
2978 m_page->setAllowsMediaDocumentInlinePlayback(allows);
2982 #if ENABLE(FULLSCREEN_API)
2983 WebFullScreenManager* WebPage::fullScreenManager()
2985 if (!m_fullScreenManager)
2986 m_fullScreenManager = WebFullScreenManager::create(this);
2987 return m_fullScreenManager.get();
2991 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2993 if (m_notificationPermissionRequestManager)
2994 return m_notificationPermissionRequestManager.get();
2996 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2997 return m_notificationPermissionRequestManager.get();
3000 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
3001 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
3003 Node* node = evt->target()->toNode();
3005 Frame* frame = node->document().frame();
3008 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
3012 Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
3014 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
3015 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
3016 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
3017 // (e.g. Tab that inserts a Tab character, or Enter).
3018 return !command.isTextInsertion() && command.execute(evt);
3021 if (command.execute(evt))
3024 // Don't allow text insertion for nodes that cannot edit.
3025 if (!frame->editor().canEdit())
3028 // Don't insert null or control characters as they can result in unexpected behaviour
3029 if (evt->charCode() < ' ')
3032 return frame->editor().insertText(evt->keyEvent()->text(), evt);
3036 #if ENABLE(DRAG_SUPPORT)
3039 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
3042 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3043 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3049 case DragControllerActionEntered: {
3050 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3051 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3054 case DragControllerActionUpdated: {
3055 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3056 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3059 case DragControllerActionExited:
3060 m_page->dragController().dragExited(dragData);
3063 case DragControllerActionPerformDragOperation: {
3064 m_page->dragController().performDragOperation(dragData);
3069 ASSERT_NOT_REACHED();
3071 // DragData does not delete its platformData so we need to do that here.
3072 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3077 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const String& dragStorageName, uint32_t flags, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsHandleArray)
3080 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3084 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3086 case DragControllerActionEntered: {
3087 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3088 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3092 case DragControllerActionUpdated: {
3093 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3094 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3097 case DragControllerActionExited:
3098 m_page->dragController().dragExited(dragData);
3101 case DragControllerActionPerformDragOperation: {
3102 ASSERT(!m_pendingDropSandboxExtension);
3104 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
3105 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3106 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
3107 m_pendingDropExtensionsForFileUpload.append(extension);
3110 m_page->dragController().performDragOperation(dragData);
3112 // If we started loading a local file, the sandbox extension tracker would have adopted this
3113 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3114 m_pendingDropSandboxExtension = nullptr;
3116 m_pendingDropExtensionsForFileUpload.clear();
3121 ASSERT_NOT_REACHED();
3126 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3128 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3129 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3131 m_page->dragController().dragEnded();
3132 FrameView* view = m_page->mainFrame().view();
3135 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3136 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime(), 0);
3137 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3140 void WebPage::willPerformLoadDragDestinationAction()
3142 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
3145 void WebPage::mayPerformUploadDragDestinationAction()
3147 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3148 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3149 m_pendingDropExtensionsForFileUpload.clear();
3152 #endif // ENABLE(DRAG_SUPPORT)
3154 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3156 return m_undoStepMap.get(stepID);
3159 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3161 m_undoStepMap.set(stepID, entry);
3164 void WebPage::removeWebEditCommand(uint64_t stepID)
3166 m_undoStepMap.remove(stepID);
3169 void WebPage::unapplyEditCommand(uint64_t stepID)
3171 WebUndoStep* step = webUndoStep(stepID);
3175 step->step()->unapply();
3178 void WebPage::reapplyEditCommand(uint64_t stepID)
3180 WebUndoStep* step = webUndoStep(stepID);
3185 step->step()->reapply();
3189 void WebPage::didRemoveEditCommand(uint64_t commandID)
3191 removeWebEditCommand(commandID);
3194 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3196 m_activePopupMenu = menu;
3199 #if ENABLE(INPUT_TYPE_COLOR)
3200 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3202 m_activeColorChooser = colorChooser;
3205 void WebPage::didEndColorPicker()
3207 m_activeColorChooser->didEndChooser();
3210 void WebPage::didChooseColor(const WebCore::Color& color)
3212 m_activeColorChooser->didChooseColor(color);
3216 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
3218 m_activeOpenPanelResultListener = openPanelResultListener;
3221 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3223 return m_page->findString(target, options);
3226 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3228 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
3231 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3233 m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3236 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3238 m_findController.getImageForFindMatch(matchIndex);
3241 void WebPage::selectFindMatch(uint32_t matchIndex)
3243 m_findController.selectFindMatch(matchIndex);
3246 void WebPage::hideFindUI()
3248 m_findController.hideFindUI();
3251 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3253 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3256 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3258 changeSelectedIndex(newIndex);
3259 m_activePopupMenu = nullptr;
3262 void WebPage::changeSelectedIndex(int32_t index)
3264 if (!m_activePopupMenu)
3267 m_activePopupMenu->didChangeSelectedIndex(index);
3271 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3273 if (!m_activeOpenPanelResultListener)
3277 if (!iconData.isEmpty()) {
3278 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3279 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3280 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3281 icon = Icon::createIconForImage(imageRef.get());
3284 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3285 m_activeOpenPanelResultListener = nullptr;
3289 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3291 if (!m_activeOpenPanelResultListener)
3294 m_activeOpenPanelResultListener->didChooseFiles(files);
3295 m_activeOpenPanelResultListener = nullptr;
3298 void WebPage::didCancelForOpenPanel()
3300 m_activeOpenPanelResultListener = nullptr;
3303 #if ENABLE(SANDBOX_EXTENSIONS)
3304 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3306 bool result = SandboxExtension::consumePermanently(handle);
3308 // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3309 WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3314 #if ENABLE(GEOLOCATION)
3315 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3317 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3321 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3323 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3326 #if ENABLE(MEDIA_STREAM)
3327 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed, const String& audioDeviceUID, const String& videoDeviceUID)
3329 m_userMediaPermissionRequestManager.didReceiveUserMediaPermissionDecision(userMediaID, allowed, audioDeviceUID, videoDeviceUID);
3334 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3336 Frame& frame = m_page->focusController().focusedOrMainFrame();
3337 frame.editor().advanceToNextMisspelling(startBeforeSelection);
3341 void WebPage::changeSpellingToWord(const String& word)
3343 replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3346 void WebPage::unmarkAllMisspellings()
3348 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3349 if (Document* document = frame->document())
3350 document->markers().removeMarkers(DocumentMarker::Spelling);
3354 void WebPage::unmarkAllBadGrammar()
3356 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3357 if (Document* document = frame->document())
3358 document->markers().removeMarkers(DocumentMarker::Grammar);
3363 void WebPage::uppercaseWord()
3365 m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3368 void WebPage::lowercaseWord()
3370 m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3373 void WebPage::capitalizeWord()
3375 m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3379 void WebPage::setTextForActivePopupMenu(int32_t index)
3381 if (!m_activePopupMenu)
3384 m_activePopupMenu->setTextForIndex(index);
3388 void WebPage::failedToShowPopupMenu()
3390 if (!m_activePopupMenu)
3393 m_activePopupMenu->client()->popupDidHide();
3397 #if ENABLE(CONTEXT_MENUS)
3398 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3403 m_contextMenu->itemSelected(item);
3404 m_contextMenu = nullptr;
3408 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3410 bool selectReplacement = true;
3411 bool smartReplace = false;
3412 return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3416 void WebPage::clearSelection()
3418 m_page->focusController().focusedOrMainFrame().selection().clear();
3422 void WebPage::restoreSelectionInFocusedEditableElement()
3424 Frame& frame = m_page->focusController().focusedOrMainFrame();
3425 if (!frame.selection().isNone())
3428 if (auto document = frame.document()) {
3429 if (auto element = document->focusedElement())
3430 element->updateFocusAppearance(true /* restoreSelection */);
3434 bool WebPage::mainFrameHasCustomContentProvider() const
3436 if (Frame* frame = mainFrame()) {
3437 WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3438 ASSERT(webFrameLoaderClient);
3439 return webFrameLoaderClient->frameHasCustomContentProvider();
3445 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3447 m_mimeTypesWithCustomContentProviders.add(mimeType);
3450 void WebPage::updateMainFrameScrollOffsetPinning()
3452 Frame& frame = m_page->mainFrame();
3453 IntPoint scrollPosition = frame.view()->scrollPosition();
3454 IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3455 IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3457 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3458 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3459 bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3460 bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3462 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3463 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3465 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3466 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3467 m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3468 m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3472 void WebPage::mainFrameDidLayout()
3474 unsigned pageCount = m_page->pageCount();
3475 if (pageCount != m_cachedPageCount) {
3476 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3477 m_cachedPageCount = pageCount;
3481 m_viewGestureGeometryCollector.mainFrameDidLayout();
3484 if (FrameView* frameView = mainFrameView()) {
3485 IntSize newContentSize = frameView->contentsSizeRespectingOverflow();
3486 if (m_viewportConfiguration.contentsSize() != newContentSize) {
3487 m_viewportConfiguration.setContentsSize(newContentSize);
3488 viewportConfigurationChanged();
3491 m_findController.redraw();
3495 void WebPage::addPluginView(PluginView* pluginView)
3497 ASSERT(!m_pluginViews.contains(pluginView));
3499 m_pluginViews.add(pluginView);
3500 m_hasSeenPlugin = true;
3501 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3502 LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3503 m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3507 void WebPage::removePluginView(PluginView* pluginView)
3509 ASSERT(m_pluginViews.contains(pluginView));
3511 m_pluginViews.remove(pluginView);
3512 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3513 LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3517 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3520 m_hasCachedWindowFrame = false;
3522 send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3526 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3528 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3529 m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3530 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3531 m_accessibilityPosition = accessibilityViewCoordinates;
3533 // Tell all our plug-in views that the window and view frames have changed.
3534 for (auto* pluginView : m_pluginViews)
3535 pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3537 m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3541 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3543 m_mainFrameIsScrollable = isScrollable;