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.
31 #include "APIGeometry.h"
32 #include "Arguments.h"
33 #include "DataReference.h"
34 #include "DragControllerAction.h"
35 #include "DrawingArea.h"
36 #include "DrawingAreaMessages.h"
37 #include "EditingRange.h"
38 #include "EditorState.h"
39 #include "EventDispatcher.h"
40 #include "InjectedBundle.h"
41 #include "InjectedBundleBackForwardList.h"
42 #include "LayerTreeHost.h"
44 #include "NetscapePlugin.h"
45 #include "NotificationPermissionRequestManager.h"
46 #include "PageBanner.h"
47 #include "PluginProcessAttributes.h"
48 #include "PluginProxy.h"
49 #include "PluginView.h"
50 #include "PrintInfo.h"
51 #include "SessionState.h"
52 #include "SessionStateConversion.h"
53 #include "SessionTracker.h"
54 #include "ShareableBitmap.h"
55 #include "VisitedLinkTableController.h"
56 #include "WKBundleAPICast.h"
57 #include "WKRetainPtr.h"
58 #include "WKSharedAPICast.h"
59 #include "WebAlternativeTextClient.h"
60 #include "WebBackForwardListItem.h"
61 #include "WebBackForwardListProxy.h"
62 #include "WebChromeClient.h"
63 #include "WebColorChooser.h"
64 #include "WebContextMenu.h"
65 #include "WebContextMenuClient.h"
66 #include "WebCoreArgumentCoders.h"
67 #include "WebDatabaseProvider.h"
68 #include "WebDiagnosticLoggingClient.h"
69 #include "WebDocumentLoader.h"
70 #include "WebDragClient.h"
71 #include "WebEditorClient.h"
73 #include "WebEventConversion.h"
74 #include "WebEventFactory.h"
76 #include "WebFrameLoaderClient.h"
77 #include "WebFullScreenManager.h"
78 #include "WebFullScreenManagerMessages.h"
79 #include "WebGeolocationClient.h"
81 #include "WebInspector.h"
82 #include "WebInspectorClient.h"
83 #include "WebInspectorMessages.h"
84 #include "WebInspectorUI.h"
85 #include "WebInspectorUIMessages.h"
86 #include "WebMediaKeyStorageManager.h"
87 #include "WebNotificationClient.h"
88 #include "WebOpenPanelResultListener.h"
89 #include "WebPageCreationParameters.h"
90 #include "WebPageGroupProxy.h"
91 #include "WebPageMessages.h"
92 #include "WebPageOverlay.h"
93 #include "WebPageProxyMessages.h"
94 #include "WebPlugInClient.h"
95 #include "WebPopupMenu.h"
96 #include "WebPreferencesDefinitions.h"
97 #include "WebPreferencesKeys.h"
98 #include "WebPreferencesStore.h"
99 #include "WebProcess.h"
100 #include "WebProcessPoolMessages.h"
101 #include "WebProcessProxyMessages.h"
102 #include "WebProgressTrackerClient.h"
103 #include "WebStorageNamespaceProvider.h"
104 #include "WebUndoStep.h"
105 #include "WebUserContentController.h"
106 #include "WebUserMediaClient.h"
107 #include <JavaScriptCore/APICast.h>
108 #include <WebCore/ArchiveResource.h>
109 #include <WebCore/Chrome.h>
110 #include <WebCore/ContextMenuController.h>
111 #include <WebCore/DataTransfer.h>
112 #include <WebCore/DatabaseManager.h>
113 #include <WebCore/DocumentFragment.h>
114 #include <WebCore/DocumentLoader.h>
115 #include <WebCore/DocumentMarkerController.h>
116 #include <WebCore/DragController.h>
117 #include <WebCore/DragData.h>
118 #include <WebCore/ElementIterator.h>
119 #include <WebCore/EventHandler.h>
120 #include <WebCore/FocusController.h>
121 #include <WebCore/FormState.h>
122 #include <WebCore/FrameLoadRequest.h>
123 #include <WebCore/FrameLoaderTypes.h>
124 #include <WebCore/FrameView.h>
125 #include <WebCore/HTMLFormElement.h>
126 #include <WebCore/HTMLInputElement.h>
127 #include <WebCore/HTMLPlugInElement.h>
128 #include <WebCore/HTMLPlugInImageElement.h>
129 #include <WebCore/HistoryController.h>
130 #include <WebCore/HistoryItem.h>
131 #include <WebCore/HitTestResult.h>
132 #include <WebCore/JSDOMWindow.h>
133 #include <WebCore/KeyboardEvent.h>
134 #include <WebCore/MIMETypeRegistry.h>
135 #include <WebCore/MainFrame.h>
136 #include <WebCore/MouseEvent.h>
137 #include <WebCore/Page.h>
138 #include <WebCore/PageConfiguration.h>
139 #include <WebCore/PageThrottler.h>
140 #include <WebCore/PlatformKeyboardEvent.h>
141 #include <WebCore/PluginDocument.h>
142 #include <WebCore/PrintContext.h>
143 #include <WebCore/Range.h>
144 #include <WebCore/RenderLayer.h>
145 #include <WebCore/RenderTreeAsText.h>
146 #include <WebCore/RenderView.h>
147 #include <WebCore/ResourceRequest.h>
148 #include <WebCore/ResourceResponse.h>
149 #include <WebCore/RuntimeEnabledFeatures.h>
150 #include <WebCore/SchemeRegistry.h>
151 #include <WebCore/ScriptController.h>
152 #include <WebCore/SerializedScriptValue.h>
153 #include <WebCore/SessionID.h>
154 #include <WebCore/Settings.h>
155 #include <WebCore/ShadowRoot.h>
156 #include <WebCore/SharedBuffer.h>
157 #include <WebCore/StyleProperties.h>
158 #include <WebCore/SubframeLoader.h>
159 #include <WebCore/SubstituteData.h>
160 #include <WebCore/TextIterator.h>
161 #include <WebCore/UserInputBridge.h>
162 #include <WebCore/VisiblePosition.h>
163 #include <WebCore/VisibleUnits.h>
164 #include <WebCore/markup.h>
165 #include <bindings/ScriptValue.h>
166 #include <profiler/ProfilerDatabase.h>
167 #include <runtime/JSCInlines.h>
168 #include <runtime/JSCJSValue.h>
169 #include <runtime/JSLock.h>
170 #include <wtf/RunLoop.h>
171 #include <wtf/TemporaryChange.h>
174 #include <WebCore/MHTMLArchive.h>
177 #if ENABLE(BATTERY_STATUS)
178 #include "WebBatteryClient.h"
181 #if ENABLE(VIBRATION)
182 #include "WebVibrationClient.h"
185 #if ENABLE(PROXIMITY_EVENTS)
186 #include "WebDeviceProximityClient.h"
190 #include "PDFPlugin.h"
191 #include "RemoteLayerTreeTransaction.h"
192 #include "WKStringCF.h"
193 #include <WebCore/LegacyWebArchive.h>
198 #include "DataObjectGtk.h"
199 #include "WebPrintOperationGtk.h"
203 #include "RemoteLayerTreeDrawingArea.h"
204 #include "WebVideoFullscreenManager.h"
205 #include <CoreGraphics/CoreGraphics.h>
206 #include <WebCore/CoreTextSPI.h>
207 #include <WebCore/Icon.h>
211 #include <wtf/RefCountedLeakCounter.h>
214 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
215 #include "CoordinatedLayerTreeHostMessages.h"
219 using namespace WebCore;
223 class SendStopResponsivenessTimer {
225 SendStopResponsivenessTimer(WebPage* page)
230 ~SendStopResponsivenessTimer()
232 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
239 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
241 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
243 RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
245 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
246 WebProcess::singleton().injectedBundle()->didCreatePage(page.get());
248 return page.release();
251 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
253 , m_viewSize(parameters.viewSize)
254 , m_hasSeenPlugin(false)
255 , m_useFixedLayout(false)
256 , m_drawsBackground(true)
257 , m_drawsTransparentBackground(false)
260 , m_tabToLinks(false)
261 , m_asynchronousPluginInitializationEnabled(false)
262 , m_asynchronousPluginInitializationEnabledForAllPlugins(false)
263 , m_artificialPluginInitializationDelayEnabled(false)
264 , m_scrollingPerformanceLoggingEnabled(false)
265 , m_mainFrameIsScrollable(true)
266 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
267 , m_readyToFindPrimarySnapshottedPlugin(false)
268 , m_didFindPrimarySnapshottedPlugin(false)
269 , m_numberOfPrimarySnapshotDetectionAttempts(0)
270 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
272 , m_layerHostingMode(parameters.layerHostingMode)
274 , m_pdfPluginEnabled(false)
275 , m_hasCachedWindowFrame(false)
276 , m_viewGestureGeometryCollector(*this)
277 #elif HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL))
278 , m_accessibilityObject(nullptr)
280 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
281 #if ENABLE(CONTEXT_MENUS)
282 , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
284 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
285 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
286 , m_findController(this)
287 #if ENABLE(INPUT_TYPE_COLOR)
288 , m_activeColorChooser(0)
290 , m_userContentController(parameters.userContentControllerID ? WebUserContentController::getOrCreate(parameters.userContentControllerID) : nullptr)
291 #if ENABLE(GEOLOCATION)
292 , m_geolocationPermissionRequestManager(this)
294 #if ENABLE(MEDIA_STREAM)
295 , m_userMediaPermissionRequestManager(*this)
297 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
298 , m_canRunModal(parameters.canRunModal)
299 , m_isRunningModal(false)
300 #if ENABLE(DRAG_SUPPORT)
301 , m_isStartingDrag(false)
303 , m_cachedMainFrameIsPinnedToLeftSide(true)
304 , m_cachedMainFrameIsPinnedToRightSide(true)
305 , m_cachedMainFrameIsPinnedToTopSide(true)
306 , m_cachedMainFrameIsPinnedToBottomSide(true)
307 , m_canShortCircuitHorizontalWheelEvents(false)
308 , m_hasWheelEventHandlers(false)
309 , m_cachedPageCount(0)
310 , m_autoSizingShouldExpandToViewHeight(false)
311 #if ENABLE(CONTEXT_MENUS)
312 , m_isShowingContextMenu(false)
315 , m_selectionAnchor(Start)
316 , m_firstLayerTreeTransactionIDAfterDidCommitLoad(0)
317 , m_hasReceivedVisibleContentRectsAfterDidCommitLoad(false)
318 , m_scaleWasSetByUIProcess(false)
319 , m_userHasChangedPageScaleFactor(false)
320 , m_hasStablePageScaleFactor(true)
321 , m_userIsInteracting(false)
322 , m_hasPendingBlurNotification(false)
323 , m_useTestingViewportConfiguration(false)
324 , m_isInStableState(true)
325 , m_oldestNonStableUpdateVisibleContentRectsTimestamp(std::chrono::milliseconds::zero())
326 , m_estimatedLatency(std::chrono::milliseconds::zero())
327 , m_screenSize(parameters.screenSize)
328 , m_availableScreenSize(parameters.availableScreenSize)
329 , m_deviceOrientation(0)
330 , m_inDynamicSizeUpdate(false)
331 , m_volatilityTimer(*this, &WebPage::volatilityTimerFired)
333 , m_inspectorClient(0)
334 , m_backgroundColor(Color::white)
335 , m_maximumRenderingSuppressionToken(0)
336 , m_scrollPinningBehavior(DoNotPin)
337 , m_useAsyncScrolling(false)
338 , m_viewState(parameters.viewState)
339 , m_processSuppressionEnabled(true)
340 , m_userActivity("Process suppression disabled for page.")
341 , m_pendingNavigationID(0)
343 , m_systemWebGLPolicy(WebGLAllowCreation)
345 , m_mainFrameProgressCompleted(false)
346 , m_shouldDispatchFakeMouseMoveEvents(true)
350 m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
353 Settings::setShouldManageAudioSessionCategory(true);
356 PageConfiguration pageConfiguration;
357 pageConfiguration.chromeClient = new WebChromeClient(this);
358 #if ENABLE(CONTEXT_MENUS)
359 pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
361 pageConfiguration.editorClient = new WebEditorClient(this);
362 #if ENABLE(DRAG_SUPPORT)
363 pageConfiguration.dragClient = new WebDragClient(this);
365 pageConfiguration.backForwardClient = WebBackForwardListProxy::create(this);
366 m_inspectorClient = new WebInspectorClient(this);
367 pageConfiguration.inspectorClient = m_inspectorClient;
368 #if USE(AUTOCORRECTION_PANEL)
369 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
371 pageConfiguration.plugInClient = new WebPlugInClient(*this);
372 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
373 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
374 pageConfiguration.diagnosticLoggingClient = new WebDiagnosticLoggingClient(*this);
376 pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
377 pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
378 pageConfiguration.userContentController = m_userContentController ? &m_userContentController->userContentController() : &m_pageGroup->userContentController();
379 pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
381 m_page = std::make_unique<Page>(pageConfiguration);
383 m_drawingArea = DrawingArea::create(*this, parameters);
384 m_drawingArea->setPaintingEnabled(false);
385 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
387 #if ENABLE(ASYNC_SCROLLING)
388 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
389 if (!m_drawingArea->supportsAsyncScrolling())
390 m_useAsyncScrolling = false;
391 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
394 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
396 #if ENABLE(BATTERY_STATUS)
397 WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
399 #if ENABLE(GEOLOCATION)
400 WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
402 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
403 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
405 #if ENABLE(VIBRATION)
406 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
408 #if ENABLE(PROXIMITY_EVENTS)
409 WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this));
411 #if ENABLE(MEDIA_STREAM)
412 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
415 #if ENABLE(REMOTE_INSPECTOR)
416 m_page->setRemoteInspectionAllowed(true);
419 m_page->setCanStartMedia(false);
420 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
422 m_page->setGroupName(m_pageGroup->identifier());
423 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
425 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
428 updatePreferences(parameters.store);
429 platformInitialize();
431 setUseFixedLayout(parameters.useFixedLayout);
433 setDrawsBackground(parameters.drawsBackground);
434 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
436 setUnderlayColor(parameters.underlayColor);
438 setPaginationMode(parameters.paginationMode);
439 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
440 setPageLength(parameters.pageLength);
441 setGapBetweenPages(parameters.gapBetweenPages);
443 // If the page is created off-screen, its visibilityState should be prerender.
444 m_page->setViewState(m_viewState);
446 m_page->setIsPrerender();
447 updateUserActivity();
449 updateIsInWindow(true);
451 setMinimumLayoutSize(parameters.minimumLayoutSize);
452 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
454 setScrollPinningBehavior(parameters.scrollPinningBehavior);
455 if (parameters.scrollbarOverlayStyle)
456 m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
458 m_scrollbarOverlayStyle = WTF::Optional<ScrollbarOverlayStyle>();
460 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
462 setTopContentInset(parameters.topContentInset);
464 m_userAgent = parameters.userAgent;
466 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
468 if (!parameters.itemStates.isEmpty())
469 restoreSession(parameters.itemStates);
471 if (parameters.sessionID.isValid())
472 setSessionID(parameters.sessionID);
474 m_drawingArea->setPaintingEnabled(true);
476 setMediaVolume(parameters.mediaVolume);
478 setMuted(parameters.muted);
480 // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
481 m_page->addLayoutMilestones(DidFirstLayout | DidFirstVisuallyNonEmptyLayout);
483 auto& webProcess = WebProcess::singleton();
484 webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
486 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
487 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
488 webProcess.addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this);
490 webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
491 webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
492 #if ENABLE(FULLSCREEN_API)
493 webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
497 webPageCounter.increment();
500 #if ENABLE(ASYNC_SCROLLING)
501 if (m_useAsyncScrolling)
502 webProcess.eventDispatcher().addScrollingTreeForPage(this);
505 for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
506 m_mimeTypesWithCustomContentProviders.add(mimeType);
509 #if ENABLE(ENCRYPTED_MEDIA_V2)
510 if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
511 m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
513 m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
515 if (parameters.viewScaleFactor != 1)
516 scaleView(parameters.viewScaleFactor);
519 void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters)
521 if (m_viewState != parameters.viewState)
522 setViewState(parameters.viewState, false, Vector<uint64_t>());
523 if (m_layerHostingMode != parameters.layerHostingMode)
524 setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode));
527 void WebPage::setPageActivityState(PageActivityState::Flags activityState)
529 PageActivityState::Flags changed = m_activityState ^ activityState;
530 m_activityState = activityState;
533 updateUserActivity();
536 void WebPage::updateUserActivity()
538 // Start the activity to prevent AppNap if the page activity is in progress,
539 // the page is visible and non-idle, or process suppression is disabled.
540 if (m_activityState || !(m_viewState & ViewState::IsVisuallyIdle) || !m_processSuppressionEnabled)
541 m_userActivity.start();
543 m_userActivity.stop();
548 if (m_backForwardList)
549 m_backForwardList->detach();
553 auto& webProcess = WebProcess::singleton();
554 #if ENABLE(ASYNC_SCROLLING)
555 if (m_useAsyncScrolling)
556 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
561 m_sandboxExtensionTracker.invalidate();
563 for (auto* pluginView : m_pluginViews)
564 pluginView->webPageDestroyed();
568 m_headerBanner->detachFromPage();
570 m_footerBanner->detachFromPage();
571 #endif // !PLATFORM(IOS)
573 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
575 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
576 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
577 webProcess.removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID);
579 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
580 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
581 #if ENABLE(FULLSCREEN_API)
582 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
586 webPageCounter.decrement();
590 void WebPage::dummy(bool&)
594 IPC::Connection* WebPage::messageSenderConnection()
596 return WebProcess::singleton().parentProcessConnection();
599 uint64_t WebPage::messageSenderDestinationID()
604 #if ENABLE(CONTEXT_MENUS)
605 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient> contextMenuClient)
607 if (!contextMenuClient) {
608 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
612 m_contextMenuClient = WTF::move(contextMenuClient);
616 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* client)
618 m_editorClient.initialize(client);
621 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient> formClient)
624 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
628 m_formClient = WTF::move(formClient);
631 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client)
633 m_loaderClient.initialize(client);
635 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
636 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
637 // for backwards compatibility.
638 LayoutMilestones milestones = 0;
640 if (m_loaderClient.client().didFirstLayoutForFrame)
641 milestones |= WebCore::DidFirstLayout;
642 if (m_loaderClient.client().didFirstVisuallyNonEmptyLayoutForFrame)
643 milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
647 listenForLayoutMilestones(milestones);
650 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
652 m_policyClient.initialize(client);
655 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase* client)
657 m_resourceLoadClient.initialize(client);
660 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient> uiClient)
663 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
667 m_uiClient = WTF::move(uiClient);
670 #if ENABLE(FULLSCREEN_API)
671 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
673 m_fullScreenClient.initialize(client);
677 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase* client)
679 m_logDiagnosticMessageClient.initialize(client);
682 #if ENABLE(NETSCAPE_PLUGIN_API)
683 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
685 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
686 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
688 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
689 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
690 unsigned pluginArea = 0;
691 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
693 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
696 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin);
698 uint64_t pluginProcessToken;
699 uint32_t pluginLoadPolicy;
700 String unavailabilityDescription;
701 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)))
704 bool isBlockedPlugin = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy) == PluginModuleBlocked;
706 if (isBlockedPlugin || !pluginProcessToken) {
707 #if ENABLE(PDFKIT_PLUGIN)
708 String path = parameters.url.path();
709 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
710 RefPtr<PDFPlugin> pdfPlugin = PDFPlugin::create(frame);
711 return pdfPlugin.release();
718 if (isBlockedPlugin) {
719 bool replacementObscured = false;
720 if (is<RenderEmbeddedObject>(*pluginElement->renderer())) {
721 auto& renderObject = downcast<RenderEmbeddedObject>(*pluginElement->renderer());
722 renderObject.setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
723 replacementObscured = renderObject.isReplacementObscured();
724 renderObject.setUnavailablePluginIndicatorIsHidden(replacementObscured);
727 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
731 if (!pluginProcessToken)
734 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
735 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
738 #endif // ENABLE(NETSCAPE_PLUGIN_API)
740 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
741 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
743 return WebGLAllowCreation;
746 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
748 return WebGLAllowCreation;
752 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
754 Frame& frame = m_page->focusController().focusedOrMainFrame();
758 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
759 if (!pluginView->getSelectionString().isNull()) {
760 result.selectionIsNone = false;
761 result.selectionIsRange = true;
762 result.isInPlugin = true;
767 const VisibleSelection& selection = frame.selection().selection();
769 result.selectionIsNone = selection.isNone();
770 result.selectionIsRange = selection.isRange();
771 result.isContentEditable = selection.isContentEditable();
772 result.isContentRichlyEditable = selection.isContentRichlyEditable();
773 result.isInPasswordField = selection.isInPasswordField();
774 result.hasComposition = frame.editor().hasComposition();
775 result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange();
777 platformEditorState(frame, result, shouldIncludePostLayoutData);
782 String WebPage::renderTreeExternalRepresentation() const
784 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
787 String WebPage::renderTreeExternalRepresentationForPrinting() const
789 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
792 uint64_t WebPage::renderTreeSize() const
796 return m_page->renderTreeSize();
799 void WebPage::setTracksRepaints(bool trackRepaints)
801 if (FrameView* view = mainFrameView())
802 view->setTracksRepaints(trackRepaints);
805 bool WebPage::isTrackingRepaints() const
807 if (FrameView* view = mainFrameView())
808 return view->isTrackingRepaints();
813 void WebPage::resetTrackedRepaints()
815 if (FrameView* view = mainFrameView())
816 view->resetTrackedRepaints();
819 Ref<API::Array> WebPage::trackedRepaintRects()
821 FrameView* view = mainFrameView();
823 return API::Array::create();
825 Vector<RefPtr<API::Object>> repaintRects;
826 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
828 for (const auto& repaintRect : view->trackedRepaintRects())
829 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
831 return API::Array::create(WTF::move(repaintRects));
834 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
836 if (!frame.document()->isPluginDocument())
839 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
841 if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
844 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
848 PluginView* WebPage::pluginViewForFrame(Frame* frame)
850 if (!frame->document()->isPluginDocument())
853 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
854 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
858 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
860 Frame& frame = m_page->focusController().focusedOrMainFrame();
862 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
863 pluginView->handleEditingCommand(commandName, argument);
867 frame.editor().command(commandName).execute(argument);
870 void WebPage::setEditable(bool editable)
872 m_page->setEditable(editable);
873 m_page->setTabKeyCyclesThroughElements(!editable);
874 Frame& frame = m_page->focusController().focusedOrMainFrame();
876 frame.editor().applyEditingStyleToBodyElement();
877 // If the page is made editable and the selection is empty, set it to something.
878 if (frame.selection().isNone())
879 frame.selection().setSelectionFromNone();
883 bool WebPage::isEditingCommandEnabled(const String& commandName)
885 Frame& frame = m_page->focusController().focusedOrMainFrame();
887 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
888 return pluginView->isEditingCommandEnabled(commandName);
890 Editor::Command command = frame.editor().command(commandName);
891 return command.isSupported() && command.isEnabled();
894 void WebPage::clearMainFrameName()
896 if (Frame* frame = mainFrame())
897 frame->tree().clearName();
900 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
902 m_drawingArea->setRootCompositingLayer(layer);
905 void WebPage::exitAcceleratedCompositingMode()
907 m_drawingArea->setRootCompositingLayer(0);
910 void WebPage::close()
917 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
918 if (!mainWebFrame()->url().isEmpty())
919 reportUsedFeatures();
921 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
922 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
925 m_inspector->disconnectFromPage();
926 m_inspector = nullptr;
929 #if ENABLE(FULLSCREEN_API)
930 m_fullScreenManager = 0;
933 if (m_activePopupMenu) {
934 m_activePopupMenu->disconnectFromPage();
935 m_activePopupMenu = 0;
938 if (m_activeOpenPanelResultListener) {
939 m_activeOpenPanelResultListener->disconnectFromPage();
940 m_activeOpenPanelResultListener = 0;
943 #if ENABLE(INPUT_TYPE_COLOR)
944 if (m_activeColorChooser) {
945 m_activeColorChooser->disconnectFromPage();
946 m_activeColorChooser = 0;
951 if (m_printOperation) {
952 m_printOperation->disconnectFromPage();
953 m_printOperation = nullptr;
957 m_sandboxExtensionTracker.invalidate();
959 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
960 m_determinePrimarySnapshottedPlugInTimer.stop();
963 #if ENABLE(CONTEXT_MENUS)
964 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
966 m_editorClient.initialize(0);
967 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
968 m_loaderClient.initialize(0);
969 m_policyClient.initialize(0);
970 m_resourceLoadClient.initialize(0);
971 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
972 #if ENABLE(FULLSCREEN_API)
973 m_fullScreenClient.initialize(0);
975 m_logDiagnosticMessageClient.initialize(0);
977 m_printContext = nullptr;
978 m_mainFrame->coreFrame()->loader().detachFromParent();
980 m_drawingArea = nullptr;
982 bool isRunningModal = m_isRunningModal;
983 m_isRunningModal = false;
985 // The WebPage can be destroyed by this call.
986 WebProcess::singleton().removeWebPage(m_pageID);
989 RunLoop::main().stop();
992 void WebPage::tryClose()
994 SendStopResponsivenessTimer stopper(this);
996 if (!corePage()->userInputBridge().tryClosePage()) {
997 send(Messages::WebPageProxy::StopResponsivenessTimer());
1001 send(Messages::WebPageProxy::ClosePage(true));
1004 void WebPage::sendClose()
1006 send(Messages::WebPageProxy::ClosePage(false));
1009 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
1011 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1015 frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url)), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1018 void WebPage::loadRequest(uint64_t navigationID, const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, uint64_t shouldOpenExternalURLsPolicy, const UserData& userData)
1020 SendStopResponsivenessTimer stopper(this);
1022 m_pendingNavigationID = navigationID;
1024 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1026 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1027 // to all the client to set up any needed state.
1028 m_loaderClient.willLoadURLRequest(this, request, WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1030 // Initate the load in WebCore.
1031 FrameLoadRequest frameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1032 ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(shouldOpenExternalURLsPolicy);
1033 frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1035 corePage()->userInputBridge().loadRequest(frameLoadRequest);
1037 ASSERT(!m_pendingNavigationID);
1040 void WebPage::loadDataImpl(uint64_t navigationID, PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1042 SendStopResponsivenessTimer stopper(this);
1044 m_pendingNavigationID = navigationID;
1046 ResourceRequest request(baseURL);
1047 ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1048 SubstituteData substituteData(sharedBuffer, unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1050 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1051 // to all the client to set up any needed state.
1052 m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1054 // Initate the load in WebCore.
1055 m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData));
1058 void WebPage::loadString(uint64_t navigationID, const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1060 if (!htmlString.isNull() && htmlString.is8Bit()) {
1061 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
1062 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, userData);
1064 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
1065 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, userData);
1069 void WebPage::loadData(const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, const UserData& userData)
1071 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
1072 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1073 loadDataImpl(0, sharedBuffer, MIMEType, encodingName, baseURL, URL(), userData);
1076 void WebPage::loadHTMLString(uint64_t navigationID, const String& htmlString, const String& baseURLString, const UserData& userData)
1078 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1079 loadString(navigationID, htmlString, ASCIILiteral("text/html"), baseURL, URL(), userData);
1082 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, const String& provisionalLoadErrorURLString, const UserData& userData)
1084 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1085 URL unreachableURL = unreachableURLString.isEmpty() ? URL() : URL(URL(), unreachableURLString);
1086 URL provisionalLoadErrorURL = provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), provisionalLoadErrorURLString);
1087 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1088 loadString(0, htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, userData);
1089 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1092 void WebPage::loadPlainTextString(const String& string, const UserData& userData)
1094 loadString(0, string, ASCIILiteral("text/plain"), blankURL(), URL(), userData);
1097 void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, const UserData& userData)
1099 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
1100 loadDataImpl(0, sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), userData);
1103 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1105 Frame* mainFrame = m_mainFrame->coreFrame();
1106 Document* mainFrameDocument = mainFrame->document();
1107 if (!mainFrameDocument)
1110 const int singleClick = 1;
1111 RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, true, true, currentTime(), nullptr, singleClick, screenPoint.x(), screenPoint.y(), documentPoint.x(), documentPoint.y(), false, false, false, false, 0, nullptr, 0, nullptr);
1113 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1116 void WebPage::stopLoadingFrame(uint64_t frameID)
1118 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1122 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1125 void WebPage::stopLoading()
1127 SendStopResponsivenessTimer stopper(this);
1129 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1132 bool WebPage::defersLoading() const
1134 return m_page->defersLoading();
1137 void WebPage::setDefersLoading(bool defersLoading)
1139 m_page->setDefersLoading(defersLoading);
1142 void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
1144 SendStopResponsivenessTimer stopper(this);
1146 ASSERT(!m_pendingNavigationID);
1147 m_pendingNavigationID = navigationID;
1149 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1150 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin);
1153 void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID)
1155 SendStopResponsivenessTimer stopper(this);
1157 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1162 ASSERT(!m_pendingNavigationID);
1163 if (!item->isInPageCache())
1164 m_pendingNavigationID = navigationID;
1166 m_page->goToItem(*item, FrameLoadType::Forward);
1169 void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID)
1171 SendStopResponsivenessTimer stopper(this);
1173 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1178 ASSERT(!m_pendingNavigationID);
1179 if (!item->isInPageCache())
1180 m_pendingNavigationID = navigationID;
1182 m_page->goToItem(*item, FrameLoadType::Back);
1185 void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID)
1187 SendStopResponsivenessTimer stopper(this);
1189 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1194 ASSERT(!m_pendingNavigationID);
1195 if (!item->isInPageCache())
1196 m_pendingNavigationID = navigationID;
1198 m_page->goToItem(*item, FrameLoadType::IndexedBackForward);
1201 void WebPage::tryRestoreScrollPosition()
1203 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1206 void WebPage::layoutIfNeeded()
1208 if (m_mainFrame->coreFrame()->view())
1209 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1212 WebPage* WebPage::fromCorePage(Page* page)
1214 return static_cast<WebChromeClient&>(page->chrome().client()).page();
1217 void WebPage::setSize(const WebCore::IntSize& viewSize)
1219 if (m_viewSize == viewSize)
1222 FrameView* view = m_page->mainFrame().view();
1223 view->resize(viewSize);
1224 m_drawingArea->setNeedsDisplay();
1226 m_viewSize = viewSize;
1228 #if USE(COORDINATED_GRAPHICS)
1229 if (view->useFixedLayout())
1230 sendViewportAttributesChanged();
1234 #if USE(COORDINATED_GRAPHICS)
1235 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1237 ASSERT(m_useFixedLayout);
1239 m_page->mainFrame().view()->setFixedVisibleContentRect(rect);
1242 void WebPage::sendViewportAttributesChanged()
1244 ASSERT(m_useFixedLayout);
1246 // Viewport properties have no impact on zero sized fixed viewports.
1247 if (m_viewSize.isEmpty())
1250 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1251 Settings& settings = m_page->settings();
1253 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1255 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1256 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1257 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1259 ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1261 FrameView* view = m_page->mainFrame().view();
1263 // If no layout was done yet set contentFixedOrigin to (0,0).
1264 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1266 // Put the width and height to the viewport width and height. In css units however.
1267 // Use FloatSize to avoid truncated values during scale.
1268 FloatSize contentFixedSize = m_viewSize;
1270 #if ENABLE(CSS_DEVICE_ADAPTATION)
1271 // CSS viewport descriptors might be applied to already affected viewport size
1272 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1273 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1276 contentFixedSize.scale(1 / attr.initialScale);
1277 setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1279 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1281 // This also takes care of the relayout.
1282 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1284 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
1285 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1287 if (m_drawingArea->layerTreeHost())
1288 m_drawingArea->layerTreeHost()->didChangeViewportProperties(attr);
1293 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1295 FrameView* frameView = m_page->mainFrame().view();
1297 IntPoint scrollPosition = frameView->scrollPosition();
1298 IntPoint maximumScrollPosition = frameView->maximumScrollPosition();
1300 // If the current scroll position in a direction is the max scroll position
1301 // we don't want to scroll at all.
1302 IntSize newScrollOffset;
1303 if (scrollPosition.x() < maximumScrollPosition.x())
1304 newScrollOffset.setWidth(scrollOffset.width());
1305 if (scrollPosition.y() < maximumScrollPosition.y())
1306 newScrollOffset.setHeight(scrollOffset.height());
1308 if (newScrollOffset.isZero())
1311 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1314 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1316 GraphicsContextStateSaver stateSaver(graphicsContext);
1317 graphicsContext.clip(rect);
1319 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1322 double WebPage::textZoomFactor() const
1324 Frame* frame = m_mainFrame->coreFrame();
1327 return frame->textZoomFactor();
1330 void WebPage::setTextZoomFactor(double zoomFactor)
1332 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1333 if (pluginView && pluginView->handlesPageScaleFactor())
1336 Frame* frame = m_mainFrame->coreFrame();
1339 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1342 double WebPage::pageZoomFactor() const
1344 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1345 if (pluginView && pluginView->handlesPageScaleFactor())
1346 return pluginView->pageScaleFactor();
1348 Frame* frame = m_mainFrame->coreFrame();
1351 return frame->pageZoomFactor();
1354 void WebPage::setPageZoomFactor(double zoomFactor)
1356 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1357 if (pluginView && pluginView->handlesPageScaleFactor()) {
1358 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1362 Frame* frame = m_mainFrame->coreFrame();
1365 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1368 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1370 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1371 if (pluginView && pluginView->handlesPageScaleFactor()) {
1372 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1376 Frame* frame = m_mainFrame->coreFrame();
1379 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1382 void WebPage::windowScreenDidChange(uint32_t displayID)
1384 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1387 void WebPage::scalePage(double scale, const IntPoint& origin)
1389 double totalScale = scale * viewScaleFactor();
1390 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1393 if (willChangeScaleFactor) {
1394 if (!m_inDynamicSizeUpdate)
1395 m_dynamicSizeUpdateHistory.clear();
1396 m_scaleWasSetByUIProcess = false;
1399 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1400 if (pluginView && pluginView->handlesPageScaleFactor()) {
1401 pluginView->setPageScaleFactor(totalScale, origin);
1405 m_page->setPageScaleFactor(totalScale, origin);
1407 // We can't early return before setPageScaleFactor because the origin might be different.
1408 if (!willChangeScaleFactor)
1411 for (auto* pluginView : m_pluginViews)
1412 pluginView->pageScaleFactorDidChange();
1414 if (m_drawingArea->layerTreeHost())
1415 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1417 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1420 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1422 double totalScale = scale * viewScaleFactor();
1423 if (totalScale == totalScaleFactor())
1426 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1427 double scaleRatio = scale / pageScaleFactor();
1428 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1429 scalePage(scale, scrollPositionAtNewScale);
1432 double WebPage::totalScaleFactor() const
1434 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1435 if (pluginView && pluginView->handlesPageScaleFactor())
1436 return pluginView->pageScaleFactor();
1438 return m_page->pageScaleFactor();
1441 double WebPage::pageScaleFactor() const
1443 return totalScaleFactor() / viewScaleFactor();
1446 double WebPage::viewScaleFactor() const
1448 return m_page->viewScaleFactor();
1451 void WebPage::scaleView(double scale)
1453 if (viewScaleFactor() == scale)
1456 float pageScale = pageScaleFactor();
1458 IntPoint scrollPositionAtNewScale;
1459 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1460 double scaleRatio = scale / viewScaleFactor();
1461 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1462 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1465 m_page->setViewScaleFactor(scale);
1466 scalePage(pageScale, scrollPositionAtNewScale);
1470 void WebPage::scaleViewAndUpdateGeometryFenced(double scale, IntSize viewSize, uint64_t callbackID)
1473 m_drawingArea->updateGeometry(viewSize, IntSize(), false);
1474 m_drawingArea->replyWithFenceAfterNextFlush(callbackID);
1478 void WebPage::setDeviceScaleFactor(float scaleFactor)
1480 if (scaleFactor == m_page->deviceScaleFactor())
1483 m_page->setDeviceScaleFactor(scaleFactor);
1485 // Tell all our plug-in views that the device scale factor changed.
1487 for (auto* pluginView : m_pluginViews)
1488 pluginView->setDeviceScaleFactor(scaleFactor);
1490 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1493 if (m_findController.isShowingOverlay()) {
1494 // We must have updated layout to get the selection rects right.
1496 m_findController.deviceScaleFactorDidChange();
1499 if (m_drawingArea->layerTreeHost())
1500 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1503 float WebPage::deviceScaleFactor() const
1505 return m_page->deviceScaleFactor();
1508 void WebPage::setUseFixedLayout(bool fixed)
1510 // Do not overwrite current settings if initially setting it to false.
1511 if (m_useFixedLayout == fixed)
1513 m_useFixedLayout = fixed;
1516 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1518 #if USE(COORDINATED_GRAPHICS)
1519 m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1520 m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1521 m_page->settings().setDelegatesPageScaling(fixed);
1522 m_page->settings().setScrollingCoordinatorEnabled(fixed);
1525 #if USE(COORDINATED_GRAPHICS) && ENABLE(SMOOTH_SCROLLING)
1526 // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1527 // Ensure we don't do animated scrolling in the WebProcess in that case.
1528 m_page->settings().setScrollAnimatorEnabled(!fixed);
1531 FrameView* view = mainFrameView();
1535 #if USE(COORDINATED_GRAPHICS)
1536 view->setDelegatesScrolling(fixed);
1537 view->setPaintsEntireContents(fixed);
1539 view->setUseFixedLayout(fixed);
1541 setFixedLayoutSize(IntSize());
1544 void WebPage::setFixedLayoutSize(const IntSize& size)
1546 FrameView* view = mainFrameView();
1547 if (!view || view->fixedLayoutSize() == size)
1550 view->setFixedLayoutSize(size);
1553 IntSize WebPage::fixedLayoutSize() const
1555 FrameView* view = mainFrameView();
1558 return view->fixedLayoutSize();
1561 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1565 m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1568 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1570 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1573 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1575 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1578 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1580 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1583 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1585 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1586 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1589 void WebPage::setPaginationMode(uint32_t mode)
1591 Pagination pagination = m_page->pagination();
1592 pagination.mode = static_cast<Pagination::Mode>(mode);
1593 m_page->setPagination(pagination);
1596 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1598 Pagination pagination = m_page->pagination();
1599 pagination.behavesLikeColumns = behavesLikeColumns;
1600 m_page->setPagination(pagination);
1603 void WebPage::setPageLength(double pageLength)
1605 Pagination pagination = m_page->pagination();
1606 pagination.pageLength = pageLength;
1607 m_page->setPagination(pagination);
1610 void WebPage::setGapBetweenPages(double gap)
1612 Pagination pagination = m_page->pagination();
1613 pagination.gap = gap;
1614 m_page->setPagination(pagination);
1617 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1619 auto& webProcess = WebProcess::singleton();
1620 InjectedBundle* injectedBundle = webProcess.injectedBundle();
1621 if (!injectedBundle)
1624 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1628 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1631 m_headerBanner->detachFromPage();
1633 m_headerBanner = pageBanner;
1636 m_headerBanner->addToPage(PageBanner::Header, this);
1639 PageBanner* WebPage::headerPageBanner()
1641 return m_headerBanner.get();
1644 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1647 m_footerBanner->detachFromPage();
1649 m_footerBanner = pageBanner;
1652 m_footerBanner->addToPage(PageBanner::Footer, this);
1655 PageBanner* WebPage::footerPageBanner()
1657 return m_footerBanner.get();
1660 void WebPage::hidePageBanners()
1663 m_headerBanner->hide();
1665 m_footerBanner->hide();
1668 void WebPage::showPageBanners()
1671 m_headerBanner->showIfHidden();
1673 m_footerBanner->showIfHidden();
1675 #endif // !PLATFORM(IOS)
1677 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1679 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1680 snapshotOptions |= SnapshotOptionsShareable;
1682 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1684 ShareableBitmap::Handle handle;
1686 image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly);
1688 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1691 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1693 IntRect snapshotRect = rect;
1694 IntSize bitmapSize = snapshotRect.size();
1695 double scaleFactor = additionalScaleFactor;
1696 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1697 scaleFactor *= corePage()->deviceScaleFactor();
1698 bitmapSize.scale(scaleFactor);
1700 return snapshotAtSize(rect, bitmapSize, options);
1703 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1705 Frame* coreFrame = m_mainFrame->coreFrame();
1709 FrameView* frameView = coreFrame->view();
1713 IntRect snapshotRect = rect;
1714 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1715 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1716 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1718 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1719 if (!snapshot->bitmap())
1722 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1724 Color backgroundColor = coreFrame->settings().backgroundShouldExtendBeyondPage() ? frameView->documentBackgroundColor() : frameView->baseBackgroundColor();
1725 graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor, ColorSpaceDeviceRGB);
1727 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1728 double deviceScaleFactor = corePage()->deviceScaleFactor();
1729 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1730 scaleFactor /= deviceScaleFactor;
1733 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1734 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1736 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1737 if (options & SnapshotOptionsExcludeSelectionHighlighting)
1738 shouldPaintSelection = FrameView::ExcludeSelection;
1740 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1741 if (options & SnapshotOptionsInViewCoordinates)
1742 coordinateSpace = FrameView::ViewCoordinates;
1744 frameView->paintContentsForSnapshot(graphicsContext.get(), snapshotRect, shouldPaintSelection, coordinateSpace);
1746 if (options & SnapshotOptionsPaintSelectionRectangle) {
1747 FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1748 graphicsContext->setStrokeColor(Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
1749 graphicsContext->strokeRect(selectionRectangle, 1);
1752 return snapshot.release();
1755 PassRefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
1757 Frame* coreFrame = m_mainFrame->coreFrame();
1761 FrameView* frameView = coreFrame->view();
1765 if (!node.renderer())
1768 LayoutRect topLevelRect;
1769 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
1770 if (snapshotRect.isEmpty())
1773 double scaleFactor = 1;
1774 IntSize snapshotSize = snapshotRect.size();
1775 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
1776 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
1777 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
1778 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
1781 RefPtr<WebImage> snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options));
1782 if (!snapshot->bitmap())
1785 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1787 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1788 double deviceScaleFactor = corePage()->deviceScaleFactor();
1789 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1790 scaleFactor /= deviceScaleFactor;
1793 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1794 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1796 Color savedBackgroundColor = frameView->baseBackgroundColor();
1797 frameView->setBaseBackgroundColor(Color::transparent);
1798 frameView->setNodeToDraw(&node);
1800 frameView->paintContentsForSnapshot(graphicsContext.get(), snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
1802 frameView->setBaseBackgroundColor(savedBackgroundColor);
1803 frameView->setNodeToDraw(nullptr);
1805 return snapshot.release();
1808 void WebPage::pageDidScroll()
1811 if (!m_inDynamicSizeUpdate)
1812 m_dynamicSizeUpdateHistory.clear();
1814 m_uiClient->pageDidScroll(this);
1816 send(Messages::WebPageProxy::PageDidScroll());
1819 #if USE(COORDINATED_GRAPHICS)
1820 void WebPage::pageDidRequestScroll(const IntPoint& point)
1822 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
1823 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1824 #elif USE(COORDINATED_GRAPHICS_THREADED)
1825 drawingArea()->scroll(IntRect(point, IntSize()), IntSize());
1830 #if ENABLE(CONTEXT_MENUS)
1831 WebContextMenu* WebPage::contextMenu()
1834 m_contextMenu = WebContextMenu::create(this);
1835 return m_contextMenu.get();
1838 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1840 corePage()->contextMenuController().clearContextMenu();
1842 // Simulate a mouse click to generate the correct menu.
1843 PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick);
1844 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
1848 return contextMenu();
1854 static const WebEvent* g_currentEvent = 0;
1856 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1857 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1858 // platform events passed to the event handler code.
1859 const WebEvent* WebPage::currentEvent()
1861 return g_currentEvent;
1864 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
1866 auto* drawingArea = this->drawingArea();
1870 drawingArea->setLayerTreeStateIsFrozen(frozen);
1873 bool WebPage::markLayersVolatileImmediatelyIfPossible()
1875 auto* drawingArea = this->drawingArea();
1879 return drawingArea->markLayersVolatileImmediatelyIfPossible();
1882 class CurrentEvent {
1884 explicit CurrentEvent(const WebEvent& event)
1885 : m_previousCurrentEvent(g_currentEvent)
1887 g_currentEvent = &event;
1892 g_currentEvent = m_previousCurrentEvent;
1896 const WebEvent* m_previousCurrentEvent;
1899 #if ENABLE(CONTEXT_MENUS)
1900 static bool isContextClick(const PlatformMouseEvent& event)
1903 return WebEventFactory::shouldBeHandledAsContextClick(event);
1905 return event.button() == WebCore::RightButton;
1909 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1911 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
1912 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
1914 Frame* frame = &page->corePage()->mainFrame();
1915 if (result.innerNonSharedNode())
1916 frame = result.innerNonSharedNode()->document().frame();
1918 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
1920 page->contextMenu()->show();
1926 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1928 Frame& frame = page->corePage()->mainFrame();
1932 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1934 switch (platformMouseEvent.type()) {
1935 case PlatformEvent::MousePressed: {
1936 #if ENABLE(CONTEXT_MENUS)
1937 if (isContextClick(platformMouseEvent))
1938 page->corePage()->contextMenuController().clearContextMenu();
1941 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
1942 #if ENABLE(CONTEXT_MENUS)
1943 if (isContextClick(platformMouseEvent))
1944 handled = handleContextMenuEvent(platformMouseEvent, page);
1948 case PlatformEvent::MouseReleased:
1949 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
1951 case PlatformEvent::MouseMoved:
1952 if (onlyUpdateScrollbars)
1953 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
1954 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
1956 case PlatformEvent::MouseForceChanged:
1957 case PlatformEvent::MouseForceDown:
1958 case PlatformEvent::MouseForceUp:
1959 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
1962 ASSERT_NOT_REACHED();
1967 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1969 m_page->pageThrottler().didReceiveUserInput();
1971 bool shouldHandleEvent = true;
1973 #if ENABLE(CONTEXT_MENUS)
1974 // Don't try to handle any pending mouse events if a context menu is showing.
1975 if (m_isShowingContextMenu)
1976 shouldHandleEvent = false;
1978 #if ENABLE(DRAG_SUPPORT)
1979 if (m_isStartingDrag)
1980 shouldHandleEvent = false;
1983 if (!shouldHandleEvent) {
1984 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1988 bool handled = false;
1991 if (!handled && m_headerBanner)
1992 handled = m_headerBanner->mouseEvent(mouseEvent);
1993 if (!handled && m_footerBanner)
1994 handled = m_footerBanner->mouseEvent(mouseEvent);
1995 #endif // !PLATFORM(IOS)
1997 if (!handled && canHandleUserEvents()) {
1998 CurrentEvent currentEvent(mouseEvent);
2000 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2001 // button is currently pressed. It is possible that neither of those things will be true since on
2002 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2003 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2004 // efficient scrollbars-only version of the event.
2005 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
2006 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
2009 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2012 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
2014 #if ENABLE(DRAG_SUPPORT)
2015 if (m_isStartingDrag)
2016 messageSenderConnection()->waitForAndDispatchImmediately<Messages::WebPage::DidStartDrag>(messageSenderDestinationID(), std::chrono::seconds(60));
2021 if (!handled && m_headerBanner)
2022 handled = m_headerBanner->mouseEvent(mouseEvent);
2023 if (!handled && m_footerBanner)
2024 handled = m_footerBanner->mouseEvent(mouseEvent);
2025 #endif // !PLATFORM(IOS)
2028 CurrentEvent currentEvent(mouseEvent);
2030 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2031 // button is currently pressed. It is possible that neither of those things will be true since on
2032 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2033 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2034 // efficient scrollbars-only version of the event.
2035 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
2036 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
2040 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2042 Frame& frame = page->mainFrame();
2046 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2047 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2050 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2052 m_page->pageThrottler().didReceiveUserInput();
2054 bool handled = false;
2056 if (canHandleUserEvents()) {
2057 CurrentEvent currentEvent(wheelEvent);
2059 handled = handleWheelEvent(wheelEvent, m_page.get());
2061 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2064 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
2066 CurrentEvent currentEvent(wheelEvent);
2068 if (ScrollingCoordinator* scrollingCoordinator = m_page->scrollingCoordinator())
2069 scrollingCoordinator->commitTreeStateIfNeeded();
2071 handled = handleWheelEvent(wheelEvent, m_page.get());
2074 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2076 if (!page->mainFrame().view())
2079 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2080 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2081 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2084 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2086 m_page->pageThrottler().didReceiveUserInput();
2088 bool handled = false;
2090 if (canHandleUserEvents()) {
2091 CurrentEvent currentEvent(keyboardEvent);
2093 handled = handleKeyEvent(keyboardEvent, m_page.get());
2094 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2096 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2098 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2101 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
2103 CurrentEvent currentEvent(keyboardEvent);
2105 Frame& frame = m_page->focusController().focusedOrMainFrame();
2106 frame.document()->updateStyleIfNeeded();
2108 handled = handleKeyEvent(keyboardEvent, m_page.get());
2110 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2113 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
2115 bool isEnabled = false;
2117 Frame& frame = m_page->focusController().focusedOrMainFrame();
2118 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2119 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2121 Editor::Command command = frame.editor().command(commandName);
2122 state = command.state();
2123 isEnabled = command.isSupported() && command.isEnabled();
2126 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2129 void WebPage::executeEditCommand(const String& commandName)
2131 executeEditingCommand(commandName, String());
2134 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2136 for (const auto& itemState : itemStates)
2137 WebBackForwardListProxy::addItemFromUIProcess(itemState.identifier, toHistoryItem(itemState.pageState), m_pageID);
2140 #if ENABLE(TOUCH_EVENTS)
2141 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2143 if (!page->mainFrame().view())
2146 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2150 #if ENABLE(IOS_TOUCH_EVENTS)
2151 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2153 RefPtr<Frame> oldFocusedFrame = m_page->focusController().focusedFrame();
2154 RefPtr<Element> oldFocusedElement = oldFocusedFrame ? oldFocusedFrame->document()->focusedElement() : nullptr;
2155 m_userIsInteracting = true;
2157 m_lastInteractionLocation = touchEvent.position();
2158 CurrentEvent currentEvent(touchEvent);
2159 handled = handleTouchEvent(touchEvent, m_page.get());
2161 RefPtr<Frame> newFocusedFrame = m_page->focusController().focusedFrame();
2162 RefPtr<Element> newFocusedElement = newFocusedFrame ? newFocusedFrame->document()->focusedElement() : nullptr;
2164 // If the focus has not changed, we need to notify the client anyway, since it might be
2165 // necessary to start assisting the node.
2166 // If the node has been focused by JavaScript without user interaction, the
2167 // keyboard is not on screen.
2168 if (newFocusedElement && newFocusedElement == oldFocusedElement)
2169 elementDidFocus(newFocusedElement.get());
2171 m_userIsInteracting = false;
2174 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2176 EventDispatcher::TouchEventQueue queuedEvents;
2177 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2178 dispatchAsynchronousTouchEvents(queuedEvents);
2180 dispatchTouchEvent(touchEvent, handled);
2182 #elif ENABLE(TOUCH_EVENTS)
2183 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2186 bool handled = false;
2187 if (canHandleUserEvents()) {
2188 CurrentEvent currentEvent(touchEvent);
2190 handled = handleTouchEvent(touchEvent, m_page.get());
2192 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2195 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
2197 CurrentEvent currentEvent(touchEvent);
2198 handled = handleTouchEvent(touchEvent, m_page.get());
2202 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2204 return page->userInputBridge().scrollRecursively(direction, granularity);
2207 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2209 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2212 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2214 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2217 void WebPage::centerSelectionInVisibleArea()
2219 Frame& frame = m_page->focusController().focusedOrMainFrame();
2220 frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
2221 m_findController.showFindIndicatorInSelection();
2224 #if ENABLE(REMOTE_INSPECTOR)
2225 void WebPage::setAllowsRemoteInspection(bool allow)
2227 m_page->setRemoteInspectionAllowed(allow);
2231 void WebPage::setDrawsBackground(bool drawsBackground)
2233 if (m_drawsBackground == drawsBackground)
2236 m_drawsBackground = drawsBackground;
2238 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2239 if (FrameView* view = coreFrame->view())
2240 view->setTransparent(!drawsBackground);
2243 m_drawingArea->pageBackgroundTransparencyChanged();
2244 m_drawingArea->setNeedsDisplay();
2247 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
2249 if (m_drawsTransparentBackground == drawsTransparentBackground)
2252 m_drawsTransparentBackground = drawsTransparentBackground;
2254 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2255 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2256 if (FrameView* view = coreFrame->view())
2257 view->setBaseBackgroundColor(backgroundColor);
2260 m_drawingArea->pageBackgroundTransparencyChanged();
2261 m_drawingArea->setNeedsDisplay();
2264 void WebPage::setTopContentInset(float contentInset)
2266 if (contentInset == m_page->topContentInset())
2269 m_page->setTopContentInset(contentInset);
2271 for (auto* pluginView : m_pluginViews)
2272 pluginView->topContentInsetDidChange();
2275 void WebPage::viewWillStartLiveResize()
2280 // FIXME: This should propagate to all ScrollableAreas.
2281 Frame& frame = m_page->focusController().focusedOrMainFrame();
2282 if (FrameView* view = frame.view())
2283 view->willStartLiveResize();
2286 void WebPage::viewWillEndLiveResize()
2291 // FIXME: This should propagate to all ScrollableAreas.
2292 Frame& frame = m_page->focusController().focusedOrMainFrame();
2293 if (FrameView* view = frame.view())
2294 view->willEndLiveResize();
2297 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, uint64_t callbackID)
2303 TemporaryChange<bool> userIsInteractingChange { m_userIsInteracting, true };
2306 Frame& frame = m_page->focusController().focusedOrMainFrame();
2307 frame.document()->setFocusedElement(0);
2309 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2310 PlatformKeyboardEvent platformEvent(platform(event));
2311 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2312 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2314 send(Messages::WebPageProxy::VoidCallback(callbackID));
2318 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2319 send(Messages::WebPageProxy::VoidCallback(callbackID));
2322 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
2324 if (m_windowResizerSize == windowResizerSize)
2327 m_windowResizerSize = windowResizerSize;
2329 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2330 FrameView* view = coreFrame->view();
2332 view->windowResizerRectChanged();
2336 void WebPage::setCanStartMediaTimerFired()
2339 m_page->setCanStartMedia(true);
2342 inline bool WebPage::canHandleUserEvents() const
2344 #if USE(COORDINATED_GRAPHICS)
2345 // Should apply only if the area was frozen by didStartPageTransition().
2346 return !m_drawingArea->layerTreeStateIsFrozen();
2351 void WebPage::updateIsInWindow(bool isInitialState)
2353 bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2356 m_setCanStartMediaTimer.stop();
2357 m_page->setCanStartMedia(false);
2359 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2360 if (!isInitialState)
2361 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2363 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2364 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2365 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2366 if (m_mayStartMediaWhenInWindow)
2367 m_setCanStartMediaTimer.startOneShot(0);
2369 WebProcess::singleton().pageDidEnterWindow(m_pageID);
2376 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState, const Vector<uint64_t>& callbackIDs)
2378 ViewState::Flags changed = m_viewState ^ viewState;
2379 m_viewState = viewState;
2382 updateUserActivity();
2384 m_page->setViewState(viewState);
2385 for (auto* pluginView : m_pluginViews)
2386 pluginView->viewStateDidChange(changed);
2388 m_drawingArea->viewStateDidChange(changed, wantsDidUpdateViewState, callbackIDs);
2390 if (changed & ViewState::IsInWindow)
2394 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2396 m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2398 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2400 for (auto* pluginView : m_pluginViews)
2401 pluginView->setLayerHostingMode(m_layerHostingMode);
2404 void WebPage::setSessionID(SessionID sessionID)
2406 if (sessionID.isEphemeral())
2407 WebProcess::singleton().ensurePrivateBrowsingSession(sessionID);
2408 m_page->setSessionID(sessionID);
2411 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, uint64_t downloadID)
2413 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2416 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID);
2419 void WebPage::didStartPageTransition()
2421 m_drawingArea->setLayerTreeStateIsFrozen(true);
2424 void WebPage::didCompletePageTransition()
2426 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
2427 // m_mainFrame can be null since r170163.
2428 if (m_mainFrame && m_mainFrame->coreFrame()->view()->delegatesScrolling()) {
2429 // Wait until the UI process sent us the visible rect it wants rendered.
2430 send(Messages::WebPageProxy::PageTransitionViewportReady());
2434 m_drawingArea->setLayerTreeStateIsFrozen(false);
2437 void WebPage::show()
2439 send(Messages::WebPageProxy::ShowPage());
2442 String WebPage::userAgent(const URL& webCoreURL) const
2444 return userAgent(nullptr, webCoreURL);
2447 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2449 if (frame && m_loaderClient.client().userAgentForURL) {
2450 API::String* apiString = m_loaderClient.userAgentForURL(frame, API::URL::create(webcoreURL).ptr());
2452 return apiString->string();
2455 String userAgent = platformUserAgent(webcoreURL);
2456 if (!userAgent.isEmpty())
2461 void WebPage::setUserAgent(const String& userAgent)
2463 m_userAgent = userAgent;
2466 void WebPage::suspendActiveDOMObjectsAndAnimations()
2468 m_page->suspendActiveDOMObjectsAndAnimations();
2471 void WebPage::resumeActiveDOMObjectsAndAnimations()
2473 m_page->resumeActiveDOMObjectsAndAnimations();
2476 IntPoint WebPage::screenToRootView(const IntPoint& point)
2478 IntPoint windowPoint;
2479 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2483 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2486 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2491 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2493 IntPoint windowPoint;
2494 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2498 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2501 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2506 IntRect WebPage::windowResizerRect() const
2508 if (m_windowResizerSize.isEmpty())
2511 IntSize frameViewSize;
2512 if (Frame* coreFrame = m_mainFrame->coreFrame()) {
2513 if (FrameView* view = coreFrame->view())
2514 frameViewSize = view->size();
2517 return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(),
2518 m_windowResizerSize.width(), m_windowResizerSize.height());
2521 KeyboardUIMode WebPage::keyboardUIMode()
2523 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
2524 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2527 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2529 // NOTE: We need to be careful when running scripts that the objects we depend on don't
2530 // disappear during script execution.
2532 RefPtr<SerializedScriptValue> serializedResultValue;
2533 JSLockHolder lock(JSDOMWindow::commonVM());
2534 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) {
2535 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
2536 toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr);
2539 IPC::DataReference dataReference;
2540 if (serializedResultValue)
2541 dataReference = serializedResultValue->data();
2542 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2545 void WebPage::getContentsAsString(uint64_t callbackID)
2547 String resultString = m_mainFrame->contentsAsString();
2548 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2552 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2554 RefPtr<SharedBuffer> buffer = useBinaryEncoding
2555 ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2556 : MHTMLArchive::generateMHTMLData(m_page.get());
2558 // FIXME: Use SharedBufferDataReference.
2559 IPC::DataReference dataReference;
2561 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2562 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2566 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2568 String resultString = renderTreeExternalRepresentation();
2569 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2572 static Frame* frameWithSelection(Page* page)
2574 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2575 if (frame->selection().isRange())
2582 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2585 RetainPtr<CFDataRef> data;
2586 if (Frame* frame = frameWithSelection(m_page.get()))
2587 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
2590 IPC::DataReference dataReference;
2593 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2595 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2598 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2600 String resultString = m_mainFrame->selectionAsString();
2601 if (resultString.isEmpty())
2602 resultString = m_mainFrame->contentsAsString();
2603 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2606 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2608 String resultString;
2609 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2610 resultString = frame->source();
2612 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2615 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2617 RefPtr<SharedBuffer> buffer;
2618 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2619 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
2620 buffer = pluginView->liveResourceData();
2622 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
2623 buffer = loader->mainResourceData();
2627 // FIXME: Use SharedBufferDataReference.
2628 IPC::DataReference dataReference;
2630 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2631 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2634 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2636 DocumentLoader* loader = frame->loader().documentLoader();
2640 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2644 return subresource->data();
2647 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2649 RefPtr<SharedBuffer> buffer;
2650 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2651 URL resourceURL(URL(), resourceURLString);
2652 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2654 // Try to get the resource data from the cache.
2655 buffer = cachedResponseDataForURL(resourceURL);
2659 // FIXME: Use SharedBufferDataReference.
2660 IPC::DataReference dataReference;
2662 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2663 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2666 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2669 RetainPtr<CFDataRef> data;
2670 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2671 data = frame->webArchiveData(nullptr, nullptr);
2673 UNUSED_PARAM(frameID);
2676 IPC::DataReference dataReference;
2679 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2681 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2684 void WebPage::forceRepaintWithoutCallback()
2686 m_drawingArea->forceRepaint();
2689 void WebPage::forceRepaint(uint64_t callbackID)
2691 if (m_drawingArea->forceRepaintAsync(callbackID))
2694 forceRepaintWithoutCallback();
2695 send(Messages::WebPageProxy::VoidCallback(callbackID));
2698 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2700 WebPreferencesStore::removeTestRunnerOverrides();
2701 updatePreferences(store);
2704 void WebPage::updatePreferences(const WebPreferencesStore& store)
2706 Settings& settings = m_page->settings();
2708 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2709 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2710 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2711 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2713 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2716 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2719 // FIXME: This should be generated from macro expansion for all preferences,
2720 // but we currently don't match the naming of WebCore exactly so we are
2721 // handrolling the boolean and integer preferences until that is fixed.
2723 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2725 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2727 #undef INITIALIZE_SETTINGS
2729 settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2730 settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2731 settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2732 settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2733 settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2734 settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2735 settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));
2736 settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2737 settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2738 settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2739 settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2740 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
2741 setSessionID(SessionID::legacyPrivateSessionID());
2742 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
2743 setSessionID(SessionID::defaultSessionID());
2744 settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2745 settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
2746 settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2747 settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2748 settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2749 settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2750 settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2751 settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey()));
2752 #if ENABLE(WEB_ARCHIVE)
2753 settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2755 settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2756 settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2757 settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2758 settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2759 settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2760 settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2761 settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2762 settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2763 settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2764 settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2765 settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2767 settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2768 settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2769 settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2770 settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2771 settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2772 settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2773 settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2774 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2775 settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2777 settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2778 settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
2779 settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
2780 settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
2781 settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2782 settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2783 settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2784 settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey()));
2786 settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2787 settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
2788 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
2789 RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey()));
2791 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2792 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2793 settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2794 settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2795 settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2796 settings.setRequiresUserGestureForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey()));
2797 settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey()));
2798 settings.setAllowsAlternateFullscreen(store.getBoolValueForKey(WebPreferencesKey::allowsAlternateFullscreenKey()));
2799 settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2800 settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2801 settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2802 #if ENABLE(SMOOTH_SCROLLING)
2803 settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2805 settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
2806 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2807 settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2809 settings.setMetaRefreshEnabled(store.getBoolValueForKey(WebPreferencesKey::metaRefreshEnabledKey()));
2811 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2813 #if ENABLE(FULLSCREEN_API)
2814 settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2817 #if USE(AVFOUNDATION)
2818 settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2822 settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2825 #if PLATFORM(IOS) && HAVE(AVKIT)
2826 settings.setAVKitEnabled(true);
2829 #if ENABLE(IOS_TEXT_AUTOSIZING)
2830 settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2833 #if ENABLE(WEB_AUDIO)
2834 settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2837 #if ENABLE(MEDIA_STREAM)
2838 settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2841 #if ENABLE(SERVICE_CONTROLS)
2842 settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2845 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2846 settings.setAllowsAirPlayForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsAirPlayForMediaPlaybackKey()));
2849 settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2850 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2851 settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2852 settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2853 settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2855 #if ENABLE(VIDEO_TRACK)
2856 settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2857 settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2858 settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2861 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2862 settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2865 settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2866 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2867 settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2869 settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2871 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2873 settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2874 settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2875 settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2876 settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2877 settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2879 #if ENABLE(TEXT_AUTOSIZING)
2880 settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2883 settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2884 settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2886 settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2887 settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2888 settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2890 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2891 settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2894 settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2895 settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2896 settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2897 settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2899 settings.setNewBlockInsideInlineModelEnabled(store.getBoolValueForKey(WebPreferencesKey::newBlockInsideInlineModelEnabledKey()));
2900 settings.setAntialiasedFontDilationEnabled(store.getBoolValueForKey(WebPreferencesKey::antialiasedFontDilationEnabledKey()));
2902 settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
2904 settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2906 #if ENABLE(MEDIA_SOURCE)
2907 settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2910 settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2912 settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2913 settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2914 settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2915 settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2917 settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2918 settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2920 settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2921 settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2923 settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2925 settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
2928 settings.setUseImageDocumentForSubframePDF(true);
2931 settings.setLongMousePressEnabled(store.getBoolValueForKey(WebPreferencesKey::longMousePressEnabledKey()));
2934 RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
2937 #if ENABLE(SERVICE_CONTROLS)
2938 settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
2941 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
2942 if (m_processSuppressionEnabled != processSuppressionEnabled) {
2943 m_processSuppressionEnabled = processSuppressionEnabled;
2944 updateUserActivity();
2947 platformPreferencesDidChange(store);
2950 m_drawingArea->updatePreferences(store);
2953 m_viewportConfiguration.setCanIgnoreScalingConstraints(store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey()));
2954 m_viewportConfiguration.setForceAlwaysUserScalable(store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
2959 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2961 layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2962 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2963 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2964 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2966 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2967 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
2968 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
2969 layerTransaction.setAllowsUserScaling(allowsUserScaling());
2972 layerTransaction.setScrollPosition(corePage()->mainFrame().view()->scrollPosition());
2976 void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp)
2979 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) {
2980 std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
2981 m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero();
2983 m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20));
2986 UNUSED_PARAM(timestamp);
2991 WebInspector* WebPage::inspector()
2996 m_inspector = WebInspector::create(this);
2997 return m_inspector.get();
3000 WebInspectorUI* WebPage::inspectorUI()
3005 m_inspectorUI = WebInspectorUI::create(this);
3006 return m_inspectorUI.get();
3010 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
3012 if (!m_videoFullscreenManager)
3013 m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
3014 return m_videoFullscreenManager.get();
3018 #if ENABLE(FULLSCREEN_API)
3019 WebFullScreenManager* WebPage::fullScreenManager()
3021 if (!m_fullScreenManager)
3022 m_fullScreenManager = WebFullScreenManager::create(this);
3023 return m_fullScreenManager.get();
3027 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3029 if (m_notificationPermissionRequestManager)
3030 return m_notificationPermissionRequestManager.get();
3032 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3033 return m_notificationPermissionRequestManager.get();
3036 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
3037 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
3039 Node* node = evt->target()->toNode();
3041 Frame* frame = node->document().frame();
3044 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
3048 Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
3050 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
3051 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
3052 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
3053 // (e.g. Tab that inserts a Tab character, or Enter).
3054 return !command.isTextInsertion() && command.execute(evt);
3057 if (command.execute(evt))
3060 // Don't allow text insertion for nodes that cannot edit.
3061 if (!frame->editor().canEdit())
3064 // Don't insert null or control characters as they can result in unexpected behaviour
3065 if (evt->charCode() < ' ')
3068 return frame->editor().insertText(evt->keyEvent()->text(), evt);
3072 #if ENABLE(DRAG_SUPPORT)
3075 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
3078 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3079 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3085 case DragControllerActionEntered: {
3086 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3087 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3090 case DragControllerActionUpdated: {
3091 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3092 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3095 case DragControllerActionExited:
3096 m_page->dragController().dragExited(dragData);
3099 case DragControllerActionPerformDragOperation: {
3100 m_page->dragController().performDragOperation(dragData);
3105 ASSERT_NOT_REACHED();
3107 // DragData does not delete its platformData so we need to do that here.
3108 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3113 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)
3116 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3120 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3122 case DragControllerActionEntered: {
3123 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3124 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3128 case DragControllerActionUpdated: {
3129 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3130 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3133 case DragControllerActionExited:
3134 m_page->dragController().dragExited(dragData);
3137 case DragControllerActionPerformDragOperation: {
3138 ASSERT(!m_pendingDropSandboxExtension);
3140 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
3141 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3142 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
3143 m_pendingDropExtensionsForFileUpload.append(extension);
3146 m_page->dragController().performDragOperation(dragData);
3148 // If we started loading a local file, the sandbox extension tracker would have adopted this
3149 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3150 m_pendingDropSandboxExtension = nullptr;
3152 m_pendingDropExtensionsForFileUpload.clear();
3157 ASSERT_NOT_REACHED();
3162 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3164 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3165 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3167 m_page->dragController().dragEnded();
3168 FrameView* view = m_page->mainFrame().view();
3171 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3172 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime(), 0);
3173 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3176 void WebPage::willPerformLoadDragDestinationAction()
3178 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
3181 void WebPage::mayPerformUploadDragDestinationAction()
3183 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3184 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3185 m_pendingDropExtensionsForFileUpload.clear();
3188 #endif // ENABLE(DRAG_SUPPORT)
3190 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3192 return m_undoStepMap.get(stepID);
3195 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3197 m_undoStepMap.set(stepID, entry);
3200 void WebPage::removeWebEditCommand(uint64_t stepID)
3202 m_undoStepMap.remove(stepID);
3205 void WebPage::unapplyEditCommand(uint64_t stepID)
3207 WebUndoStep* step = webUndoStep(stepID);
3211 step->step()->unapply();
3214 void WebPage::reapplyEditCommand(uint64_t stepID)
3216 WebUndoStep* step = webUndoStep(stepID);
3221 step->step()->reapply();
3225 void WebPage::didRemoveEditCommand(uint64_t commandID)
3227 removeWebEditCommand(commandID);
3230 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3232 m_activePopupMenu = menu;
3235 #if ENABLE(INPUT_TYPE_COLOR)
3236 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3238 m_activeColorChooser = colorChooser;
3241 void WebPage::didEndColorPicker()
3243 m_activeColorChooser->didEndChooser();
3246 void WebPage::didChooseColor(const WebCore::Color& color)
3248 m_activeColorChooser->didChooseColor(color);
3252 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
3254 m_activeOpenPanelResultListener = openPanelResultListener;
3257 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3259 return m_page->findString(target, options);
3262 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3264 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
3267 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3269 m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3272 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3274 m_findController.getImageForFindMatch(matchIndex);
3277 void WebPage::selectFindMatch(uint32_t matchIndex)
3279 m_findController.selectFindMatch(matchIndex);
3282 void WebPage::hideFindUI()
3284 m_findController.hideFindUI();
3287 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3289 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3292 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3294 changeSelectedIndex(newIndex);
3295 m_activePopupMenu = 0;
3298 void WebPage::changeSelectedIndex(int32_t index)
3300 if (!m_activePopupMenu)
3303 m_activePopupMenu->didChangeSelectedIndex(index);
3307 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3309 if (!m_activeOpenPanelResultListener)
3313 if (!iconData.isEmpty()) {
3314 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3315 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3316 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3317 icon = Icon::createIconForImage(imageRef.get());
3320 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3321 m_activeOpenPanelResultListener = nullptr;
3325 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3327 if (!m_activeOpenPanelResultListener)
3330 m_activeOpenPanelResultListener->didChooseFiles(files);
3331 m_activeOpenPanelResultListener = 0;
3334 void WebPage::didCancelForOpenPanel()
3336 m_activeOpenPanelResultListener = 0;
3339 #if ENABLE(SANDBOX_EXTENSIONS)
3340 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3342 bool result = SandboxExtension::consumePermanently(handle);
3344 // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3345 WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3350 #if ENABLE(GEOLOCATION)
3351 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3353 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3357 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3359 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3362 #if ENABLE(MEDIA_STREAM)
3363 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed)
3365 m_userMediaPermissionRequestManager.didReceiveUserMediaPermissionDecision(userMediaID, allowed);
3370 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3372 Frame& frame = m_page->focusController().focusedOrMainFrame();
3373 frame.editor().advanceToNextMisspelling(startBeforeSelection);
3377 void WebPage::changeSpellingToWord(const String& word)
3379 replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3382 void WebPage::unmarkAllMisspellings()
3384 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3385 if (Document* document = frame->document())
3386 document->markers().removeMarkers(DocumentMarker::Spelling);
3390 void WebPage::unmarkAllBadGrammar()
3392 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3393 if (Document* document = frame->document())
3394 document->markers().removeMarkers(DocumentMarker::Grammar);
3399 void WebPage::uppercaseWord()
3401 m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3404 void WebPage::lowercaseWord()
3406 m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3409 void WebPage::capitalizeWord()
3411 m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3415 void WebPage::setTextForActivePopupMenu(int32_t index)
3417 if (!m_activePopupMenu)
3420 m_activePopupMenu->setTextForIndex(index);
3424 void WebPage::failedToShowPopupMenu()
3426 if (!m_activePopupMenu)
3429 m_activePopupMenu->client()->popupDidHide();
3433 #if ENABLE(CONTEXT_MENUS)
3434 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3439 m_contextMenu->itemSelected(item);
3444 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3446 bool selectReplacement = true;
3447 bool smartReplace = false;
3448 return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3452 void WebPage::clearSelection()
3454 m_page->focusController().focusedOrMainFrame().selection().clear();
3458 void WebPage::restoreSelectionInFocusedEditableElement()
3460 Frame& frame = m_page->focusController().focusedOrMainFrame();
3461 if (!frame.selection().isNone())
3464 if (auto document = frame.document()) {
3465 if (auto element = document->focusedElement())
3466 element->updateFocusAppearance(true /* restoreSelection */);
3470 bool WebPage::mainFrameHasCustomContentProvider() const
3472 if (Frame* frame = mainFrame()) {
3473 WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3474 ASSERT(webFrameLoaderClient);
3475 return webFrameLoaderClient->frameHasCustomContentProvider();
3481 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3483 m_mimeTypesWithCustomContentProviders.add(mimeType);
3486 void WebPage::updateMainFrameScrollOffsetPinning()
3488 Frame& frame = m_page->mainFrame();
3489 IntPoint scrollPosition = frame.view()->scrollPosition();
3490 IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3491 IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3493 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3494 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3495 bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3496 bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3498 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3499 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3501 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3502 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3503 m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3504 m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3508 void WebPage::mainFrameDidLayout()
3510 unsigned pageCount = m_page->pageCount();
3511 if (pageCount != m_cachedPageCount) {
3512 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3513 m_cachedPageCount = pageCount;
3517 m_viewGestureGeometryCollector.mainFrameDidLayout();
3520 if (FrameView* frameView = mainFrameView()) {
3521 IntSize newContentSize = frameView->contentsSize();
3522 if (m_viewportConfiguration.contentsSize() != newContentSize) {
3523 m_viewportConfiguration.setContentsSize(newContentSize);
3524 viewportConfigurationChanged();
3527 m_findController.redraw();
3531 void WebPage::addPluginView(PluginView* pluginView)
3533 ASSERT(!m_pluginViews.contains(pluginView));
3535 m_pluginViews.add(pluginView);
3536 m_hasSeenPlugin = true;
3537 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3538 LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3539 m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3543 void WebPage::removePluginView(PluginView* pluginView)
3545 ASSERT(m_pluginViews.contains(pluginView));
3547 m_pluginViews.remove(pluginView);
3548 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3549 LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3553 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3556 m_hasCachedWindowFrame = false;
3558 send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3562 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3564 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3565 m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3566 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3567 m_accessibilityPosition = accessibilityViewCoordinates;
3569 // Tell all our plug-in views that the window and view frames have changed.
3570 for (auto* pluginView : m_pluginViews)
3571 pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3573 m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3577 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3579 m_mainFrameIsScrollable = isScrollable;
3580 m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3582 if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3583 frameView->setCanHaveScrollbars(isScrollable);
3584 frameView->setProhibitsScrolling(!isScrollable);
3588 bool WebPage::windowIsFocused() const
3590 return m_page->focusController().isActive();
3593 bool WebPage::windowAndWebPageAreFocused() const
3598 return m_page->focusController().isFocused() && m_page->focusController().isActive();
3601 void WebPage::didReceiveMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder)
3603 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
3604 if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
3606 m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
3611 if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
3612 if (WebInspector* inspector = this->inspector())
3613 inspector->didReceiveMessage(connection, decoder);
3617 if (decoder.messageReceiverName() == Messages::WebInspectorUI::messageReceiverName()) {
3618 if (WebInspectorUI* inspectorUI = this->inspectorUI())
3619 inspectorUI->didReceiveMessage(connection, decoder);
3623 #if ENABLE(FULLSCREEN_API)
3624 if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
3625 fullScreenManager()->didReceiveMessage(connection, decoder);
3630 didReceiveWebPageMessage(connection, decoder);
3633 void WebPage::didReceiveSyncMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder)
3635 didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
3638 InjectedBundleBackForwardList* WebPage::backForwardList()
3640 if (!m_backForwardList)
3641 m_backForwardList = InjectedBundleBackForwardList::create(this);
3642 return m_backForwardList.get();
3645 #if ENABLE(ASYNC_SCROLLING)
3646 ScrollingCoordinator* WebPage::scrollingCoordinator() const
3648 return m_page->scrollingCoordinator();
3652 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3657 void WebPage::SandboxExtensionTracker::invalidate()
3659 m_pendingProvisionalSandboxExtension = nullptr;
3661 if (m_provisionalSandboxExtension) {
3662 m_provisionalSandboxExtension->revoke();
3663 m_provisionalSandboxExtension = nullptr;
3666 if (m_committedSandboxExtension) {
3667 m_committedSandboxExtension->revoke();
3668 m_committedSandboxExtension = nullptr;
3672 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3674 setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3677 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3679 ASSERT_UNUSED(frame, frame->isMainFrame());
3681 setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3684 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3686 m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;
3689 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3691 ASSERT(frame->isMainFrame());
3693 FrameLoader& frameLoader = frame->coreFrame()->loader();
3694 FrameLoadType frameLoadType = frameLoader.loadType();
3696 // If the page is being reloaded, it should reuse whatever extension is committed.
3697 if (frameLoadType == FrameLoadType::Reload || frameLoadType == FrameLoadType::ReloadFromOrigin)
3700 DocumentLoader* documentLoader = frameLoader.documentLoader();
3701 DocumentLoader* provisionalDocumentLoader = frameLoader.provisionalDocumentLoader();
3702 if (!documentLoader || !provisionalDocumentLoader)
3705 if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3711 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3713 if (!frame->isMainFrame())
3716 // We should only reuse the commited sandbox extension if it is not null. It can be
3717 // null if the last load was for an error page.
3718 if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame))
3719 m_pendingProvisionalSandboxExtension = m_committedSandboxExtension;
3721 ASSERT(!m_provisionalSandboxExtension);
3723 m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3724 if (!m_provisionalSandboxExtension)
3727 ASSERT(!m_provisionalSandboxExtension || frame->coreFrame()->loader().provisionalDocumentLoader()->url().isLocalFile());
3729 m_provisionalSandboxExtension->consume();
3732 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3734 if (!frame->isMainFrame())
3737 if (m_committedSandboxExtension)
3738 m_committedSandboxExtension->revoke();
3740 m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3742 // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started.
3743 // This extension is not cleared, because it does not pertain to the failed load, and will be needed.
3746 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3748 if (!frame->isMainFrame())
3751 if (!m_provisionalSandboxExtension)
3754 m_provisionalSandboxExtension->revoke();
3755 m_provisionalSandboxExtension = nullptr;
3757 // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started
3758 // (notably, if the current one fails because the new one cancels it). This extension is not cleared,
3759 // because it does not pertain to the failed load, and will be needed.
3762 bool WebPage::hasLocalDataForURL(const URL& url)
3764 if (url.isLocalFile())
3767 DocumentLoader* documentLoader = m_page->mainFrame().loader().documentLoader();
3768 if (documentLoader && documentLoader->subresource(url))
3771 return platformHasLocalDataForURL(url);
3774 void WebPage::setCustomTextEncodingName(const String& encoding)
3776 m_page->mainFrame().loader().reloadWithOverrideEncoding(encoding);
3779 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3781 WebBackForwardListProxy::removeItem(itemID);
3786 bool WebPage::isSpeaking()
3789 return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3792 void WebPage::speak(const String& string)
3794 send(Messages::WebPageProxy::Speak(string));
3797 void WebPage::stopSpeaking()
3799 send(Messages::WebPageProxy::StopSpeaking());
3805 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3807 Document* document = coreFrame->document();
3808 if (!is<PluginDocument>(document))
3811 PluginView* pluginView = static_cast<PluginView*>(downcast<PluginDocument>(*document).pluginWidget());
3815 return pluginView->pdfDocumentForPrinting();
3817 #endif // PLATFORM(MAC)
3819 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3821 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3825 Frame* coreFrame = frame->coreFrame();
3830 if (pdfDocumentForPrintingFrame(coreFrame))
3832 #endif // PLATFORM(MAC)
3834 if (!m_printContext)
3835 m_printContext = std::make_unique<PrintContext>(coreFrame);
3837 drawingArea()->setLayerTreeStateIsFrozen(true);
3838 m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3840 float fullPageHeight;
3841 m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3844 if (!m_printOperation)
3845 m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3849 void WebPage::endPrinting()
3851 drawingArea()->setLayerTreeStateIsFrozen(false);
3852 m_printContext = nullptr;
3855 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3857 Vector<IntRect> resultPageRects;
3858 double resultTotalScaleFactorForPrinting = 1;
3859 computePagesForPrintingImpl(frameID, printInfo, resultPageRects, resultTotalScaleFactorForPrinting);
3860 send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3863 void WebPage::computePagesForPrintingImpl(uint64_t frameID, const PrintInfo& printInfo, Vector<WebCore::IntRect>& resultPageRects, double& resultTotalScaleFactorForPrinting)
3865 ASSERT(resultPageRects.isEmpty());
3867 beginPrinting(frameID, printInfo);
3869 if (m_printContext) {
3870 resultPageRects = m_printContext->pageRects();
3871 resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3875 computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3876 #endif // PLATFORM(COCOA)
3878 // If we're asked to print, we should actually print at least a blank page.
3879 if (resultPageRects.isEmpty())
3880 resultPageRects.append(IntRect(0, 0, 1, 1));
3884 void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, uint64_t callbackID)
3886 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3887 Frame* coreFrame = frame ? frame->coreFrame() : 0;
3889 RefPtr<WebImage> image;
3894 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3896 ASSERT(coreFrame->document()->printing());
3899 RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(imageSize, ShareableBitmap::SupportsAlpha);
3900 auto graphicsContext = bitmap->createGraphicsContext();
3902 float printingScale = static_cast<float>(imageSize.width()) / rect.width();
3903 graphicsContext->scale(FloatSize(printingScale, printingScale));
3906 if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3907 ASSERT(!m_printContext);
3908 graphicsContext->scale(FloatSize(1, -1));
3909 graphicsContext->translate(0, -rect.height());
3910 drawPDFDocument(graphicsContext->platformContext(), pdfDocument.get(), printInfo, rect);
3914 m_printContext->spoolRect(*graphicsContext, rect);
3917 image = WebImage::create(bitmap.release());
3921 ShareableBitmap::Handle handle;
3924 image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly);
3926 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
3929 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3931 RetainPtr<CFMutableDataRef> pdfPageData;
3932 drawPagesToPDFImpl(frameID, printInfo, first, count, pdfPageData);
3933 send(Messages::WebPageProxy::DataCallback(IPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3936 void WebPage::drawPagesToPDFImpl(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, RetainPtr<CFMutableDataRef>& pdfPageData)
3938 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3939 Frame* coreFrame = frame ? frame->coreFrame() : 0;
3941 pdfPageData = adoptCF(CFDataCreateMutable(0, 0));
3947 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3949 ASSERT(coreFrame->document()->printing());
3952 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3953 RetainPtr<CGDataConsumerRef> pdfDataConsumer = adoptCF(CGDataConsumerCreateWithCFData(pdfPageData.get()));
3955 CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3956 RetainPtr<CGContextRef> context = adoptCF(CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3959 if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3960 ASSERT(!m_printContext);
3961 drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3965 size_t pageCount = m_printContext->pageCount();
3966 for (uint32_t page = first; page < first + count; ++page) {
3967 if (page >= pageCount)
3970 RetainPtr<CFDictionaryRef> pageInfo = adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3971 CGPDFContextBeginPage(context.get(), pageInfo.get());
3973 GraphicsContext ctx(context.get());
3974 ctx.scale(FloatSize(1, -1));
3975 ctx.translate(0, -m_printContext->pageRect(page).height());
3976 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
3978 CGPDFContextEndPage(context.get());
3981 CGPDFContextClose(context.get());
3987 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3989 beginPrinting(frameID, printInfo);
3990 if (m_printContext && m_printOperation) {
3991 m_printOperation->startPrint(m_printContext.get(), callbackID);
3995 send(Messages::WebPageProxy::VoidCallback(callbackID));
3998 void WebPage::didFinishPrintOperation(const WebCore::ResourceError& error, uint64_t callbackID)
4000 send(Messages::WebPageProxy::PrintFinishedCallback(error, callbackID));
4001 m_printOperation = nullptr;
4005 void WebPage::savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size)
4007 send(Messages::WebPageProxy::SavePDFToFileInDownloadsFolder(suggestedFilename, originatingURLString, IPC::DataReference(data, size)));
4011 void WebPage::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID)
4013 send(Messages::WebPageProxy::SavePDFToTemporaryFolderAndOpenWithNativeApplication(suggestedFilename, originatingURLString, IPC::DataReference(data, size), pdfUUID));
4017 void WebPage::addResourceRequest(unsigned long identifier, const WebCore::ResourceRequest& request)
4019 if (!request.url().protocolIsInHTTPFamily())
4022 if (m_mainFrameProgressCompleted && !ScriptController::processingUserGesture())
4025 ASSERT(!m_trackedNetworkResourceRequestIdentifiers.contains(identifier));
4026 bool wasEmpty = m_trackedNetworkResourceRequestIdentifiers.isEmpty();
4027 m_trackedNetworkResourceRequestIdentifiers.add(identifier);
4029 send(Messages::WebPageProxy::SetNetworkRequestsInProgress(true));
4032 void WebPage::removeResourceRequest(unsigned long identifier)
4034 if (!m_trackedNetworkResourceRequestIdentifiers.remove(identifier))
4037 if (m_trackedNetworkResourceRequestIdentifiers.isEmpty())
4038 send(Messages::WebPageProxy::SetNetworkRequestsInProgress(false));
4041 void WebPage::setMediaVolume(float volume)
4043 m_page->setMediaVolume(volume);
4046 void WebPage::setMuted(bool muted)
4048 m_page->setMuted(muted);
4051 void WebPage::setMayStartMediaWhenInWindow(bool mayStartMedia)
4053 if (mayStartMedia == m_mayStartMediaWhenInWindow)
4056 m_mayStartMediaWhenInWindow = mayStartMedia;
4057 if (m_mayStartMediaWhenInWindow && m_page->isInWindow())
4058 m_setCanStartMediaTimer.startOneShot(0);
4061 void WebPage::runModal()
4065 if (m_isRunningModal)
4068 m_isRunningModal = true;
4069 send(Messages::WebPageProxy::RunModal());
4070 #if !ASSERT_DISABLED
4071 Ref<WebPage> protector(*this);
4074 ASSERT(!m_isRunningModal);
4077 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
4079 if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
4082 if (request.url().protocolIs("blob"))
4085 return platformCanHandleRequest(request);
4088 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
4089 void WebPage::commitPageTransitionViewport()
4091 m_drawingArea->setLayerTreeStateIsFrozen(false);
4096 void WebPage::handleAlternativeTextUIResult(const String& result)
4098 Frame& frame = m_page->focusController().focusedOrMainFrame();
4099 frame.editor().handleAlternativeTextUIResult(result);
4103 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
4105 mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time, WebCore::ForceAtClick));
4108 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
4110 mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time, WebCore::ForceAtClick));
4113 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
4115 mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time, 0));
4118 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
4120 Frame& frame = m_page->focusController().focusedOrMainFrame();
4121 if (!frame.editor().canEdit())
4124 Vector<CompositionUnderline> underlines;
4125 underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
4126 frame.editor().setComposition(compositionString, underlines, from, from + length);
4129 bool WebPage::hasCompositionForTesting()
4131 Frame& frame = m_page->focusController().focusedOrMainFrame();
4132 return frame.editor().hasComposition();
4135 void WebPage::confirmCompositionForTesting(const String& compositionString)
4137 Frame& frame = m_page->focusController().focusedOrMainFrame();
4138 if (!frame.editor().canEdit())
4141 if (compositionString.isNull())
4142 frame.editor().confirmComposition();
4143 frame.editor().confirmComposition(compositionString);
4146 void WebPage::wheelEventHandlersChanged(bool hasHandlers)
4148 if (m_hasWheelEventHandlers == hasHandlers)
4151 m_hasWheelEventHandlers = hasHandlers;
4152 recomputeShortCircuitHorizontalWheelEventsState();
4155 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
4157 if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
4158 return scrollbar->enabled();
4163 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
4165 if (FrameView* frameView = mainFrame->view()) {
4166 if (hasEnabledHorizontalScrollbar(frameView))
4170 for (Frame* frame = mainFrame; frame; frame = frame->tree().traverseNext()) {
4171 FrameView* frameView = frame->view();
4175 const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();