2 * Copyright (C) 2010, 2011, 2012, 2013-2015 Apple Inc. All rights reserved.
3 * Copyright (C) 2012 Intel Corporation. All rights reserved.
4 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
19 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
25 * THE POSSIBILITY OF SUCH DAMAGE.
32 #include "APIGeometry.h"
33 #include "Arguments.h"
34 #include "DataReference.h"
35 #include "DragControllerAction.h"
36 #include "DrawingArea.h"
37 #include "DrawingAreaMessages.h"
38 #include "EditingRange.h"
39 #include "EditorState.h"
40 #include "EventDispatcher.h"
41 #include "InjectedBundle.h"
42 #include "InjectedBundleBackForwardList.h"
43 #include "LayerTreeHost.h"
45 #include "NetscapePlugin.h"
46 #include "NotificationPermissionRequestManager.h"
47 #include "PageBanner.h"
48 #include "PluginProcessAttributes.h"
49 #include "PluginProxy.h"
50 #include "PluginView.h"
51 #include "PrintInfo.h"
52 #include "SessionState.h"
53 #include "SessionStateConversion.h"
54 #include "SessionTracker.h"
55 #include "ShareableBitmap.h"
56 #include "VisitedLinkTableController.h"
57 #include "WKBundleAPICast.h"
58 #include "WKRetainPtr.h"
59 #include "WKSharedAPICast.h"
60 #include "WebAlternativeTextClient.h"
61 #include "WebBackForwardListItem.h"
62 #include "WebBackForwardListProxy.h"
63 #include "WebChromeClient.h"
64 #include "WebColorChooser.h"
65 #include "WebContextMenu.h"
66 #include "WebContextMenuClient.h"
67 #include "WebCoreArgumentCoders.h"
68 #include "WebDatabaseProvider.h"
69 #include "WebDiagnosticLoggingClient.h"
70 #include "WebDocumentLoader.h"
71 #include "WebDragClient.h"
72 #include "WebEditorClient.h"
74 #include "WebEventConversion.h"
75 #include "WebEventFactory.h"
77 #include "WebFrameLoaderClient.h"
78 #include "WebFullScreenManager.h"
79 #include "WebFullScreenManagerMessages.h"
80 #include "WebGeolocationClient.h"
82 #include "WebInspector.h"
83 #include "WebInspectorClient.h"
84 #include "WebInspectorMessages.h"
85 #include "WebInspectorUI.h"
86 #include "WebInspectorUIMessages.h"
87 #include "WebMediaKeyStorageManager.h"
88 #include "WebNotificationClient.h"
89 #include "WebOpenPanelResultListener.h"
90 #include "WebPageCreationParameters.h"
91 #include "WebPageGroupProxy.h"
92 #include "WebPageMessages.h"
93 #include "WebPageOverlay.h"
94 #include "WebPageProxyMessages.h"
95 #include "WebPlugInClient.h"
96 #include "WebPopupMenu.h"
97 #include "WebPreferencesDefinitions.h"
98 #include "WebPreferencesKeys.h"
99 #include "WebPreferencesStore.h"
100 #include "WebProcess.h"
101 #include "WebProcessPoolMessages.h"
102 #include "WebProcessProxyMessages.h"
103 #include "WebProgressTrackerClient.h"
104 #include "WebStorageNamespaceProvider.h"
105 #include "WebUndoStep.h"
106 #include "WebUserContentController.h"
107 #include "WebUserMediaClient.h"
108 #include <JavaScriptCore/APICast.h>
109 #include <WebCore/ArchiveResource.h>
110 #include <WebCore/Chrome.h>
111 #include <WebCore/ContextMenuController.h>
112 #include <WebCore/DataTransfer.h>
113 #include <WebCore/DatabaseManager.h>
114 #include <WebCore/DocumentFragment.h>
115 #include <WebCore/DocumentLoader.h>
116 #include <WebCore/DocumentMarkerController.h>
117 #include <WebCore/DragController.h>
118 #include <WebCore/DragData.h>
119 #include <WebCore/ElementIterator.h>
120 #include <WebCore/EventHandler.h>
121 #include <WebCore/FocusController.h>
122 #include <WebCore/FormState.h>
123 #include <WebCore/FrameLoadRequest.h>
124 #include <WebCore/FrameLoaderTypes.h>
125 #include <WebCore/FrameView.h>
126 #include <WebCore/HTMLFormElement.h>
127 #include <WebCore/HTMLInputElement.h>
128 #include <WebCore/HTMLPlugInElement.h>
129 #include <WebCore/HTMLPlugInImageElement.h>
130 #include <WebCore/HistoryController.h>
131 #include <WebCore/HistoryItem.h>
132 #include <WebCore/HitTestResult.h>
133 #include <WebCore/JSDOMWindow.h>
134 #include <WebCore/KeyboardEvent.h>
135 #include <WebCore/MIMETypeRegistry.h>
136 #include <WebCore/MainFrame.h>
137 #include <WebCore/MouseEvent.h>
138 #include <WebCore/Page.h>
139 #include <WebCore/PageConfiguration.h>
140 #include <WebCore/PageThrottler.h>
141 #include <WebCore/PlatformKeyboardEvent.h>
142 #include <WebCore/PluginDocument.h>
143 #include <WebCore/PrintContext.h>
144 #include <WebCore/Range.h>
145 #include <WebCore/RenderLayer.h>
146 #include <WebCore/RenderTreeAsText.h>
147 #include <WebCore/RenderView.h>
148 #include <WebCore/ResourceRequest.h>
149 #include <WebCore/ResourceResponse.h>
150 #include <WebCore/RuntimeEnabledFeatures.h>
151 #include <WebCore/SchemeRegistry.h>
152 #include <WebCore/ScriptController.h>
153 #include <WebCore/SerializedScriptValue.h>
154 #include <WebCore/SessionID.h>
155 #include <WebCore/Settings.h>
156 #include <WebCore/ShadowRoot.h>
157 #include <WebCore/SharedBuffer.h>
158 #include <WebCore/StyleProperties.h>
159 #include <WebCore/SubframeLoader.h>
160 #include <WebCore/SubstituteData.h>
161 #include <WebCore/TextIterator.h>
162 #include <WebCore/UserInputBridge.h>
163 #include <WebCore/VisiblePosition.h>
164 #include <WebCore/VisibleUnits.h>
165 #include <WebCore/markup.h>
166 #include <bindings/ScriptValue.h>
167 #include <profiler/ProfilerDatabase.h>
168 #include <runtime/JSCInlines.h>
169 #include <runtime/JSCJSValue.h>
170 #include <runtime/JSLock.h>
171 #include <wtf/RunLoop.h>
172 #include <wtf/TemporaryChange.h>
175 #include <WebCore/MHTMLArchive.h>
178 #if ENABLE(BATTERY_STATUS)
179 #include "WebBatteryClient.h"
182 #if ENABLE(VIBRATION)
183 #include "WebVibrationClient.h"
186 #if ENABLE(PROXIMITY_EVENTS)
187 #include "WebDeviceProximityClient.h"
191 #include "PDFPlugin.h"
192 #include "RemoteLayerTreeTransaction.h"
193 #include "WKStringCF.h"
194 #include <WebCore/LegacyWebArchive.h>
199 #include "DataObjectGtk.h"
200 #include "WebPrintOperationGtk.h"
204 #include "RemoteLayerTreeDrawingArea.h"
205 #include "WebVideoFullscreenManager.h"
206 #include <CoreGraphics/CoreGraphics.h>
207 #include <WebCore/CoreTextSPI.h>
208 #include <WebCore/Icon.h>
212 #include <wtf/RefCountedLeakCounter.h>
215 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
216 #include "CoordinatedLayerTreeHostMessages.h"
219 #if ENABLE(VIDEO) && USE(GSTREAMER)
220 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
224 using namespace WebCore;
228 static const double pageScrollHysteresisSeconds = 0.3;
230 class SendStopResponsivenessTimer {
232 SendStopResponsivenessTimer(WebPage* page)
237 ~SendStopResponsivenessTimer()
239 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
246 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
248 Ref<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
250 Ref<WebPage> page = adoptRef(*new WebPage(pageID, parameters));
252 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
253 WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
258 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
260 , m_viewSize(parameters.viewSize)
261 , m_hasSeenPlugin(false)
262 , m_useFixedLayout(false)
263 , m_drawsBackground(true)
264 , m_drawsTransparentBackground(false)
267 , m_tabToLinks(false)
268 , m_asynchronousPluginInitializationEnabled(false)
269 , m_asynchronousPluginInitializationEnabledForAllPlugins(false)
270 , m_artificialPluginInitializationDelayEnabled(false)
271 , m_scrollingPerformanceLoggingEnabled(false)
272 , m_mainFrameIsScrollable(true)
273 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
274 , m_readyToFindPrimarySnapshottedPlugin(false)
275 , m_didFindPrimarySnapshottedPlugin(false)
276 , m_numberOfPrimarySnapshotDetectionAttempts(0)
277 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
279 , m_layerHostingMode(parameters.layerHostingMode)
281 , m_pdfPluginEnabled(false)
282 , m_hasCachedWindowFrame(false)
283 , m_viewGestureGeometryCollector(*this)
284 #elif HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL))
285 , m_accessibilityObject(nullptr)
287 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
288 #if ENABLE(CONTEXT_MENUS)
289 , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
291 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
292 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
293 , m_findController(this)
294 #if ENABLE(INPUT_TYPE_COLOR)
295 , m_activeColorChooser(0)
297 , m_userContentController(parameters.userContentControllerID ? WebUserContentController::getOrCreate(parameters.userContentControllerID) : nullptr)
298 #if ENABLE(GEOLOCATION)
299 , m_geolocationPermissionRequestManager(this)
301 #if ENABLE(MEDIA_STREAM)
302 , m_userMediaPermissionRequestManager(*this)
304 , m_pageScrolledHysteresis([this](HysteresisState state) { if (state == HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisSeconds)
305 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
306 , m_canRunModal(parameters.canRunModal)
307 , m_isRunningModal(false)
308 #if ENABLE(DRAG_SUPPORT)
309 , m_isStartingDrag(false)
311 , m_cachedMainFrameIsPinnedToLeftSide(true)
312 , m_cachedMainFrameIsPinnedToRightSide(true)
313 , m_cachedMainFrameIsPinnedToTopSide(true)
314 , m_cachedMainFrameIsPinnedToBottomSide(true)
315 , m_canShortCircuitHorizontalWheelEvents(false)
316 , m_hasWheelEventHandlers(false)
317 , m_cachedPageCount(0)
318 , m_autoSizingShouldExpandToViewHeight(false)
319 #if ENABLE(CONTEXT_MENUS)
320 , m_isShowingContextMenu(false)
323 , m_selectionAnchor(Start)
324 , m_hasReceivedVisibleContentRectsAfterDidCommitLoad(false)
325 , m_scaleWasSetByUIProcess(false)
326 , m_userHasChangedPageScaleFactor(false)
327 , m_hasStablePageScaleFactor(true)
328 , m_userIsInteracting(false)
329 , m_hasPendingBlurNotification(false)
330 , m_useTestingViewportConfiguration(false)
331 , m_isInStableState(true)
332 , m_oldestNonStableUpdateVisibleContentRectsTimestamp(std::chrono::milliseconds::zero())
333 , m_estimatedLatency(std::chrono::milliseconds::zero())
334 , m_screenSize(parameters.screenSize)
335 , m_availableScreenSize(parameters.availableScreenSize)
336 , m_deviceOrientation(0)
337 , m_inDynamicSizeUpdate(false)
338 , m_volatilityTimer(*this, &WebPage::volatilityTimerFired)
340 , m_inspectorClient(0)
341 , m_backgroundColor(Color::white)
342 , m_maximumRenderingSuppressionToken(0)
343 , m_scrollPinningBehavior(DoNotPin)
344 , m_useAsyncScrolling(false)
345 , m_viewState(parameters.viewState)
346 , m_processSuppressionEnabled(true)
347 , m_userActivity("Process suppression disabled for page.")
348 , m_pendingNavigationID(0)
350 , m_systemWebGLPolicy(WebGLAllowCreation)
352 , m_mainFrameProgressCompleted(false)
353 , m_shouldDispatchFakeMouseMoveEvents(true)
357 m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
360 Settings::setShouldManageAudioSessionCategory(true);
363 PageConfiguration pageConfiguration;
364 pageConfiguration.chromeClient = new WebChromeClient(this);
365 #if ENABLE(CONTEXT_MENUS)
366 pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
368 pageConfiguration.editorClient = new WebEditorClient(this);
369 #if ENABLE(DRAG_SUPPORT)
370 pageConfiguration.dragClient = new WebDragClient(this);
372 pageConfiguration.backForwardClient = WebBackForwardListProxy::create(this);
373 m_inspectorClient = new WebInspectorClient(this);
374 pageConfiguration.inspectorClient = m_inspectorClient;
375 #if USE(AUTOCORRECTION_PANEL)
376 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
378 pageConfiguration.plugInClient = new WebPlugInClient(*this);
379 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
380 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
381 pageConfiguration.diagnosticLoggingClient = new WebDiagnosticLoggingClient(*this);
383 pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
384 pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
385 pageConfiguration.userContentController = m_userContentController ? &m_userContentController->userContentController() : &m_pageGroup->userContentController();
386 pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
388 m_page = std::make_unique<Page>(pageConfiguration);
390 m_drawingArea = DrawingArea::create(*this, parameters);
391 m_drawingArea->setPaintingEnabled(false);
392 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
394 #if ENABLE(ASYNC_SCROLLING)
395 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
396 if (!m_drawingArea->supportsAsyncScrolling())
397 m_useAsyncScrolling = false;
398 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
401 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
403 #if ENABLE(BATTERY_STATUS)
404 WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
406 #if ENABLE(GEOLOCATION)
407 WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
409 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
410 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
412 #if ENABLE(VIBRATION)
413 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
415 #if ENABLE(PROXIMITY_EVENTS)
416 WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this));
418 #if ENABLE(MEDIA_STREAM)
419 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
422 #if ENABLE(REMOTE_INSPECTOR)
423 m_page->setRemoteInspectionAllowed(true);
426 m_page->setCanStartMedia(false);
427 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
429 m_page->setGroupName(m_pageGroup->identifier());
430 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
432 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
435 updatePreferences(parameters.store);
436 platformInitialize();
438 setUseFixedLayout(parameters.useFixedLayout);
440 setDrawsBackground(parameters.drawsBackground);
441 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
443 setUnderlayColor(parameters.underlayColor);
445 setPaginationMode(parameters.paginationMode);
446 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
447 setPageLength(parameters.pageLength);
448 setGapBetweenPages(parameters.gapBetweenPages);
450 // If the page is created off-screen, its visibilityState should be prerender.
451 m_page->setViewState(m_viewState);
453 m_page->setIsPrerender();
454 updateUserActivity();
456 updateIsInWindow(true);
458 setMinimumLayoutSize(parameters.minimumLayoutSize);
459 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
461 setScrollPinningBehavior(parameters.scrollPinningBehavior);
462 if (parameters.scrollbarOverlayStyle)
463 m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
465 m_scrollbarOverlayStyle = WTF::Optional<ScrollbarOverlayStyle>();
467 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
469 setTopContentInset(parameters.topContentInset);
471 m_userAgent = parameters.userAgent;
473 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
475 if (!parameters.itemStates.isEmpty())
476 restoreSession(parameters.itemStates);
478 if (parameters.sessionID.isValid())
479 setSessionID(parameters.sessionID);
481 m_drawingArea->setPaintingEnabled(true);
483 setMediaVolume(parameters.mediaVolume);
485 setMuted(parameters.muted);
487 // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
488 m_page->addLayoutMilestones(DidFirstLayout | DidFirstVisuallyNonEmptyLayout);
490 auto& webProcess = WebProcess::singleton();
491 webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
493 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
494 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
495 webProcess.addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this);
497 webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
498 webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
499 #if ENABLE(FULLSCREEN_API)
500 webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
504 webPageCounter.increment();
507 #if ENABLE(ASYNC_SCROLLING)
508 if (m_useAsyncScrolling)
509 webProcess.eventDispatcher().addScrollingTreeForPage(this);
512 for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
513 m_mimeTypesWithCustomContentProviders.add(mimeType);
516 #if ENABLE(ENCRYPTED_MEDIA_V2)
517 if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
518 m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
520 m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
522 if (parameters.viewScaleFactor != 1)
523 scaleView(parameters.viewScaleFactor);
525 m_page->setUserContentExtensionsEnabled(parameters.userContentExtensionsEnabled);
528 m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
532 void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters)
534 if (m_viewState != parameters.viewState)
535 setViewState(parameters.viewState, false, Vector<uint64_t>());
536 if (m_layerHostingMode != parameters.layerHostingMode)
537 setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode));
540 void WebPage::setPageActivityState(PageActivityState::Flags activityState)
542 PageActivityState::Flags changed = m_activityState ^ activityState;
543 m_activityState = activityState;
546 updateUserActivity();
549 void WebPage::updateUserActivity()
551 // Start the activity to prevent AppNap if the page activity is in progress,
552 // the page is visible and non-idle, or process suppression is disabled.
553 if (m_activityState || !(m_viewState & ViewState::IsVisuallyIdle) || !m_processSuppressionEnabled)
554 m_userActivity.start();
556 m_userActivity.stop();
561 if (m_backForwardList)
562 m_backForwardList->detach();
566 auto& webProcess = WebProcess::singleton();
567 #if ENABLE(ASYNC_SCROLLING)
568 if (m_useAsyncScrolling)
569 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
574 m_sandboxExtensionTracker.invalidate();
576 for (auto* pluginView : m_pluginViews)
577 pluginView->webPageDestroyed();
581 m_headerBanner->detachFromPage();
583 m_footerBanner->detachFromPage();
584 #endif // !PLATFORM(IOS)
586 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
588 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
589 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
590 webProcess.removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID);
592 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
593 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
594 #if ENABLE(FULLSCREEN_API)
595 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
599 webPageCounter.decrement();
603 void WebPage::dummy(bool&)
607 IPC::Connection* WebPage::messageSenderConnection()
609 return WebProcess::singleton().parentProcessConnection();
612 uint64_t WebPage::messageSenderDestinationID()
617 #if ENABLE(CONTEXT_MENUS)
618 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient> contextMenuClient)
620 if (!contextMenuClient) {
621 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
625 m_contextMenuClient = WTF::move(contextMenuClient);
629 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* client)
631 m_editorClient.initialize(client);
634 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient> formClient)
637 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
641 m_formClient = WTF::move(formClient);
644 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client)
646 m_loaderClient.initialize(client);
648 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
649 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
650 // for backwards compatibility.
651 LayoutMilestones milestones = 0;
653 if (m_loaderClient.client().didFirstLayoutForFrame)
654 milestones |= WebCore::DidFirstLayout;
655 if (m_loaderClient.client().didFirstVisuallyNonEmptyLayoutForFrame)
656 milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
660 listenForLayoutMilestones(milestones);
663 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
665 m_policyClient.initialize(client);
668 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase* client)
670 m_resourceLoadClient.initialize(client);
673 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient> uiClient)
676 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
680 m_uiClient = WTF::move(uiClient);
683 #if ENABLE(FULLSCREEN_API)
684 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
686 m_fullScreenClient.initialize(client);
690 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase* client)
692 m_logDiagnosticMessageClient.initialize(client);
695 #if ENABLE(NETSCAPE_PLUGIN_API)
696 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
698 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
699 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
701 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
702 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
703 unsigned pluginArea = 0;
704 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
706 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
709 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
711 uint64_t pluginProcessToken;
712 uint32_t pluginLoadPolicy;
713 String unavailabilityDescription;
714 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)))
717 PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
718 bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
720 if (isBlockedPlugin || !pluginProcessToken) {
721 #if ENABLE(PDFKIT_PLUGIN)
722 String path = parameters.url.path();
723 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
724 RefPtr<PDFPlugin> pdfPlugin = PDFPlugin::create(frame);
725 return pdfPlugin.release();
732 if (isBlockedPlugin) {
733 bool replacementObscured = false;
734 if (is<RenderEmbeddedObject>(*pluginElement->renderer())) {
735 auto& renderObject = downcast<RenderEmbeddedObject>(*pluginElement->renderer());
736 renderObject.setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
737 replacementObscured = renderObject.isReplacementObscured();
738 renderObject.setUnavailablePluginIndicatorIsHidden(replacementObscured);
741 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
745 if (!pluginProcessToken)
748 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
749 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
752 #endif // ENABLE(NETSCAPE_PLUGIN_API)
754 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
755 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
757 return WebGLAllowCreation;
760 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
762 return WebGLAllowCreation;
766 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
768 Frame& frame = m_page->focusController().focusedOrMainFrame();
772 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
773 if (!pluginView->getSelectionString().isNull()) {
774 result.selectionIsNone = false;
775 result.selectionIsRange = true;
776 result.isInPlugin = true;
781 const VisibleSelection& selection = frame.selection().selection();
783 result.selectionIsNone = selection.isNone();
784 result.selectionIsRange = selection.isRange();
785 result.isContentEditable = selection.isContentEditable();
786 result.isContentRichlyEditable = selection.isContentRichlyEditable();
787 result.isInPasswordField = selection.isInPasswordField();
788 result.hasComposition = frame.editor().hasComposition();
789 result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange();
791 platformEditorState(frame, result, shouldIncludePostLayoutData);
796 String WebPage::renderTreeExternalRepresentation() const
798 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
801 String WebPage::renderTreeExternalRepresentationForPrinting() const
803 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
806 uint64_t WebPage::renderTreeSize() const
810 return m_page->renderTreeSize();
813 void WebPage::setTracksRepaints(bool trackRepaints)
815 if (FrameView* view = mainFrameView())
816 view->setTracksRepaints(trackRepaints);
819 bool WebPage::isTrackingRepaints() const
821 if (FrameView* view = mainFrameView())
822 return view->isTrackingRepaints();
827 void WebPage::resetTrackedRepaints()
829 if (FrameView* view = mainFrameView())
830 view->resetTrackedRepaints();
833 Ref<API::Array> WebPage::trackedRepaintRects()
835 FrameView* view = mainFrameView();
837 return API::Array::create();
839 Vector<RefPtr<API::Object>> repaintRects;
840 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
842 for (const auto& repaintRect : view->trackedRepaintRects())
843 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
845 return API::Array::create(WTF::move(repaintRects));
848 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
850 if (!frame.document()->isPluginDocument())
853 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
855 if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
858 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
862 PluginView* WebPage::pluginViewForFrame(Frame* frame)
864 if (!frame->document()->isPluginDocument())
867 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
868 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
872 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
874 Frame& frame = m_page->focusController().focusedOrMainFrame();
876 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
877 pluginView->handleEditingCommand(commandName, argument);
881 frame.editor().command(commandName).execute(argument);
884 void WebPage::setEditable(bool editable)
886 m_page->setEditable(editable);
887 m_page->setTabKeyCyclesThroughElements(!editable);
888 Frame& frame = m_page->focusController().focusedOrMainFrame();
890 frame.editor().applyEditingStyleToBodyElement();
891 // If the page is made editable and the selection is empty, set it to something.
892 if (frame.selection().isNone())
893 frame.selection().setSelectionFromNone();
897 bool WebPage::isEditingCommandEnabled(const String& commandName)
899 Frame& frame = m_page->focusController().focusedOrMainFrame();
901 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
902 return pluginView->isEditingCommandEnabled(commandName);
904 Editor::Command command = frame.editor().command(commandName);
905 return command.isSupported() && command.isEnabled();
908 void WebPage::clearMainFrameName()
910 if (Frame* frame = mainFrame())
911 frame->tree().clearName();
914 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
916 m_drawingArea->setRootCompositingLayer(layer);
919 void WebPage::exitAcceleratedCompositingMode()
921 m_drawingArea->setRootCompositingLayer(0);
924 void WebPage::close()
931 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
932 if (!mainWebFrame()->url().isEmpty())
933 reportUsedFeatures();
935 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
936 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
939 m_inspector->disconnectFromPage();
940 m_inspector = nullptr;
943 #if ENABLE(FULLSCREEN_API)
944 m_fullScreenManager = nullptr;
947 if (m_activePopupMenu) {
948 m_activePopupMenu->disconnectFromPage();
949 m_activePopupMenu = nullptr;
952 if (m_activeOpenPanelResultListener) {
953 m_activeOpenPanelResultListener->disconnectFromPage();
954 m_activeOpenPanelResultListener = nullptr;
957 #if ENABLE(INPUT_TYPE_COLOR)
958 if (m_activeColorChooser) {
959 m_activeColorChooser->disconnectFromPage();
960 m_activeColorChooser = nullptr;
965 if (m_printOperation) {
966 m_printOperation->disconnectFromPage();
967 m_printOperation = nullptr;
971 #if ENABLE(VIDEO) && USE(GSTREAMER)
972 if (m_installMediaPluginsCallback) {
973 m_installMediaPluginsCallback->invalidate();
974 m_installMediaPluginsCallback = nullptr;
978 m_sandboxExtensionTracker.invalidate();
980 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
981 m_determinePrimarySnapshottedPlugInTimer.stop();
984 #if ENABLE(CONTEXT_MENUS)
985 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
987 m_editorClient.initialize(0);
988 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
989 m_loaderClient.initialize(0);
990 m_policyClient.initialize(0);
991 m_resourceLoadClient.initialize(0);
992 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
993 #if ENABLE(FULLSCREEN_API)
994 m_fullScreenClient.initialize(0);
996 m_logDiagnosticMessageClient.initialize(0);
998 m_printContext = nullptr;
999 m_mainFrame->coreFrame()->loader().detachFromParent();
1001 m_drawingArea = nullptr;
1003 bool isRunningModal = m_isRunningModal;
1004 m_isRunningModal = false;
1006 // The WebPage can be destroyed by this call.
1007 WebProcess::singleton().removeWebPage(m_pageID);
1010 RunLoop::main().stop();
1013 void WebPage::tryClose()
1015 SendStopResponsivenessTimer stopper(this);
1017 if (!corePage()->userInputBridge().tryClosePage()) {
1018 send(Messages::WebPageProxy::StopResponsivenessTimer());
1022 send(Messages::WebPageProxy::ClosePage(true));
1025 void WebPage::sendClose()
1027 send(Messages::WebPageProxy::ClosePage(false));
1030 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
1032 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1036 frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url)), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1039 void WebPage::loadRequest(uint64_t navigationID, const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, uint64_t shouldOpenExternalURLsPolicy, const UserData& userData)
1041 SendStopResponsivenessTimer stopper(this);
1043 m_pendingNavigationID = navigationID;
1045 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1047 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1048 // to all the client to set up any needed state.
1049 m_loaderClient.willLoadURLRequest(this, request, WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1051 // Initate the load in WebCore.
1052 FrameLoadRequest frameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1053 ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(shouldOpenExternalURLsPolicy);
1054 frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1056 corePage()->userInputBridge().loadRequest(frameLoadRequest);
1058 ASSERT(!m_pendingNavigationID);
1061 void WebPage::loadDataImpl(uint64_t navigationID, PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1063 SendStopResponsivenessTimer stopper(this);
1065 m_pendingNavigationID = navigationID;
1067 ResourceRequest request(baseURL);
1068 ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1069 SubstituteData substituteData(sharedBuffer, unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1071 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1072 // to all the client to set up any needed state.
1073 m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1075 // Initate the load in WebCore.
1076 m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData));
1079 void WebPage::loadString(uint64_t navigationID, const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1081 if (!htmlString.isNull() && htmlString.is8Bit()) {
1082 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
1083 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, userData);
1085 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
1086 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, userData);
1090 void WebPage::loadData(uint64_t navigationID, const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, const UserData& userData)
1092 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
1093 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1094 loadDataImpl(navigationID, sharedBuffer, MIMEType, encodingName, baseURL, URL(), userData);
1097 void WebPage::loadHTMLString(uint64_t navigationID, const String& htmlString, const String& baseURLString, const UserData& userData)
1099 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1100 loadString(navigationID, htmlString, ASCIILiteral("text/html"), baseURL, URL(), userData);
1103 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, const String& provisionalLoadErrorURLString, const UserData& userData)
1105 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1106 URL unreachableURL = unreachableURLString.isEmpty() ? URL() : URL(URL(), unreachableURLString);
1107 URL provisionalLoadErrorURL = provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), provisionalLoadErrorURLString);
1108 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1109 loadString(0, htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, userData);
1110 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1113 void WebPage::loadPlainTextString(const String& string, const UserData& userData)
1115 loadString(0, string, ASCIILiteral("text/plain"), blankURL(), URL(), userData);
1118 void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, const UserData& userData)
1120 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
1121 loadDataImpl(0, sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), userData);
1124 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1126 Frame* mainFrame = m_mainFrame->coreFrame();
1127 Document* mainFrameDocument = mainFrame->document();
1128 if (!mainFrameDocument)
1131 const int singleClick = 1;
1132 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);
1134 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1137 void WebPage::stopLoadingFrame(uint64_t frameID)
1139 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1143 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1146 void WebPage::stopLoading()
1148 SendStopResponsivenessTimer stopper(this);
1150 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1153 bool WebPage::defersLoading() const
1155 return m_page->defersLoading();
1158 void WebPage::setDefersLoading(bool defersLoading)
1160 m_page->setDefersLoading(defersLoading);
1163 void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
1165 SendStopResponsivenessTimer stopper(this);
1167 ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1168 m_pendingNavigationID = navigationID;
1170 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1171 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin);
1174 void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID)
1176 SendStopResponsivenessTimer stopper(this);
1178 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1183 ASSERT(!m_pendingNavigationID);
1184 m_pendingNavigationID = navigationID;
1186 m_page->goToItem(*item, FrameLoadType::Forward);
1189 void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID)
1191 SendStopResponsivenessTimer stopper(this);
1193 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1198 ASSERT(!m_pendingNavigationID);
1199 m_pendingNavigationID = navigationID;
1201 m_page->goToItem(*item, FrameLoadType::Back);
1204 void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID)
1206 SendStopResponsivenessTimer stopper(this);
1208 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1213 ASSERT(!m_pendingNavigationID);
1214 m_pendingNavigationID = navigationID;
1216 m_page->goToItem(*item, FrameLoadType::IndexedBackForward);
1219 void WebPage::tryRestoreScrollPosition()
1221 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1224 void WebPage::layoutIfNeeded()
1226 if (m_mainFrame->coreFrame()->view())
1227 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1230 WebPage* WebPage::fromCorePage(Page* page)
1232 return static_cast<WebChromeClient&>(page->chrome().client()).page();
1235 void WebPage::setSize(const WebCore::IntSize& viewSize)
1237 if (m_viewSize == viewSize)
1240 FrameView* view = m_page->mainFrame().view();
1241 view->resize(viewSize);
1242 m_drawingArea->setNeedsDisplay();
1244 m_viewSize = viewSize;
1246 #if USE(COORDINATED_GRAPHICS)
1247 if (view->useFixedLayout())
1248 sendViewportAttributesChanged();
1252 #if USE(COORDINATED_GRAPHICS)
1253 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1255 ASSERT(m_useFixedLayout);
1257 m_page->mainFrame().view()->setFixedVisibleContentRect(rect);
1260 void WebPage::sendViewportAttributesChanged()
1262 ASSERT(m_useFixedLayout);
1264 // Viewport properties have no impact on zero sized fixed viewports.
1265 if (m_viewSize.isEmpty())
1268 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1269 Settings& settings = m_page->settings();
1271 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1273 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1274 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1275 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1277 ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1279 FrameView* view = m_page->mainFrame().view();
1281 // If no layout was done yet set contentFixedOrigin to (0,0).
1282 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1284 // Put the width and height to the viewport width and height. In css units however.
1285 // Use FloatSize to avoid truncated values during scale.
1286 FloatSize contentFixedSize = m_viewSize;
1288 #if ENABLE(CSS_DEVICE_ADAPTATION)
1289 // CSS viewport descriptors might be applied to already affected viewport size
1290 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1291 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1294 contentFixedSize.scale(1 / attr.initialScale);
1295 setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1297 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1299 // This also takes care of the relayout.
1300 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1302 #if USE(COORDINATED_GRAPHICS_THREADED)
1303 if (m_drawingArea->layerTreeHost())
1304 m_drawingArea->layerTreeHost()->didChangeViewportProperties(attr);
1306 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1311 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1313 FrameView* frameView = m_page->mainFrame().view();
1315 IntPoint scrollPosition = frameView->scrollPosition();
1316 IntPoint maximumScrollPosition = frameView->maximumScrollPosition();
1318 // If the current scroll position in a direction is the max scroll position
1319 // we don't want to scroll at all.
1320 IntSize newScrollOffset;
1321 if (scrollPosition.x() < maximumScrollPosition.x())
1322 newScrollOffset.setWidth(scrollOffset.width());
1323 if (scrollPosition.y() < maximumScrollPosition.y())
1324 newScrollOffset.setHeight(scrollOffset.height());
1326 if (newScrollOffset.isZero())
1329 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1332 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1334 GraphicsContextStateSaver stateSaver(graphicsContext);
1335 graphicsContext.clip(rect);
1337 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1340 double WebPage::textZoomFactor() const
1342 Frame* frame = m_mainFrame->coreFrame();
1345 return frame->textZoomFactor();
1348 void WebPage::setTextZoomFactor(double zoomFactor)
1350 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1351 if (pluginView && pluginView->handlesPageScaleFactor())
1354 Frame* frame = m_mainFrame->coreFrame();
1357 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1360 double WebPage::pageZoomFactor() const
1362 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1363 if (pluginView && pluginView->handlesPageScaleFactor())
1364 return pluginView->pageScaleFactor();
1366 Frame* frame = m_mainFrame->coreFrame();
1369 return frame->pageZoomFactor();
1372 void WebPage::setPageZoomFactor(double zoomFactor)
1374 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1375 if (pluginView && pluginView->handlesPageScaleFactor()) {
1376 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1380 Frame* frame = m_mainFrame->coreFrame();
1383 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1386 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1388 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1389 if (pluginView && pluginView->handlesPageScaleFactor()) {
1390 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1394 Frame* frame = m_mainFrame->coreFrame();
1397 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1400 void WebPage::windowScreenDidChange(uint32_t displayID)
1402 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1405 void WebPage::scalePage(double scale, const IntPoint& origin)
1407 double totalScale = scale * viewScaleFactor();
1408 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1411 if (willChangeScaleFactor) {
1412 if (!m_inDynamicSizeUpdate)
1413 m_dynamicSizeUpdateHistory.clear();
1414 m_scaleWasSetByUIProcess = false;
1417 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1418 if (pluginView && pluginView->handlesPageScaleFactor()) {
1419 // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1420 // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1421 if (m_page->pageScaleFactor() != 1) {
1422 m_page->setPageScaleFactor(1, origin);
1423 for (auto* pluginView : m_pluginViews)
1424 pluginView->pageScaleFactorDidChange();
1427 pluginView->setPageScaleFactor(totalScale, origin);
1431 m_page->setPageScaleFactor(totalScale, origin);
1433 // We can't early return before setPageScaleFactor because the origin might be different.
1434 if (!willChangeScaleFactor)
1437 for (auto* pluginView : m_pluginViews)
1438 pluginView->pageScaleFactorDidChange();
1440 if (m_drawingArea->layerTreeHost())
1441 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1443 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1446 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1448 double totalScale = scale * viewScaleFactor();
1449 if (totalScale == totalScaleFactor())
1452 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1453 double scaleRatio = scale / pageScaleFactor();
1454 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1455 scalePage(scale, scrollPositionAtNewScale);
1458 double WebPage::totalScaleFactor() const
1460 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1461 if (pluginView && pluginView->handlesPageScaleFactor())
1462 return pluginView->pageScaleFactor();
1464 return m_page->pageScaleFactor();
1467 double WebPage::pageScaleFactor() const
1469 return totalScaleFactor() / viewScaleFactor();
1472 double WebPage::viewScaleFactor() const
1474 return m_page->viewScaleFactor();
1477 void WebPage::scaleView(double scale)
1479 if (viewScaleFactor() == scale)
1482 float pageScale = pageScaleFactor();
1484 IntPoint scrollPositionAtNewScale;
1485 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1486 double scaleRatio = scale / viewScaleFactor();
1487 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1488 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1491 m_page->setViewScaleFactor(scale);
1492 scalePage(pageScale, scrollPositionAtNewScale);
1496 void WebPage::scaleViewAndUpdateGeometryFenced(double scale, IntSize viewSize, uint64_t callbackID)
1499 m_drawingArea->updateGeometry(viewSize, IntSize(), false, MachSendRight());
1500 m_drawingArea->replyWithFenceAfterNextFlush(callbackID);
1504 void WebPage::setDeviceScaleFactor(float scaleFactor)
1506 if (scaleFactor == m_page->deviceScaleFactor())
1509 m_page->setDeviceScaleFactor(scaleFactor);
1511 // Tell all our plug-in views that the device scale factor changed.
1513 for (auto* pluginView : m_pluginViews)
1514 pluginView->setDeviceScaleFactor(scaleFactor);
1516 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1519 if (m_findController.isShowingOverlay()) {
1520 // We must have updated layout to get the selection rects right.
1522 m_findController.deviceScaleFactorDidChange();
1525 if (m_drawingArea->layerTreeHost())
1526 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1529 float WebPage::deviceScaleFactor() const
1531 return m_page->deviceScaleFactor();
1534 void WebPage::setUseFixedLayout(bool fixed)
1536 // Do not overwrite current settings if initially setting it to false.
1537 if (m_useFixedLayout == fixed)
1539 m_useFixedLayout = fixed;
1542 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1544 #if USE(COORDINATED_GRAPHICS)
1545 m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1546 m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1547 m_page->settings().setDelegatesPageScaling(fixed);
1548 m_page->settings().setScrollingCoordinatorEnabled(fixed);
1551 #if USE(COORDINATED_GRAPHICS) && ENABLE(SMOOTH_SCROLLING)
1552 // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1553 // Ensure we don't do animated scrolling in the WebProcess in that case.
1554 m_page->settings().setScrollAnimatorEnabled(!fixed);
1557 FrameView* view = mainFrameView();
1561 #if USE(COORDINATED_GRAPHICS)
1562 view->setDelegatesScrolling(fixed);
1563 view->setPaintsEntireContents(fixed);
1565 view->setUseFixedLayout(fixed);
1567 setFixedLayoutSize(IntSize());
1569 send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1572 void WebPage::setFixedLayoutSize(const IntSize& size)
1574 FrameView* view = mainFrameView();
1575 if (!view || view->fixedLayoutSize() == size)
1578 view->setFixedLayoutSize(size);
1580 send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1583 IntSize WebPage::fixedLayoutSize() const
1585 FrameView* view = mainFrameView();
1588 return view->fixedLayoutSize();
1591 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1595 m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1598 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1600 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1603 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1605 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1608 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1610 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1613 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1615 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1616 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1619 void WebPage::setPaginationMode(uint32_t mode)
1621 Pagination pagination = m_page->pagination();
1622 pagination.mode = static_cast<Pagination::Mode>(mode);
1623 m_page->setPagination(pagination);
1626 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1628 Pagination pagination = m_page->pagination();
1629 pagination.behavesLikeColumns = behavesLikeColumns;
1630 m_page->setPagination(pagination);
1633 void WebPage::setPageLength(double pageLength)
1635 Pagination pagination = m_page->pagination();
1636 pagination.pageLength = pageLength;
1637 m_page->setPagination(pagination);
1640 void WebPage::setGapBetweenPages(double gap)
1642 Pagination pagination = m_page->pagination();
1643 pagination.gap = gap;
1644 m_page->setPagination(pagination);
1647 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1649 auto& webProcess = WebProcess::singleton();
1650 InjectedBundle* injectedBundle = webProcess.injectedBundle();
1651 if (!injectedBundle)
1654 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1658 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1661 m_headerBanner->detachFromPage();
1663 m_headerBanner = pageBanner;
1666 m_headerBanner->addToPage(PageBanner::Header, this);
1669 PageBanner* WebPage::headerPageBanner()
1671 return m_headerBanner.get();
1674 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1677 m_footerBanner->detachFromPage();
1679 m_footerBanner = pageBanner;
1682 m_footerBanner->addToPage(PageBanner::Footer, this);
1685 PageBanner* WebPage::footerPageBanner()
1687 return m_footerBanner.get();
1690 void WebPage::hidePageBanners()
1693 m_headerBanner->hide();
1695 m_footerBanner->hide();
1698 void WebPage::showPageBanners()
1701 m_headerBanner->showIfHidden();
1703 m_footerBanner->showIfHidden();
1705 #endif // !PLATFORM(IOS)
1707 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1709 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1710 snapshotOptions |= SnapshotOptionsShareable;
1712 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1714 ShareableBitmap::Handle handle;
1716 image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly);
1718 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1721 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1723 IntRect snapshotRect = rect;
1724 IntSize bitmapSize = snapshotRect.size();
1725 double scaleFactor = additionalScaleFactor;
1726 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1727 scaleFactor *= corePage()->deviceScaleFactor();
1728 bitmapSize.scale(scaleFactor);
1730 return snapshotAtSize(rect, bitmapSize, options);
1733 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1735 Frame* coreFrame = m_mainFrame->coreFrame();
1739 FrameView* frameView = coreFrame->view();
1743 IntRect snapshotRect = rect;
1744 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1745 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1746 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1748 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1749 if (!snapshot->bitmap())
1752 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1754 Color documentBackgroundColor = frameView->documentBackgroundColor();
1755 Color backgroundColor = (coreFrame->settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView->baseBackgroundColor();
1756 graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor, ColorSpaceDeviceRGB);
1758 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1759 double deviceScaleFactor = corePage()->deviceScaleFactor();
1760 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1761 scaleFactor /= deviceScaleFactor;
1764 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1765 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1767 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1768 if (options & SnapshotOptionsExcludeSelectionHighlighting)
1769 shouldPaintSelection = FrameView::ExcludeSelection;
1771 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1772 if (options & SnapshotOptionsInViewCoordinates)
1773 coordinateSpace = FrameView::ViewCoordinates;
1775 frameView->paintContentsForSnapshot(graphicsContext.get(), snapshotRect, shouldPaintSelection, coordinateSpace);
1777 if (options & SnapshotOptionsPaintSelectionRectangle) {
1778 FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1779 graphicsContext->setStrokeColor(Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
1780 graphicsContext->strokeRect(selectionRectangle, 1);
1783 return snapshot.release();
1786 PassRefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
1788 Frame* coreFrame = m_mainFrame->coreFrame();
1792 FrameView* frameView = coreFrame->view();
1796 if (!node.renderer())
1799 LayoutRect topLevelRect;
1800 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
1801 if (snapshotRect.isEmpty())
1804 double scaleFactor = 1;
1805 IntSize snapshotSize = snapshotRect.size();
1806 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
1807 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
1808 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
1809 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
1812 RefPtr<WebImage> snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options));
1813 if (!snapshot->bitmap())
1816 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1818 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1819 double deviceScaleFactor = corePage()->deviceScaleFactor();
1820 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1821 scaleFactor /= deviceScaleFactor;
1824 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1825 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1827 Color savedBackgroundColor = frameView->baseBackgroundColor();
1828 frameView->setBaseBackgroundColor(Color::transparent);
1829 frameView->setNodeToDraw(&node);
1831 frameView->paintContentsForSnapshot(graphicsContext.get(), snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
1833 frameView->setBaseBackgroundColor(savedBackgroundColor);
1834 frameView->setNodeToDraw(nullptr);
1836 return snapshot.release();
1839 void WebPage::pageDidScroll()
1842 if (!m_inDynamicSizeUpdate)
1843 m_dynamicSizeUpdateHistory.clear();
1845 m_uiClient->pageDidScroll(this);
1847 m_pageScrolledHysteresis.impulse();
1849 send(Messages::WebPageProxy::PageDidScroll());
1852 void WebPage::pageStoppedScrolling()
1854 // Maintain the current history item's scroll position up-to-date.
1855 if (Frame* frame = m_mainFrame->coreFrame())
1856 frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
1859 #if USE(COORDINATED_GRAPHICS)
1860 void WebPage::pageDidRequestScroll(const IntPoint& point)
1862 #if USE(COORDINATED_GRAPHICS_THREADED)
1863 drawingArea()->scroll(IntRect(point, IntSize()), IntSize());
1864 #elif USE(COORDINATED_GRAPHICS_MULTIPROCESS)
1865 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1870 #if ENABLE(CONTEXT_MENUS)
1871 WebContextMenu* WebPage::contextMenu()
1874 m_contextMenu = WebContextMenu::create(this);
1875 return m_contextMenu.get();
1878 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1880 corePage()->contextMenuController().clearContextMenu();
1882 // Simulate a mouse click to generate the correct menu.
1883 PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick);
1884 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
1888 return contextMenu();
1894 static const WebEvent* g_currentEvent = 0;
1896 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1897 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1898 // platform events passed to the event handler code.
1899 const WebEvent* WebPage::currentEvent()
1901 return g_currentEvent;
1904 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
1906 auto* drawingArea = this->drawingArea();
1910 drawingArea->setLayerTreeStateIsFrozen(frozen);
1913 bool WebPage::markLayersVolatileImmediatelyIfPossible()
1915 auto* drawingArea = this->drawingArea();
1919 return drawingArea->markLayersVolatileImmediatelyIfPossible();
1922 class CurrentEvent {
1924 explicit CurrentEvent(const WebEvent& event)
1925 : m_previousCurrentEvent(g_currentEvent)
1927 g_currentEvent = &event;
1932 g_currentEvent = m_previousCurrentEvent;
1936 const WebEvent* m_previousCurrentEvent;
1939 #if ENABLE(CONTEXT_MENUS)
1940 static bool isContextClick(const PlatformMouseEvent& event)
1943 return WebEventFactory::shouldBeHandledAsContextClick(event);
1945 return event.button() == WebCore::RightButton;
1949 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1951 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
1952 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
1954 Frame* frame = &page->corePage()->mainFrame();
1955 if (result.innerNonSharedNode())
1956 frame = result.innerNonSharedNode()->document().frame();
1958 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
1960 page->contextMenu()->show();
1966 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1968 Frame& frame = page->corePage()->mainFrame();
1972 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1974 switch (platformMouseEvent.type()) {
1975 case PlatformEvent::MousePressed: {
1976 #if ENABLE(CONTEXT_MENUS)
1977 if (isContextClick(platformMouseEvent))
1978 page->corePage()->contextMenuController().clearContextMenu();
1981 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
1982 #if ENABLE(CONTEXT_MENUS)
1983 if (isContextClick(platformMouseEvent))
1984 handled = handleContextMenuEvent(platformMouseEvent, page);
1988 case PlatformEvent::MouseReleased:
1989 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
1991 case PlatformEvent::MouseMoved:
1992 if (onlyUpdateScrollbars)
1993 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
1994 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
1996 case PlatformEvent::MouseForceChanged:
1997 case PlatformEvent::MouseForceDown:
1998 case PlatformEvent::MouseForceUp:
1999 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2002 ASSERT_NOT_REACHED();
2007 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2009 m_page->pageThrottler().didReceiveUserInput();
2011 bool shouldHandleEvent = true;
2013 #if ENABLE(CONTEXT_MENUS)
2014 // Don't try to handle any pending mouse events if a context menu is showing.
2015 if (m_isShowingContextMenu)
2016 shouldHandleEvent = false;
2018 #if ENABLE(DRAG_SUPPORT)
2019 if (m_isStartingDrag)
2020 shouldHandleEvent = false;
2023 if (!shouldHandleEvent) {
2024 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2028 bool handled = false;
2031 if (!handled && m_headerBanner)
2032 handled = m_headerBanner->mouseEvent(mouseEvent);
2033 if (!handled && m_footerBanner)
2034 handled = m_footerBanner->mouseEvent(mouseEvent);
2035 #endif // !PLATFORM(IOS)
2037 if (!handled && canHandleUserEvents()) {
2038 CurrentEvent currentEvent(mouseEvent);
2040 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2041 // button is currently pressed. It is possible that neither of those things will be true since on
2042 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2043 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2044 // efficient scrollbars-only version of the event.
2045 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
2046 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
2049 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2052 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
2054 #if ENABLE(DRAG_SUPPORT)
2055 if (m_isStartingDrag)
2056 messageSenderConnection()->waitForAndDispatchImmediately<Messages::WebPage::DidStartDrag>(messageSenderDestinationID(), std::chrono::seconds(60));
2061 if (!handled && m_headerBanner)
2062 handled = m_headerBanner->mouseEvent(mouseEvent);
2063 if (!handled && m_footerBanner)
2064 handled = m_footerBanner->mouseEvent(mouseEvent);
2065 #endif // !PLATFORM(IOS)
2068 CurrentEvent currentEvent(mouseEvent);
2070 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2071 // button is currently pressed. It is possible that neither of those things will be true since on
2072 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2073 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2074 // efficient scrollbars-only version of the event.
2075 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
2076 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
2080 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2082 Frame& frame = page->mainFrame();
2086 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2087 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2090 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2092 m_page->pageThrottler().didReceiveUserInput();
2094 bool handled = false;
2096 if (canHandleUserEvents()) {
2097 CurrentEvent currentEvent(wheelEvent);
2099 handled = handleWheelEvent(wheelEvent, m_page.get());
2101 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2104 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
2106 CurrentEvent currentEvent(wheelEvent);
2108 if (ScrollingCoordinator* scrollingCoordinator = m_page->scrollingCoordinator())
2109 scrollingCoordinator->commitTreeStateIfNeeded();
2111 handled = handleWheelEvent(wheelEvent, m_page.get());
2114 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2116 if (!page->mainFrame().view())
2119 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2120 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2121 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2124 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2126 m_page->pageThrottler().didReceiveUserInput();
2128 bool handled = false;
2130 if (canHandleUserEvents()) {
2131 CurrentEvent currentEvent(keyboardEvent);
2133 handled = handleKeyEvent(keyboardEvent, m_page.get());
2134 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2136 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2138 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2141 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
2143 CurrentEvent currentEvent(keyboardEvent);
2145 Frame& frame = m_page->focusController().focusedOrMainFrame();
2146 frame.document()->updateStyleIfNeeded();
2148 handled = handleKeyEvent(keyboardEvent, m_page.get());
2150 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2153 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
2155 bool isEnabled = false;
2157 Frame& frame = m_page->focusController().focusedOrMainFrame();
2158 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2159 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2161 Editor::Command command = frame.editor().command(commandName);
2162 state = command.state();
2163 isEnabled = command.isSupported() && command.isEnabled();
2166 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2169 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2171 executeEditingCommand(commandName, argument);
2174 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2176 for (const auto& itemState : itemStates)
2177 WebBackForwardListProxy::addItemFromUIProcess(itemState.identifier, toHistoryItem(itemState.pageState), m_pageID);
2180 #if ENABLE(TOUCH_EVENTS)
2181 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2183 if (!page->mainFrame().view())
2186 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2190 #if ENABLE(IOS_TOUCH_EVENTS)
2191 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2193 RefPtr<Frame> oldFocusedFrame = m_page->focusController().focusedFrame();
2194 RefPtr<Element> oldFocusedElement = oldFocusedFrame ? oldFocusedFrame->document()->focusedElement() : nullptr;
2195 m_userIsInteracting = true;
2197 m_lastInteractionLocation = touchEvent.position();
2198 CurrentEvent currentEvent(touchEvent);
2199 handled = handleTouchEvent(touchEvent, m_page.get());
2201 RefPtr<Frame> newFocusedFrame = m_page->focusController().focusedFrame();
2202 RefPtr<Element> newFocusedElement = newFocusedFrame ? newFocusedFrame->document()->focusedElement() : nullptr;
2204 // If the focus has not changed, we need to notify the client anyway, since it might be
2205 // necessary to start assisting the node.
2206 // If the node has been focused by JavaScript without user interaction, the
2207 // keyboard is not on screen.
2208 if (newFocusedElement && newFocusedElement == oldFocusedElement)
2209 elementDidFocus(newFocusedElement.get());
2211 m_userIsInteracting = false;
2214 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2216 EventDispatcher::TouchEventQueue queuedEvents;
2217 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2218 dispatchAsynchronousTouchEvents(queuedEvents);
2220 dispatchTouchEvent(touchEvent, handled);
2222 #elif ENABLE(TOUCH_EVENTS)
2223 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2226 bool handled = false;
2227 if (canHandleUserEvents()) {
2228 CurrentEvent currentEvent(touchEvent);
2230 handled = handleTouchEvent(touchEvent, m_page.get());
2232 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2235 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
2237 CurrentEvent currentEvent(touchEvent);
2238 handled = handleTouchEvent(touchEvent, m_page.get());
2242 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2244 return page->userInputBridge().scrollRecursively(direction, granularity);
2247 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2249 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2252 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2254 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2257 void WebPage::centerSelectionInVisibleArea()
2259 Frame& frame = m_page->focusController().focusedOrMainFrame();
2260 frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
2261 m_findController.showFindIndicatorInSelection();
2264 #if ENABLE(REMOTE_INSPECTOR)
2265 void WebPage::setAllowsRemoteInspection(bool allow)
2267 m_page->setRemoteInspectionAllowed(allow);
2271 void WebPage::setDrawsBackground(bool drawsBackground)
2273 if (m_drawsBackground == drawsBackground)
2276 m_drawsBackground = drawsBackground;
2278 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2279 if (FrameView* view = coreFrame->view())
2280 view->setTransparent(!drawsBackground);
2283 m_drawingArea->pageBackgroundTransparencyChanged();
2284 m_drawingArea->setNeedsDisplay();
2287 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
2289 if (m_drawsTransparentBackground == drawsTransparentBackground)
2292 m_drawsTransparentBackground = drawsTransparentBackground;
2294 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2295 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2296 if (FrameView* view = coreFrame->view())
2297 view->setBaseBackgroundColor(backgroundColor);
2300 m_drawingArea->pageBackgroundTransparencyChanged();
2301 m_drawingArea->setNeedsDisplay();
2304 void WebPage::setTopContentInset(float contentInset)
2306 if (contentInset == m_page->topContentInset())
2309 m_page->setTopContentInset(contentInset);
2311 for (auto* pluginView : m_pluginViews)
2312 pluginView->topContentInsetDidChange();
2315 void WebPage::viewWillStartLiveResize()
2320 // FIXME: This should propagate to all ScrollableAreas.
2321 Frame& frame = m_page->focusController().focusedOrMainFrame();
2322 if (FrameView* view = frame.view())
2323 view->willStartLiveResize();
2326 void WebPage::viewWillEndLiveResize()
2331 // FIXME: This should propagate to all ScrollableAreas.
2332 Frame& frame = m_page->focusController().focusedOrMainFrame();
2333 if (FrameView* view = frame.view())
2334 view->willEndLiveResize();
2337 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, uint64_t callbackID)
2343 TemporaryChange<bool> userIsInteractingChange { m_userIsInteracting, true };
2346 Frame& frame = m_page->focusController().focusedOrMainFrame();
2347 frame.document()->setFocusedElement(0);
2349 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2350 PlatformKeyboardEvent platformEvent(platform(event));
2351 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2352 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2354 send(Messages::WebPageProxy::VoidCallback(callbackID));
2358 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2359 send(Messages::WebPageProxy::VoidCallback(callbackID));
2362 void WebPage::setCanStartMediaTimerFired()
2365 m_page->setCanStartMedia(true);
2368 inline bool WebPage::canHandleUserEvents() const
2370 #if USE(COORDINATED_GRAPHICS)
2371 // Should apply only if the area was frozen by didStartPageTransition().
2372 return !m_drawingArea->layerTreeStateIsFrozen();
2377 void WebPage::updateIsInWindow(bool isInitialState)
2379 bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2382 m_setCanStartMediaTimer.stop();
2383 m_page->setCanStartMedia(false);
2385 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2386 if (!isInitialState)
2387 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2389 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2390 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2391 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2392 if (m_mayStartMediaWhenInWindow)
2393 m_setCanStartMediaTimer.startOneShot(0);
2395 WebProcess::singleton().pageDidEnterWindow(m_pageID);
2402 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState, const Vector<uint64_t>& callbackIDs)
2404 ViewState::Flags changed = m_viewState ^ viewState;
2405 m_viewState = viewState;
2408 updateUserActivity();
2410 m_page->setViewState(viewState);
2411 for (auto* pluginView : m_pluginViews)
2412 pluginView->viewStateDidChange(changed);
2414 m_drawingArea->viewStateDidChange(changed, wantsDidUpdateViewState, callbackIDs);
2416 if (changed & ViewState::IsInWindow)
2420 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2422 m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2424 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2426 for (auto* pluginView : m_pluginViews)
2427 pluginView->setLayerHostingMode(m_layerHostingMode);
2430 void WebPage::setSessionID(SessionID sessionID)
2432 if (sessionID.isEphemeral())
2433 WebProcess::singleton().ensurePrivateBrowsingSession(sessionID);
2434 m_page->setSessionID(sessionID);
2437 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, uint64_t downloadID)
2439 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2442 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID);
2445 void WebPage::didStartPageTransition()
2447 m_drawingArea->setLayerTreeStateIsFrozen(true);
2449 m_hasFocusedDueToUserInteraction = false;
2453 void WebPage::didCompletePageTransition()
2455 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
2456 // m_mainFrame can be null since r170163.
2457 if (m_mainFrame && m_mainFrame->coreFrame()->view()->delegatesScrolling()) {
2458 // Wait until the UI process sent us the visible rect it wants rendered.
2459 send(Messages::WebPageProxy::PageTransitionViewportReady());
2463 m_drawingArea->setLayerTreeStateIsFrozen(false);
2466 void WebPage::show()
2468 send(Messages::WebPageProxy::ShowPage());
2471 String WebPage::userAgent(const URL& webCoreURL) const
2473 return userAgent(nullptr, webCoreURL);
2476 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2478 if (frame && m_loaderClient.client().userAgentForURL) {
2479 API::String* apiString = m_loaderClient.userAgentForURL(frame, API::URL::create(webcoreURL).ptr());
2481 return apiString->string();
2484 String userAgent = platformUserAgent(webcoreURL);
2485 if (!userAgent.isEmpty())
2490 void WebPage::setUserAgent(const String& userAgent)
2492 m_userAgent = userAgent;
2495 void WebPage::suspendActiveDOMObjectsAndAnimations()
2497 m_page->suspendActiveDOMObjectsAndAnimations();
2500 void WebPage::resumeActiveDOMObjectsAndAnimations()
2502 m_page->resumeActiveDOMObjectsAndAnimations();
2505 IntPoint WebPage::screenToRootView(const IntPoint& point)
2507 IntPoint windowPoint;
2508 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2512 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2515 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2520 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2522 IntPoint windowPoint;
2523 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2527 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2530 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2535 KeyboardUIMode WebPage::keyboardUIMode()
2537 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
2538 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2541 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2543 // NOTE: We need to be careful when running scripts that the objects we depend on don't
2544 // disappear during script execution.
2546 RefPtr<SerializedScriptValue> serializedResultValue;
2547 JSLockHolder lock(JSDOMWindow::commonVM());
2548 bool hadException = true;
2549 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) {
2550 hadException = false;
2551 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
2552 toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr);
2555 IPC::DataReference dataReference;
2556 if (serializedResultValue)
2557 dataReference = serializedResultValue->data();
2558 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, callbackID));
2561 void WebPage::getContentsAsString(uint64_t callbackID)
2563 String resultString = m_mainFrame->contentsAsString();
2564 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2568 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2570 RefPtr<SharedBuffer> buffer = useBinaryEncoding
2571 ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2572 : MHTMLArchive::generateMHTMLData(m_page.get());
2574 // FIXME: Use SharedBufferDataReference.
2575 IPC::DataReference dataReference;
2577 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2578 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2582 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2584 String resultString = renderTreeExternalRepresentation();
2585 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2588 static Frame* frameWithSelection(Page* page)
2590 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2591 if (frame->selection().isRange())
2598 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2601 RetainPtr<CFDataRef> data;
2602 if (Frame* frame = frameWithSelection(m_page.get()))
2603 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
2606 IPC::DataReference dataReference;
2609 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2611 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2614 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2616 String resultString = m_mainFrame->selectionAsString();
2617 if (resultString.isEmpty())
2618 resultString = m_mainFrame->contentsAsString();
2619 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2622 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2624 String resultString;
2625 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2626 resultString = frame->source();
2628 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2631 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2633 RefPtr<SharedBuffer> buffer;
2634 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2635 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
2636 buffer = pluginView->liveResourceData();
2638 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
2639 buffer = loader->mainResourceData();
2643 // FIXME: Use SharedBufferDataReference.
2644 IPC::DataReference dataReference;
2646 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2647 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2650 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2652 DocumentLoader* loader = frame->loader().documentLoader();
2656 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2660 return subresource->data();
2663 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2665 RefPtr<SharedBuffer> buffer;
2666 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2667 URL resourceURL(URL(), resourceURLString);
2668 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2670 // Try to get the resource data from the cache.
2671 buffer = cachedResponseDataForURL(resourceURL);
2675 // FIXME: Use SharedBufferDataReference.
2676 IPC::DataReference dataReference;
2678 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2679 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2682 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2685 RetainPtr<CFDataRef> data;
2686 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2687 data = frame->webArchiveData(nullptr, nullptr);
2689 UNUSED_PARAM(frameID);
2692 IPC::DataReference dataReference;
2695 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2697 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2700 void WebPage::forceRepaintWithoutCallback()
2702 m_drawingArea->forceRepaint();
2705 void WebPage::forceRepaint(uint64_t callbackID)
2707 if (m_drawingArea->forceRepaintAsync(callbackID))
2710 forceRepaintWithoutCallback();
2711 send(Messages::WebPageProxy::VoidCallback(callbackID));
2714 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2716 WebPreferencesStore::removeTestRunnerOverrides();
2717 updatePreferences(store);
2720 void WebPage::updatePreferences(const WebPreferencesStore& store)
2722 Settings& settings = m_page->settings();
2724 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2725 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2726 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2727 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2729 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2732 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2735 // FIXME: This should be generated from macro expansion for all preferences,
2736 // but we currently don't match the naming of WebCore exactly so we are
2737 // handrolling the boolean and integer preferences until that is fixed.
2739 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2741 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2743 #undef INITIALIZE_SETTINGS
2745 settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2746 settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2747 settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2748 settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2749 settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2750 settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2751 settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));
2752 settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2753 settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2754 settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2755 settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2756 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
2757 setSessionID(SessionID::legacyPrivateSessionID());
2758 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
2759 setSessionID(SessionID::defaultSessionID());
2760 settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2761 settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
2762 settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2763 settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2764 settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2765 settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2766 settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2767 settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey()));
2768 #if ENABLE(WEB_ARCHIVE)
2769 settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2771 settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2772 settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2773 settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2774 settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2775 settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2776 settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2777 settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2778 settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2779 settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2780 settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2781 settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2783 settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2784 settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2785 settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2786 settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2787 settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2788 settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2789 settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2790 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2791 settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2793 settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2794 settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
2795 settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
2796 settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
2797 settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2798 settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2799 settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2800 settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey()));
2802 settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2803 settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
2804 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
2805 RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey()));
2807 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2808 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2809 settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2810 settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2811 settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2812 settings.setRequiresUserGestureForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey()));
2813 settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey()));
2814 settings.setAllowsPictureInPictureMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey()));
2815 settings.setMediaControlsScaleWithPageZoom(store.getBoolValueForKey(WebPreferencesKey::mediaControlsScaleWithPageZoomKey()));
2816 settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2817 settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2818 settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2819 #if ENABLE(SMOOTH_SCROLLING)
2820 settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2822 settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
2823 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2824 settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2826 settings.setHttpEquivEnabled(store.getBoolValueForKey(WebPreferencesKey::httpEquivEnabledKey()));
2828 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2830 #if ENABLE(FULLSCREEN_API)
2831 settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2834 #if USE(AVFOUNDATION)
2835 settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2839 settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2842 #if PLATFORM(IOS) && HAVE(AVKIT)
2843 settings.setAVKitEnabled(true);
2846 #if ENABLE(IOS_TEXT_AUTOSIZING)
2847 settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2850 #if ENABLE(WEB_AUDIO)
2851 settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2854 #if ENABLE(MEDIA_STREAM)
2855 settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2858 #if ENABLE(SERVICE_CONTROLS)
2859 settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2862 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2863 settings.setAllowsAirPlayForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsAirPlayForMediaPlaybackKey()));
2866 settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2867 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2868 settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2869 settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2870 settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2872 #if ENABLE(VIDEO_TRACK)
2873 settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2874 settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2875 settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2878 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2879 settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2882 settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2883 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2884 settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2886 settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2888 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2890 settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2891 settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2892 settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2893 settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2894 settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2896 #if ENABLE(TEXT_AUTOSIZING)
2897 settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2900 settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2901 settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2903 settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2904 settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2905 settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2907 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2908 settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2911 settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2912 settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2913 settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2914 settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2916 settings.setNewBlockInsideInlineModelEnabled(store.getBoolValueForKey(WebPreferencesKey::newBlockInsideInlineModelEnabledKey()));
2917 settings.setAntialiasedFontDilationEnabled(store.getBoolValueForKey(WebPreferencesKey::antialiasedFontDilationEnabledKey()));
2919 settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
2921 settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2923 #if ENABLE(MEDIA_SOURCE)
2924 settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2927 settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2929 settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2930 settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2931 settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2932 settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2934 settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2935 settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2937 settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2938 settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2940 settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2942 settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
2945 settings.setUseImageDocumentForSubframePDF(true);
2948 settings.setLongMousePressEnabled(store.getBoolValueForKey(WebPreferencesKey::longMousePressEnabledKey()));
2951 RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
2954 #if ENABLE(SERVICE_CONTROLS)
2955 settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
2958 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
2959 if (m_processSuppressionEnabled != processSuppressionEnabled) {
2960 m_processSuppressionEnabled = processSuppressionEnabled;
2961 updateUserActivity();
2964 platformPreferencesDidChange(store);
2967 m_drawingArea->updatePreferences(store);
2970 m_viewportConfiguration.setCanIgnoreScalingConstraints(store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey()));
2971 m_viewportConfiguration.setForceAlwaysUserScalable(store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
2976 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2978 layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2979 layerTransaction.setScrollOrigin(corePage()->mainFrame().view()->scrollOrigin());
2980 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2981 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2982 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2984 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2985 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
2986 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
2987 layerTransaction.setAllowsUserScaling(allowsUserScaling());
2990 layerTransaction.setScrollPosition(corePage()->mainFrame().view()->scrollPosition());
2994 void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp)
2997 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) {
2998 std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
2999 m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero();
3001 m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20));
3004 UNUSED_PARAM(timestamp);
3009 WebInspector* WebPage::inspector()
3014 m_inspector = WebInspector::create(this);
3015 return m_inspector.get();
3018 WebInspectorUI* WebPage::inspectorUI()
3023 m_inspectorUI = WebInspectorUI::create(this);
3024 return m_inspectorUI.get();
3028 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
3030 if (!m_videoFullscreenManager)
3031 m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
3032 return m_videoFullscreenManager.get();
3035 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3037 m_page->setAllowsMediaDocumentInlinePlayback(allows);
3041 #if ENABLE(FULLSCREEN_API)
3042 WebFullScreenManager* WebPage::fullScreenManager()
3044 if (!m_fullScreenManager)
3045 m_fullScreenManager = WebFullScreenManager::create(this);
3046 return m_fullScreenManager.get();
3050 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3052 if (m_notificationPermissionRequestManager)
3053 return m_notificationPermissionRequestManager.get();
3055 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3056 return m_notificationPermissionRequestManager.get();
3059 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
3060 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
3062 Node* node = evt->target()->toNode();
3064 Frame* frame = node->document().frame();
3067 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
3071 Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
3073 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
3074 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
3075 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
3076 // (e.g. Tab that inserts a Tab character, or Enter).
3077 return !command.isTextInsertion() && command.execute(evt);
3080 if (command.execute(evt))
3083 // Don't allow text insertion for nodes that cannot edit.
3084 if (!frame->editor().canEdit())
3087 // Don't insert null or control characters as they can result in unexpected behaviour
3088 if (evt->charCode() < ' ')
3091 return frame->editor().insertText(evt->keyEvent()->text(), evt);
3095 #if ENABLE(DRAG_SUPPORT)
3098 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
3101 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3102 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3108 case DragControllerActionEntered: {
3109 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3110 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3113 case DragControllerActionUpdated: {
3114 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3115 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3118 case DragControllerActionExited:
3119 m_page->dragController().dragExited(dragData);
3122 case DragControllerActionPerformDragOperation: {
3123 m_page->dragController().performDragOperation(dragData);
3128 ASSERT_NOT_REACHED();
3130 // DragData does not delete its platformData so we need to do that here.
3131 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3136 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)
3139 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3143 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3145 case DragControllerActionEntered: {
3146 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3147 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3151 case DragControllerActionUpdated: {
3152 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3153 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3156 case DragControllerActionExited:
3157 m_page->dragController().dragExited(dragData);
3160 case DragControllerActionPerformDragOperation: {
3161 ASSERT(!m_pendingDropSandboxExtension);
3163 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
3164 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3165 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
3166 m_pendingDropExtensionsForFileUpload.append(extension);
3169 m_page->dragController().performDragOperation(dragData);
3171 // If we started loading a local file, the sandbox extension tracker would have adopted this
3172 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3173 m_pendingDropSandboxExtension = nullptr;
3175 m_pendingDropExtensionsForFileUpload.clear();
3180 ASSERT_NOT_REACHED();
3185 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3187 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3188 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3190 m_page->dragController().dragEnded();
3191 FrameView* view = m_page->mainFrame().view();
3194 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3195 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime(), 0);
3196 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3199 void WebPage::willPerformLoadDragDestinationAction()
3201 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
3204 void WebPage::mayPerformUploadDragDestinationAction()
3206 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3207 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3208 m_pendingDropExtensionsForFileUpload.clear();
3211 #endif // ENABLE(DRAG_SUPPORT)
3213 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3215 return m_undoStepMap.get(stepID);
3218 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3220 m_undoStepMap.set(stepID, entry);
3223 void WebPage::removeWebEditCommand(uint64_t stepID)
3225 m_undoStepMap.remove(stepID);
3228 void WebPage::unapplyEditCommand(uint64_t stepID)
3230 WebUndoStep* step = webUndoStep(stepID);
3234 step->step()->unapply();
3237 void WebPage::reapplyEditCommand(uint64_t stepID)
3239 WebUndoStep* step = webUndoStep(stepID);
3244 step->step()->reapply();
3248 void WebPage::didRemoveEditCommand(uint64_t commandID)
3250 removeWebEditCommand(commandID);
3253 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3255 m_activePopupMenu = menu;
3258 #if ENABLE(INPUT_TYPE_COLOR)
3259 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3261 m_activeColorChooser = colorChooser;
3264 void WebPage::didEndColorPicker()
3266 m_activeColorChooser->didEndChooser();
3269 void WebPage::didChooseColor(const WebCore::Color& color)
3271 m_activeColorChooser->didChooseColor(color);
3275 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
3277 m_activeOpenPanelResultListener = openPanelResultListener;
3280 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3282 return m_page->findString(target, options);
3285 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3287 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
3290 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3292 m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3295 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3297 m_findController.getImageForFindMatch(matchIndex);
3300 void WebPage::selectFindMatch(uint32_t matchIndex)
3302 m_findController.selectFindMatch(matchIndex);
3305 void WebPage::hideFindUI()
3307 m_findController.hideFindUI();
3310 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3312 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3315 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3317 changeSelectedIndex(newIndex);
3318 m_activePopupMenu = nullptr;
3321 void WebPage::changeSelectedIndex(int32_t index)
3323 if (!m_activePopupMenu)
3326 m_activePopupMenu->didChangeSelectedIndex(index);
3330 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3332 if (!m_activeOpenPanelResultListener)
3336 if (!iconData.isEmpty()) {
3337 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3338 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3339 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3340 icon = Icon::createIconForImage(imageRef.get());
3343 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3344 m_activeOpenPanelResultListener = nullptr;
3348 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3350 if (!m_activeOpenPanelResultListener)
3353 m_activeOpenPanelResultListener->didChooseFiles(files);
3354 m_activeOpenPanelResultListener = nullptr;
3357 void WebPage::didCancelForOpenPanel()
3359 m_activeOpenPanelResultListener = nullptr;
3362 #if ENABLE(SANDBOX_EXTENSIONS)
3363 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3365 bool result = SandboxExtension::consumePermanently(handle);
3367 // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3368 WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3373 #if ENABLE(GEOLOCATION)
3374 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3376 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3380 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3382 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3385 #if ENABLE(MEDIA_STREAM)
3386 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed, const String& deviceUIDVideo, const String& deviceUIDAudio)
3388 m_userMediaPermissionRequestManager.didReceiveUserMediaPermissionDecision(userMediaID, allowed, deviceUIDVideo, deviceUIDAudio);
3393 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3395 Frame& frame = m_page->focusController().focusedOrMainFrame();
3396 frame.editor().advanceToNextMisspelling(startBeforeSelection);
3400 void WebPage::changeSpellingToWord(const String& word)
3402 replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3405 void WebPage::unmarkAllMisspellings()
3407 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3408 if (Document* document = frame->document())
3409 document->markers().removeMarkers(DocumentMarker::Spelling);
3413 void WebPage::unmarkAllBadGrammar()
3415 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3416 if (Document* document = frame->document())
3417 document->markers().removeMarkers(DocumentMarker::Grammar);
3422 void WebPage::uppercaseWord()
3424 m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3427 void WebPage::lowercaseWord()
3429 m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3432 void WebPage::capitalizeWord()
3434 m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3438 void WebPage::setTextForActivePopupMenu(int32_t index)
3440 if (!m_activePopupMenu)
3443 m_activePopupMenu->setTextForIndex(index);
3447 void WebPage::failedToShowPopupMenu()
3449 if (!m_activePopupMenu)
3452 m_activePopupMenu->client()->popupDidHide();
3456 #if ENABLE(CONTEXT_MENUS)
3457 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3462 m_contextMenu->itemSelected(item);
3463 m_contextMenu = nullptr;
3467 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3469 bool selectReplacement = true;
3470 bool smartReplace = false;
3471 return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3475 void WebPage::clearSelection()
3477 m_page->focusController().focusedOrMainFrame().selection().clear();
3481 void WebPage::restoreSelectionInFocusedEditableElement()
3483 Frame& frame = m_page->focusController().focusedOrMainFrame();
3484 if (!frame.selection().isNone())
3487 if (auto document = frame.document()) {
3488 if (auto element = document->focusedElement())
3489 element->updateFocusAppearance(true /* restoreSelection */);
3493 bool WebPage::mainFrameHasCustomContentProvider() const
3495 if (Frame* frame = mainFrame()) {
3496 WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3497 ASSERT(webFrameLoaderClient);
3498 return webFrameLoaderClient->frameHasCustomContentProvider();
3504 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3506 m_mimeTypesWithCustomContentProviders.add(mimeType);
3509 void WebPage::updateMainFrameScrollOffsetPinning()
3511 Frame& frame = m_page->mainFrame();
3512 IntPoint scrollPosition = frame.view()->scrollPosition();
3513 IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3514 IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3516 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3517 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3518 bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3519 bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3521 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3522 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3524 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3525 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3526 m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3527 m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3531 void WebPage::mainFrameDidLayout()
3533 unsigned pageCount = m_page->pageCount();
3534 if (pageCount != m_cachedPageCount) {
3535 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3536 m_cachedPageCount = pageCount;
3540 m_viewGestureGeometryCollector.mainFrameDidLayout();
3543 if (FrameView* frameView = mainFrameView()) {
3544 IntSize newContentSize = frameView->contentsSizeRespectingOverflow();
3545 if (m_viewportConfiguration.contentsSize() != newContentSize) {
3546 m_viewportConfiguration.setContentsSize(newContentSize);
3547 viewportConfigurationChanged();
3550 m_findController.redraw();
3554 void WebPage::addPluginView(PluginView* pluginView)
3556 ASSERT(!m_pluginViews.contains(pluginView));
3558 m_pluginViews.add(pluginView);
3559 m_hasSeenPlugin = true;
3560 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3561 LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3562 m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3566 void WebPage::removePluginView(PluginView* pluginView)
3568 ASSERT(m_pluginViews.contains(pluginView));
3570 m_pluginViews.remove(pluginView);
3571 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3572 LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3576 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3579 m_hasCachedWindowFrame = false;
3581 send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3585 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3587 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3588 m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3589 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3590 m_accessibilityPosition = accessibilityViewCoordinates;
3592 // Tell all our plug-in views that the window and view frames have changed.
3593 for (auto* pluginView : m_pluginViews)
3594 pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3596 m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3600 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3602 m_mainFrameIsScrollable = isScrollable;
3603 m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3605 if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3606 frameView->setCanHaveScrollbars(isScrollable);
3607 frameView->setProhibitsScrolling(!isScrollable);
3611 bool WebPage::windowIsFocused() const
3613 return m_page->focusController().isActive();
3616 bool WebPage::windowAndWebPageAreFocused() const
3621 return m_page->focusController().isFocused() && m_page->focusController().isActive();
3624 void WebPage::didReceiveMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder)
3626 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
3627 if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
3629 m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
3634 if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
3635 if (WebInspector* inspector = this->inspector())
3636 inspector->didReceiveMessage(connection, decoder);
3640 if (decoder.messageReceiverName() == Messages::WebInspectorUI::messageReceiverName()) {
3641 if (WebInspectorUI* inspectorUI = this->inspectorUI())
3642 inspectorUI->didReceiveMessage(connection, decoder);
3646 #if ENABLE(FULLSCREEN_API)
3647 if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
3648 fullScreenManager()->didReceiveMessage(connection, decoder);
3653 didReceiveWebPageMessage(connection, decoder);
3656 void WebPage::didReceiveSyncMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder)
3658 didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
3661 InjectedBundleBackForwardList* WebPage::backForwardList()
3663 if (!m_backForwardList)
3664 m_backForwardList = InjectedBundleBackForwardList::create(this);
3665 return m_backForwardList.get();
3668 #if ENABLE(ASYNC_SCROLLING)
3669 ScrollingCoordinator* WebPage::scrollingCoordinator() const
3671 return m_page->scrollingCoordinator();
3675 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3680 void WebPage::SandboxExtensionTracker::invalidate()
3682 m_pendingProvisionalSandboxExtension = nullptr;
3684 if (m_provisionalSandboxExtension) {
3685 m_provisionalSandboxExtension->revoke();
3686 m_provisionalSandboxExtension = nullptr;
3689 if (m_committedSandboxExtension) {
3690 m_committedSandboxExtension->revoke();
3691 m_committedSandboxExtension = nullptr;
3695 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3697 setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3700 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3702 ASSERT_UNUSED(frame, frame->isMainFrame());
3704 setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3707 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3709 m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;
3712 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3714 ASSERT(frame->isMainFrame());
3716 FrameLoader& frameLoader = frame->coreFrame()->loader();
3717 FrameLoadType frameLoadType = frameLoader.loadType();
3719 // If the page is being reloaded, it should reuse whatever extension is committed.
3720 if (frameLoadType == FrameLoadType::Reload || frameLoadType == FrameLoadType::ReloadFromOrigin)
3723 DocumentLoader* documentLoader = frameLoader.documentLoader();
3724 DocumentLoader* provisionalDocumentLoader = frameLoader.provisionalDocumentLoader();
3725 if (!documentLoader || !provisionalDocumentLoader)
3728 if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3734 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3736 if (!frame->isMainFrame())
3739 // We should only reuse the commited sandbox extension if it is not null. It can be
3740 // null if the last load was for an error page.
3741 if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame))
3742 m_pendingProvisionalSandboxExtension = m_committedSandboxExtension;
3744 ASSERT(!m_provisionalSandboxExtension);
3746 m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3747 if (!m_provisionalSandboxExtension)
3750 ASSERT(!m_provisionalSandboxExtension || frame->coreFrame()->loader().provisionalDocumentLoader()->url().isLocalFile());
3752 m_provisionalSandboxExtension->consume();
3755 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3757 if (!frame->isMainFrame())
3760 if (m_committedSandboxExtension)
3761 m_committedSandboxExtension->revoke();
3763 m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3765 // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started.
3766 // This extension is not cleared, because it does not pertain to the failed load, and will be needed.
3769 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3771 if (!frame->isMainFrame())
3774 if (!m_provisionalSandboxExtension)
3777 m_provisionalSandboxExtension->revoke();
3778 m_provisionalSandboxExtension = nullptr;
3780 // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started
3781 // (notably, if the current one fails because the new one cancels it). This extension is not cleared,
3782 // because it does not pertain to the failed load, and will be needed.
3785 bool WebPage::hasLocalDataForURL(const URL& url)
3787 if (url.isLocalFile())
3790 DocumentLoader* documentLoader = m_page->mainFrame().loader().documentLoader();
3791 if (documentLoader && documentLoader->subresource(url))
3794 return platformHasLocalDataForURL(url);
3797 void WebPage::setCustomTextEncodingName(const String& encoding)
3799 m_page->mainFrame().loader().reloadWithOverrideEncoding(encoding);
3802 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3804 WebBackForwardListProxy::removeItem(itemID);
3809 bool WebPage::isSpeaking()
3812 return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3815 void WebPage::speak(const String& string)
3817 send(Messages::WebPageProxy::Speak(string));
3820 void WebPage::stopSpeaking()
3822 send(Messages::WebPageProxy::StopSpeaking());
3828 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3830 Document* document = coreFrame->document();
3831 if (!is<PluginDocument>(document))
3834 PluginView* pluginView = static_cast<PluginView*>(downcast<PluginDocument>(*document).pluginWidget());
3838 return pluginView->pdfDocumentForPrinting();
3840 #endif // PLATFORM(MAC)
3842 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3844 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3848 Frame* coreFrame = frame->coreFrame();
3853 if (pdfDocumentForPrintingFrame(coreFrame))
3855 #endif // PLATFORM(MAC)
3857 if (!m_printContext)
3858 m_printContext = std::make_unique<PrintContext>(coreFrame);
3860 drawingArea()->setLayerTreeStateIsFrozen(true);
3861 m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3863 float fullPageHeight;
3864 m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3867 if (!m_printOperation)
3868 m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3872 void WebPage::endPrinting()
3874 drawingArea()->setLayerTreeStateIsFrozen(false);
3875 m_printContext = nullptr;
3878 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3880 Vector<IntRect> resultPageRects;
3881 double resultTotalScaleFactorForPrinting = 1;
3882 computePagesForPrintingImpl(frameID, printInfo, resultPageRects, resultTotalScaleFactorForPrinting);
3883 send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3886 void WebPage::computePagesForPrintingImpl(uint64_t frameID, const PrintInfo& printInfo, Vector<WebCore::IntRect>& resultPageRects, double& resultTotalScaleFactorForPrinting)
3888 ASSERT(resultPageRects.isEmpty());
3890 beginPrinting(frameID, printInfo);
3892 if (m_printContext) {
3893 resultPageRects = m_printContext->pageRects();
3894 resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3898 computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3899 #endif // PLATFORM(COCOA)
3901 // If we're asked to print, we should actually print at least a blank page.
3902 if (resultPageRects.isEmpty())
3903 resultPageRects.append(IntRect(0, 0, 1, 1));
3907 void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, uint64_t callbackID)
3909 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3910 Frame* coreFrame = frame ? frame->coreFrame() : 0;
3912 RefPtr<WebImage> image;
3917 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3919 ASSERT(coreFrame->document()->printing());
3922 RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(imageSize, ShareableBitmap::SupportsAlpha);
3923 auto graphicsContext = bitmap->createGraphicsContext();
3925 float printingScale = static_cast<float>(imageSize.width()) / rect.width();
3926 graphicsContext->scale(FloatSize(printingScale, printingScale));
3929 if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3930 ASSERT(!m_printContext);
3931 graphicsContext->scale(FloatSize(1, -1));
3932 graphicsContext->translate(0, -rect.height());
3933 drawPDFDocument(graphicsContext->platformContext(), pdfDocument.get(), printInfo, rect);
3937 m_printContext->spoolRect(*graphicsContext, rect);
3940 image = WebImage::create(bitmap.release());
3944 ShareableBitmap::Handle handle;
3947 image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly);
3949 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
3952 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3954 RetainPtr<CFMutableDataRef> pdfPageData;
3955 drawPagesToPDFImpl(frameID, printInfo, first, count, pdfPageData);
3956 send(Messages::WebPageProxy::DataCallback(IPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3959 void WebPage::drawPagesToPDFImpl(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, RetainPtr<CFMutableDataRef>& pdfPageData)
3961 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3962 Frame* coreFrame = frame ? frame->coreFrame() : 0;
3964 pdfPageData = adoptCF(CFDataCreateMutable(0, 0));
3970 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3972 ASSERT(coreFrame->document()->printing());
3975 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3976 RetainPtr<CGDataConsumerRef> pdfDataConsumer = adoptCF(CGDataConsumerCreateWithCFData(pdfPageData.get()));
3978 CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3979 RetainPtr<CGContextRef> context = adoptCF(CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3982 if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3983 ASSERT(!m_printContext);
3984 drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3988 size_t pageCount = m_printContext->pageCount();
3989 for (uint32_t page = first; page < first + count; ++page) {
3990 if (page >= pageCount)
3993 RetainPtr<CFDictionaryRef> pageInfo = adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3994 CGPDFContextBeginPage(context.get(), pageInfo.get());
3996 GraphicsContext ctx(context.get());
3997 ctx.scale(FloatSize(1, -1));
3998 ctx.translate(0, -m_printContext->pageRect(page).height());
3999 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
4001 CGPDFContextEndPage(context.get());
4004 CGPDFContextClose(context.get());
4010 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
4012 beginPrinting(frameID, printInfo);
4013 if (m_printContext && m_printOperation) {
4014 m_printOperation->startPrint(m_printContext.get(), callbackID);
4018 send(Messages::WebPageProxy::VoidCallback(callbackID));
4021 void WebPage::didFinishPrintOperation(const WebCore::ResourceError& error, uint64_t callbackID)
4023 send(Messages::WebPageProxy::PrintFinishedCallback(error, callbackID));
4024 m_printOperation = nullptr;
4028 void WebPage::savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size)
4030 send(Messages::WebPageProxy::SavePDFToFileInDownloadsFolder(suggestedFilename, originatingURLString, IPC::DataReference(data, size)));
4034 void WebPage::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID)
4036 send(Messages::WebPageProxy::SavePDFToTemporaryFolderAndOpenWithNativeApplication(suggestedFilename, originatingURLString, IPC::DataReference(data, size), pdfUUID));
4040 void WebPage::addResourceRequest(unsigned long identifier, const WebCore::ResourceRequest& request)
4042 if (!request.url().protocolIsInHTTPFamily())
4045 if (m_mainFrameProgressCompleted && !ScriptController::processingUserGesture())
4048 ASSERT(!m_trackedNetworkResourceRequestIdentifiers.contains(identifier));
4049 bool wasEmpty = m_trackedNetworkResourceRequestIdentifiers.isEmpty();
4050 m_trackedNetworkResourceRequestIdentifiers.add(identifier);
4052 send(Messages::WebPageProxy::SetNetworkRequestsInProgress(true));
4055 void WebPage::removeResourceRequest(unsigned long identifier)
4057 if (!m_trackedNetworkResourceRequestIdentifiers.remove(identifier))
4060 if (m_trackedNetworkResourceRequestIdentifiers.isEmpty())
4061 send(Messages::WebPageProxy::SetNetworkRequestsInProgress(false));
4064 void WebPage::setMediaVolume(float volume)
4066 m_page->setMediaVolume(volume);
4069 void WebPage::setMuted(bool muted)
4071 m_page->setMuted(muted);
4074 #if ENABLE(MEDIA_SESSION)
4075 void WebPage::handleMediaEvent(uint32_t eventType)
4077 m_page->handleMediaEvent(static_cast<MediaEventType>(eventType));
4081 void WebPage::setMayStartMediaWhenInWindow(bool mayStartMedia)
4083 if (mayStartMedia == m_mayStartMediaWhenInWindow)
4086 m_mayStartMediaWhenInWindow = mayStartMedia;
4087 if (m_mayStartMediaWhenInWindow && m_page->isInWindow())
4088 m_setCanStartMediaTimer.startOneShot(0);
4091 void WebPage::runModal()
4095 if (m_isRunningModal)
4098 m_isRunningModal = true;
4099 send(Messages::WebPageProxy::RunModal());
4100 #if !ASSERT_DISABLED
4101 Ref<WebPage> protector(*this);
4104 ASSERT(!m_isRunningModal);
4107 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
4109 if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
4112 if (request.url().protocolIs("blob"))
4115 return platformCanHandleRequest(request);
4118 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
4119 void WebPage::commitPageTransitionViewport()
4121 m_drawingArea->setLayerTreeStateIsFrozen(false);
4126 void WebPage::handleAlternativeTextUIResult(const String& result)
4128 Frame& frame = m_page->focusController().focusedOrMainFrame();
4129 frame.editor().handleAlternativeTextUIResult(result);
4133 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
4135 mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time, WebCore::ForceAtClick));
4138 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
4140 mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time, WebCore::ForceAtClick));
4143 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
4145 mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time, 0));
4148 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
4150 Frame& frame = m_page->focusController().focusedOrMainFrame();
4151 if (!frame.editor().canEdit())
4154 Vector<CompositionUnderline> underlines;
4155 underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
4156 frame.editor().setComposition(compositionString, underlines, from, from + length);
4159 bool WebPage::hasCompositionForTesting()
4161 Frame& frame = m_page->focusController().focusedOrMainFrame();
4162 return frame.editor().hasComposition();
4165 void WebPage::confirmCompositionForTesting(const String& compositionString)
4167 Frame& frame = m_page->focusController().focusedOrMainFrame();
4168 if (!frame.editor().canEdit())
4171 if (compositionString.isNull())
4172 frame.editor().confirmComposition();