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"
44 #include "NetscapePlugin.h"
45 #include "NotificationPermissionRequestManager.h"
46 #include "PageBanner.h"
47 #include "PluginProcessAttributes.h"
48 #include "PluginProxy.h"
49 #include "PluginView.h"
50 #include "PrintInfo.h"
51 #include "SessionState.h"
52 #include "SessionStateConversion.h"
53 #include "SessionTracker.h"
54 #include "ShareableBitmap.h"
55 #include "VisitedLinkTableController.h"
56 #include "WKBundleAPICast.h"
57 #include "WKRetainPtr.h"
58 #include "WKSharedAPICast.h"
59 #include "WebAlternativeTextClient.h"
60 #include "WebBackForwardListItem.h"
61 #include "WebBackForwardListProxy.h"
62 #include "WebChromeClient.h"
63 #include "WebColorChooser.h"
64 #include "WebContextMenu.h"
65 #include "WebContextMenuClient.h"
66 #include "WebCoreArgumentCoders.h"
67 #include "WebDatabaseProvider.h"
68 #include "WebDiagnosticLoggingClient.h"
69 #include "WebDocumentLoader.h"
70 #include "WebDragClient.h"
71 #include "WebEditorClient.h"
73 #include "WebEventConversion.h"
74 #include "WebEventFactory.h"
76 #include "WebFrameLoaderClient.h"
77 #include "WebFullScreenManager.h"
78 #include "WebFullScreenManagerMessages.h"
79 #include "WebGeolocationClient.h"
81 #include "WebInspector.h"
82 #include "WebInspectorClient.h"
83 #include "WebInspectorMessages.h"
84 #include "WebInspectorUI.h"
85 #include "WebInspectorUIMessages.h"
86 #include "WebMediaKeyStorageManager.h"
87 #include "WebNotificationClient.h"
88 #include "WebOpenPanelResultListener.h"
89 #include "WebPageCreationParameters.h"
90 #include "WebPageGroupProxy.h"
91 #include "WebPageMessages.h"
92 #include "WebPageOverlay.h"
93 #include "WebPageProxyMessages.h"
94 #include "WebPlugInClient.h"
95 #include "WebPopupMenu.h"
96 #include "WebPreferencesDefinitions.h"
97 #include "WebPreferencesKeys.h"
98 #include "WebPreferencesStore.h"
99 #include "WebProcess.h"
100 #include "WebProcessPoolMessages.h"
101 #include "WebProcessProxyMessages.h"
102 #include "WebProgressTrackerClient.h"
103 #include "WebStorageNamespaceProvider.h"
104 #include "WebUndoStep.h"
105 #include "WebUserContentController.h"
106 #include "WebUserMediaClient.h"
107 #include <JavaScriptCore/APICast.h>
108 #include <WebCore/ArchiveResource.h>
109 #include <WebCore/Chrome.h>
110 #include <WebCore/ContextMenuController.h>
111 #include <WebCore/DataTransfer.h>
112 #include <WebCore/DatabaseManager.h>
113 #include <WebCore/DocumentFragment.h>
114 #include <WebCore/DocumentLoader.h>
115 #include <WebCore/DocumentMarkerController.h>
116 #include <WebCore/DragController.h>
117 #include <WebCore/DragData.h>
118 #include <WebCore/ElementIterator.h>
119 #include <WebCore/EventHandler.h>
120 #include <WebCore/FocusController.h>
121 #include <WebCore/FormState.h>
122 #include <WebCore/FrameLoadRequest.h>
123 #include <WebCore/FrameLoaderTypes.h>
124 #include <WebCore/FrameView.h>
125 #include <WebCore/HTMLFormElement.h>
126 #include <WebCore/HTMLInputElement.h>
127 #include <WebCore/HTMLPlugInElement.h>
128 #include <WebCore/HTMLPlugInImageElement.h>
129 #include <WebCore/HistoryController.h>
130 #include <WebCore/HistoryItem.h>
131 #include <WebCore/HitTestResult.h>
132 #include <WebCore/JSDOMWindow.h>
133 #include <WebCore/KeyboardEvent.h>
134 #include <WebCore/MIMETypeRegistry.h>
135 #include <WebCore/MainFrame.h>
136 #include <WebCore/MouseEvent.h>
137 #include <WebCore/Page.h>
138 #include <WebCore/PageConfiguration.h>
139 #include <WebCore/PageThrottler.h>
140 #include <WebCore/PlatformKeyboardEvent.h>
141 #include <WebCore/PluginDocument.h>
142 #include <WebCore/PrintContext.h>
143 #include <WebCore/Range.h>
144 #include <WebCore/RenderLayer.h>
145 #include <WebCore/RenderTreeAsText.h>
146 #include <WebCore/RenderView.h>
147 #include <WebCore/ResourceRequest.h>
148 #include <WebCore/ResourceResponse.h>
149 #include <WebCore/RuntimeEnabledFeatures.h>
150 #include <WebCore/SchemeRegistry.h>
151 #include <WebCore/ScriptController.h>
152 #include <WebCore/SerializedScriptValue.h>
153 #include <WebCore/SessionID.h>
154 #include <WebCore/Settings.h>
155 #include <WebCore/ShadowRoot.h>
156 #include <WebCore/SharedBuffer.h>
157 #include <WebCore/StyleProperties.h>
158 #include <WebCore/SubframeLoader.h>
159 #include <WebCore/SubstituteData.h>
160 #include <WebCore/TextIterator.h>
161 #include <WebCore/UserInputBridge.h>
162 #include <WebCore/VisiblePosition.h>
163 #include <WebCore/VisibleUnits.h>
164 #include <WebCore/markup.h>
165 #include <bindings/ScriptValue.h>
166 #include <profiler/ProfilerDatabase.h>
167 #include <runtime/JSCInlines.h>
168 #include <runtime/JSCJSValue.h>
169 #include <runtime/JSLock.h>
170 #include <wtf/RunLoop.h>
171 #include <wtf/TemporaryChange.h>
174 #include <WebCore/MHTMLArchive.h>
177 #if ENABLE(BATTERY_STATUS)
178 #include "WebBatteryClient.h"
181 #if ENABLE(VIBRATION)
182 #include "WebVibrationClient.h"
185 #if ENABLE(PROXIMITY_EVENTS)
186 #include "WebDeviceProximityClient.h"
190 #include "PDFPlugin.h"
191 #include "RemoteLayerTreeTransaction.h"
192 #include "WKStringCF.h"
193 #include <WebCore/LegacyWebArchive.h>
198 #include "DataObjectGtk.h"
199 #include "WebPrintOperationGtk.h"
203 #include "RemoteLayerTreeDrawingArea.h"
204 #include "WebVideoFullscreenManager.h"
205 #include <CoreGraphics/CoreGraphics.h>
206 #include <WebCore/CoreTextSPI.h>
207 #include <WebCore/Icon.h>
211 #include <wtf/RefCountedLeakCounter.h>
214 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
215 #include "LayerTreeHost.h"
218 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
219 #include "CoordinatedLayerTreeHostMessages.h"
222 #if ENABLE(VIDEO) && USE(GSTREAMER)
223 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
227 using namespace WebCore;
231 static const double pageScrollHysteresisSeconds = 0.3;
233 class SendStopResponsivenessTimer {
235 SendStopResponsivenessTimer(WebPage* page)
240 ~SendStopResponsivenessTimer()
242 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
249 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
251 Ref<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
253 Ref<WebPage> page = adoptRef(*new WebPage(pageID, parameters));
255 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
256 WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
261 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
263 , m_viewSize(parameters.viewSize)
264 , m_hasSeenPlugin(false)
265 , m_useFixedLayout(false)
266 , m_drawsBackground(true)
269 , m_tabToLinks(false)
270 , m_asynchronousPluginInitializationEnabled(false)
271 , m_asynchronousPluginInitializationEnabledForAllPlugins(false)
272 , m_artificialPluginInitializationDelayEnabled(false)
273 , m_scrollingPerformanceLoggingEnabled(false)
274 , m_mainFrameIsScrollable(true)
275 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
276 , m_readyToFindPrimarySnapshottedPlugin(false)
277 , m_didFindPrimarySnapshottedPlugin(false)
278 , m_numberOfPrimarySnapshotDetectionAttempts(0)
279 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
281 , m_layerHostingMode(parameters.layerHostingMode)
283 , m_pdfPluginEnabled(false)
284 , m_hasCachedWindowFrame(false)
285 , m_viewGestureGeometryCollector(*this)
286 #elif HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL))
287 , m_accessibilityObject(nullptr)
289 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
290 #if ENABLE(CONTEXT_MENUS)
291 , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
293 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
294 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
295 , m_findController(this)
296 #if ENABLE(INPUT_TYPE_COLOR)
297 , m_activeColorChooser(0)
299 , m_userContentController(parameters.userContentControllerID ? WebUserContentController::getOrCreate(parameters.userContentControllerID) : nullptr)
300 #if ENABLE(GEOLOCATION)
301 , m_geolocationPermissionRequestManager(this)
303 #if ENABLE(MEDIA_STREAM)
304 , m_userMediaPermissionRequestManager(*this)
306 , m_pageScrolledHysteresis([this](HysteresisState state) { if (state == HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisSeconds)
307 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
308 , m_canRunModal(parameters.canRunModal)
309 , m_isRunningModal(false)
310 #if ENABLE(DRAG_SUPPORT)
311 , m_isStartingDrag(false)
313 , m_cachedMainFrameIsPinnedToLeftSide(true)
314 , m_cachedMainFrameIsPinnedToRightSide(true)
315 , m_cachedMainFrameIsPinnedToTopSide(true)
316 , m_cachedMainFrameIsPinnedToBottomSide(true)
317 , m_canShortCircuitHorizontalWheelEvents(false)
318 , m_hasWheelEventHandlers(false)
319 , m_cachedPageCount(0)
320 , m_autoSizingShouldExpandToViewHeight(false)
321 #if ENABLE(CONTEXT_MENUS)
322 , m_isShowingContextMenu(false)
325 , m_selectionAnchor(Start)
326 , m_hasReceivedVisibleContentRectsAfterDidCommitLoad(false)
327 , m_scaleWasSetByUIProcess(false)
328 , m_userHasChangedPageScaleFactor(false)
329 , m_hasStablePageScaleFactor(true)
330 , m_userIsInteracting(false)
331 , m_hasPendingBlurNotification(false)
332 , m_useTestingViewportConfiguration(false)
333 , m_isInStableState(true)
334 , m_oldestNonStableUpdateVisibleContentRectsTimestamp(std::chrono::milliseconds::zero())
335 , m_estimatedLatency(std::chrono::milliseconds::zero())
336 , m_screenSize(parameters.screenSize)
337 , m_availableScreenSize(parameters.availableScreenSize)
338 , m_deviceOrientation(0)
339 , m_inDynamicSizeUpdate(false)
340 , m_volatilityTimer(*this, &WebPage::volatilityTimerFired)
342 , m_backgroundColor(Color::white)
343 , m_maximumRenderingSuppressionToken(0)
344 , m_scrollPinningBehavior(DoNotPin)
345 , m_useAsyncScrolling(false)
346 , m_viewState(parameters.viewState)
347 , m_processSuppressionEnabled(true)
348 , m_userActivity("Process suppression disabled for page.")
349 , m_pendingNavigationID(0)
351 , m_systemWebGLPolicy(WebGLAllowCreation)
353 , m_mainFrameProgressCompleted(false)
354 , m_shouldDispatchFakeMouseMoveEvents(true)
358 m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
361 Settings::setShouldManageAudioSessionCategory(true);
364 PageConfiguration pageConfiguration;
365 pageConfiguration.chromeClient = new WebChromeClient(this);
366 #if ENABLE(CONTEXT_MENUS)
367 pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
369 pageConfiguration.editorClient = new WebEditorClient(this);
370 #if ENABLE(DRAG_SUPPORT)
371 pageConfiguration.dragClient = new WebDragClient(this);
373 pageConfiguration.backForwardClient = WebBackForwardListProxy::create(this);
374 pageConfiguration.inspectorClient = new WebInspectorClient(this);
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(parameters.allowsRemoteInspection);
424 m_page->setRemoteInspectionNameOverride(parameters.remoteInspectionNameOverride);
427 m_page->setCanStartMedia(false);
428 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
430 m_page->setGroupName(m_pageGroup->identifier());
431 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
433 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
436 updatePreferences(parameters.store);
437 platformInitialize();
439 setUseFixedLayout(parameters.useFixedLayout);
441 setDrawsBackground(parameters.drawsBackground);
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);
526 m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
530 void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters)
532 if (m_viewState != parameters.viewState)
533 setViewState(parameters.viewState, false, Vector<uint64_t>());
534 if (m_layerHostingMode != parameters.layerHostingMode)
535 setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode));
538 void WebPage::setPageActivityState(PageActivityState::Flags activityState)
540 PageActivityState::Flags changed = m_activityState ^ activityState;
541 m_activityState = activityState;
544 updateUserActivity();
547 void WebPage::updateUserActivity()
549 // Start the activity to prevent AppNap if the page activity is in progress,
550 // the page is visible and non-idle, or process suppression is disabled.
551 if (m_activityState || !(m_viewState & ViewState::IsVisuallyIdle) || !m_processSuppressionEnabled)
552 m_userActivity.start();
554 m_userActivity.stop();
559 if (m_backForwardList)
560 m_backForwardList->detach();
564 auto& webProcess = WebProcess::singleton();
565 #if ENABLE(ASYNC_SCROLLING)
566 if (m_useAsyncScrolling)
567 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
572 m_sandboxExtensionTracker.invalidate();
574 for (auto* pluginView : m_pluginViews)
575 pluginView->webPageDestroyed();
579 m_headerBanner->detachFromPage();
581 m_footerBanner->detachFromPage();
582 #endif // !PLATFORM(IOS)
584 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
586 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
587 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
588 webProcess.removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID);
590 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
591 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
592 #if ENABLE(FULLSCREEN_API)
593 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
597 webPageCounter.decrement();
601 void WebPage::dummy(bool&)
605 IPC::Connection* WebPage::messageSenderConnection()
607 return WebProcess::singleton().parentProcessConnection();
610 uint64_t WebPage::messageSenderDestinationID()
615 #if ENABLE(CONTEXT_MENUS)
616 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient> contextMenuClient)
618 if (!contextMenuClient) {
619 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
623 m_contextMenuClient = WTF::move(contextMenuClient);
627 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* client)
629 m_editorClient.initialize(client);
632 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient> formClient)
635 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
639 m_formClient = WTF::move(formClient);
642 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client)
644 m_loaderClient.initialize(client);
646 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
647 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
648 // for backwards compatibility.
649 LayoutMilestones milestones = 0;
651 if (m_loaderClient.client().didFirstLayoutForFrame)
652 milestones |= WebCore::DidFirstLayout;
653 if (m_loaderClient.client().didFirstVisuallyNonEmptyLayoutForFrame)
654 milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
658 listenForLayoutMilestones(milestones);
661 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
663 m_policyClient.initialize(client);
666 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase* client)
668 m_resourceLoadClient.initialize(client);
671 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient> uiClient)
674 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
678 m_uiClient = WTF::move(uiClient);
681 #if ENABLE(FULLSCREEN_API)
682 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
684 m_fullScreenClient.initialize(client);
688 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase* client)
690 m_logDiagnosticMessageClient.initialize(client);
693 #if ENABLE(NETSCAPE_PLUGIN_API)
694 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
696 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
697 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
699 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
700 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
701 unsigned pluginArea = 0;
702 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
704 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
707 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
709 uint64_t pluginProcessToken;
710 uint32_t pluginLoadPolicy;
711 String unavailabilityDescription;
712 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)))
715 PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
716 bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
718 if (isBlockedPlugin || !pluginProcessToken) {
719 #if ENABLE(PDFKIT_PLUGIN)
720 String path = parameters.url.path();
721 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
722 RefPtr<PDFPlugin> pdfPlugin = PDFPlugin::create(frame);
723 return pdfPlugin.release();
730 if (isBlockedPlugin) {
731 bool replacementObscured = false;
732 if (is<RenderEmbeddedObject>(*pluginElement->renderer())) {
733 auto& renderObject = downcast<RenderEmbeddedObject>(*pluginElement->renderer());
734 renderObject.setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
735 replacementObscured = renderObject.isReplacementObscured();
736 renderObject.setUnavailablePluginIndicatorIsHidden(replacementObscured);
739 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
743 if (!pluginProcessToken)
746 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
747 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
750 #endif // ENABLE(NETSCAPE_PLUGIN_API)
752 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
753 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
755 return WebGLAllowCreation;
758 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
760 return WebGLAllowCreation;
764 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
766 Frame& frame = m_page->focusController().focusedOrMainFrame();
770 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
771 if (!pluginView->getSelectionString().isNull()) {
772 result.selectionIsNone = false;
773 result.selectionIsRange = true;
774 result.isInPlugin = true;
779 const VisibleSelection& selection = frame.selection().selection();
781 result.selectionIsNone = selection.isNone();
782 result.selectionIsRange = selection.isRange();
783 result.isContentEditable = selection.isContentEditable();
784 result.isContentRichlyEditable = selection.isContentRichlyEditable();
785 result.isInPasswordField = selection.isInPasswordField();
786 result.hasComposition = frame.editor().hasComposition();
787 result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange();
789 platformEditorState(frame, result, shouldIncludePostLayoutData);
794 String WebPage::renderTreeExternalRepresentation() const
796 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
799 String WebPage::renderTreeExternalRepresentationForPrinting() const
801 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
804 uint64_t WebPage::renderTreeSize() const
808 return m_page->renderTreeSize();
811 void WebPage::setTracksRepaints(bool trackRepaints)
813 if (FrameView* view = mainFrameView())
814 view->setTracksRepaints(trackRepaints);
817 bool WebPage::isTrackingRepaints() const
819 if (FrameView* view = mainFrameView())
820 return view->isTrackingRepaints();
825 void WebPage::resetTrackedRepaints()
827 if (FrameView* view = mainFrameView())
828 view->resetTrackedRepaints();
831 Ref<API::Array> WebPage::trackedRepaintRects()
833 FrameView* view = mainFrameView();
835 return API::Array::create();
837 Vector<RefPtr<API::Object>> repaintRects;
838 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
840 for (const auto& repaintRect : view->trackedRepaintRects())
841 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
843 return API::Array::create(WTF::move(repaintRects));
846 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
848 if (!frame.document()->isPluginDocument())
851 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
853 if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
856 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
860 PluginView* WebPage::pluginViewForFrame(Frame* frame)
862 if (!frame->document()->isPluginDocument())
865 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
866 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
870 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
872 Frame& frame = m_page->focusController().focusedOrMainFrame();
874 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
875 pluginView->handleEditingCommand(commandName, argument);
879 frame.editor().command(commandName).execute(argument);
882 void WebPage::setEditable(bool editable)
884 m_page->setEditable(editable);
885 m_page->setTabKeyCyclesThroughElements(!editable);
886 Frame& frame = m_page->focusController().focusedOrMainFrame();
888 frame.editor().applyEditingStyleToBodyElement();
889 // If the page is made editable and the selection is empty, set it to something.
890 if (frame.selection().isNone())
891 frame.selection().setSelectionFromNone();
895 bool WebPage::isEditingCommandEnabled(const String& commandName)
897 Frame& frame = m_page->focusController().focusedOrMainFrame();
899 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
900 return pluginView->isEditingCommandEnabled(commandName);
902 Editor::Command command = frame.editor().command(commandName);
903 return command.isSupported() && command.isEnabled();
906 void WebPage::clearMainFrameName()
908 if (Frame* frame = mainFrame())
909 frame->tree().clearName();
912 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
914 m_drawingArea->setRootCompositingLayer(layer);
917 void WebPage::exitAcceleratedCompositingMode()
919 m_drawingArea->setRootCompositingLayer(0);
922 void WebPage::close()
929 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
930 if (!mainWebFrame()->url().isEmpty())
931 reportUsedFeatures();
933 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
934 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
937 m_inspector->disconnectFromPage();
938 m_inspector = nullptr;
941 #if ENABLE(FULLSCREEN_API)
942 m_fullScreenManager = nullptr;
945 if (m_activePopupMenu) {
946 m_activePopupMenu->disconnectFromPage();
947 m_activePopupMenu = nullptr;
950 if (m_activeOpenPanelResultListener) {
951 m_activeOpenPanelResultListener->disconnectFromPage();
952 m_activeOpenPanelResultListener = nullptr;
955 #if ENABLE(INPUT_TYPE_COLOR)
956 if (m_activeColorChooser) {
957 m_activeColorChooser->disconnectFromPage();
958 m_activeColorChooser = nullptr;
963 if (m_printOperation) {
964 m_printOperation->disconnectFromPage();
965 m_printOperation = nullptr;
969 #if ENABLE(VIDEO) && USE(GSTREAMER)
970 if (m_installMediaPluginsCallback) {
971 m_installMediaPluginsCallback->invalidate();
972 m_installMediaPluginsCallback = nullptr;
976 m_sandboxExtensionTracker.invalidate();
978 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
979 m_determinePrimarySnapshottedPlugInTimer.stop();
982 #if ENABLE(CONTEXT_MENUS)
983 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
985 m_editorClient.initialize(0);
986 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
987 m_loaderClient.initialize(0);
988 m_policyClient.initialize(0);
989 m_resourceLoadClient.initialize(0);
990 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
991 #if ENABLE(FULLSCREEN_API)
992 m_fullScreenClient.initialize(0);
994 m_logDiagnosticMessageClient.initialize(0);
996 m_printContext = nullptr;
997 m_mainFrame->coreFrame()->loader().detachFromParent();
999 m_drawingArea = nullptr;
1001 bool isRunningModal = m_isRunningModal;
1002 m_isRunningModal = false;
1004 // The WebPage can be destroyed by this call.
1005 WebProcess::singleton().removeWebPage(m_pageID);
1007 WebProcess::singleton().updateActivePages();
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(),
1133 #if ENABLE(POINTER_LOCK)
1136 false, false, false, false, 0, nullptr, 0, nullptr);
1138 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1141 void WebPage::stopLoadingFrame(uint64_t frameID)
1143 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1147 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1150 void WebPage::stopLoading()
1152 SendStopResponsivenessTimer stopper(this);
1154 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1157 bool WebPage::defersLoading() const
1159 return m_page->defersLoading();
1162 void WebPage::setDefersLoading(bool defersLoading)
1164 m_page->setDefersLoading(defersLoading);
1167 void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, bool contentBlockersEnabled, const SandboxExtension::Handle& sandboxExtensionHandle)
1169 SendStopResponsivenessTimer stopper(this);
1171 ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1172 m_pendingNavigationID = navigationID;
1174 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1175 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin, contentBlockersEnabled);
1178 void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID)
1180 SendStopResponsivenessTimer stopper(this);
1182 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1187 ASSERT(!m_pendingNavigationID);
1188 m_pendingNavigationID = navigationID;
1190 m_page->goToItem(*item, FrameLoadType::Forward);
1193 void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID)
1195 SendStopResponsivenessTimer stopper(this);
1197 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1202 ASSERT(!m_pendingNavigationID);
1203 m_pendingNavigationID = navigationID;
1205 m_page->goToItem(*item, FrameLoadType::Back);
1208 void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID)
1210 SendStopResponsivenessTimer stopper(this);
1212 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1217 ASSERT(!m_pendingNavigationID);
1218 m_pendingNavigationID = navigationID;
1220 m_page->goToItem(*item, FrameLoadType::IndexedBackForward);
1223 void WebPage::tryRestoreScrollPosition()
1225 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1228 void WebPage::layoutIfNeeded()
1230 if (m_mainFrame->coreFrame()->view())
1231 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1234 WebPage* WebPage::fromCorePage(Page* page)
1236 return static_cast<WebChromeClient&>(page->chrome().client()).page();
1239 void WebPage::setSize(const WebCore::IntSize& viewSize)
1241 if (m_viewSize == viewSize)
1244 FrameView* view = m_page->mainFrame().view();
1245 view->resize(viewSize);
1246 m_drawingArea->setNeedsDisplay();
1248 m_viewSize = viewSize;
1250 #if USE(COORDINATED_GRAPHICS)
1251 if (view->useFixedLayout())
1252 sendViewportAttributesChanged();
1256 #if USE(COORDINATED_GRAPHICS)
1257 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1259 ASSERT(m_useFixedLayout);
1261 m_page->mainFrame().view()->setFixedVisibleContentRect(rect);
1264 void WebPage::sendViewportAttributesChanged()
1266 ASSERT(m_useFixedLayout);
1268 // Viewport properties have no impact on zero sized fixed viewports.
1269 if (m_viewSize.isEmpty())
1272 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1273 Settings& settings = m_page->settings();
1275 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1277 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1278 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1279 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1281 ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1283 FrameView* view = m_page->mainFrame().view();
1285 // If no layout was done yet set contentFixedOrigin to (0,0).
1286 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1288 // Put the width and height to the viewport width and height. In css units however.
1289 // Use FloatSize to avoid truncated values during scale.
1290 FloatSize contentFixedSize = m_viewSize;
1292 #if ENABLE(CSS_DEVICE_ADAPTATION)
1293 // CSS viewport descriptors might be applied to already affected viewport size
1294 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1295 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1298 contentFixedSize.scale(1 / attr.initialScale);
1299 setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1301 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1303 // This also takes care of the relayout.
1304 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1306 #if USE(COORDINATED_GRAPHICS_THREADED)
1307 if (m_drawingArea->layerTreeHost())
1308 m_drawingArea->layerTreeHost()->didChangeViewportProperties(attr);
1310 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1315 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1317 FrameView* frameView = m_page->mainFrame().view();
1319 IntPoint scrollPosition = frameView->scrollPosition();
1320 IntPoint maximumScrollPosition = frameView->maximumScrollPosition();
1322 // If the current scroll position in a direction is the max scroll position
1323 // we don't want to scroll at all.
1324 IntSize newScrollOffset;
1325 if (scrollPosition.x() < maximumScrollPosition.x())
1326 newScrollOffset.setWidth(scrollOffset.width());
1327 if (scrollPosition.y() < maximumScrollPosition.y())
1328 newScrollOffset.setHeight(scrollOffset.height());
1330 if (newScrollOffset.isZero())
1333 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1336 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1338 GraphicsContextStateSaver stateSaver(graphicsContext);
1339 graphicsContext.clip(rect);
1341 m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1344 double WebPage::textZoomFactor() const
1346 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1347 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1348 if (pluginView->handlesPageScaleFactor())
1349 return pluginView->pageScaleFactor();
1350 return pageScaleFactor();
1353 Frame* frame = m_mainFrame->coreFrame();
1356 return frame->textZoomFactor();
1359 void WebPage::setTextZoomFactor(double zoomFactor)
1361 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1362 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1363 if (pluginView->handlesPageScaleFactor())
1364 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1366 scalePage(zoomFactor, IntPoint());
1370 Frame* frame = m_mainFrame->coreFrame();
1373 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1376 double WebPage::pageZoomFactor() const
1378 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1379 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1380 if (pluginView->handlesPageScaleFactor())
1381 return pluginView->pageScaleFactor();
1382 return pageScaleFactor();
1385 Frame* frame = m_mainFrame->coreFrame();
1388 return frame->pageZoomFactor();
1391 void WebPage::setPageZoomFactor(double zoomFactor)
1393 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1394 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1395 if (pluginView->handlesPageScaleFactor())
1396 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1398 scalePage(zoomFactor, IntPoint());
1402 Frame* frame = m_mainFrame->coreFrame();
1405 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1408 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1410 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1411 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1412 if (pluginView->handlesPageScaleFactor())
1413 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1415 scalePage(pageZoomFactor, IntPoint());
1419 Frame* frame = m_mainFrame->coreFrame();
1422 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1425 void WebPage::windowScreenDidChange(uint32_t displayID)
1427 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1430 void WebPage::scalePage(double scale, const IntPoint& origin)
1432 double totalScale = scale * viewScaleFactor();
1433 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1436 if (willChangeScaleFactor) {
1437 if (!m_inDynamicSizeUpdate)
1438 m_dynamicSizeUpdateHistory.clear();
1439 m_scaleWasSetByUIProcess = false;
1442 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1443 if (pluginView && pluginView->handlesPageScaleFactor()) {
1444 // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1445 // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1446 if (m_page->pageScaleFactor() != 1) {
1447 m_page->setPageScaleFactor(1, origin);
1448 for (auto* pluginView : m_pluginViews)
1449 pluginView->pageScaleFactorDidChange();
1452 pluginView->setPageScaleFactor(totalScale, origin);
1456 m_page->setPageScaleFactor(totalScale, origin);
1458 // We can't early return before setPageScaleFactor because the origin might be different.
1459 if (!willChangeScaleFactor)
1462 for (auto* pluginView : m_pluginViews)
1463 pluginView->pageScaleFactorDidChange();
1465 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1466 if (m_drawingArea->layerTreeHost())
1467 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1470 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1473 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1475 double totalScale = scale * viewScaleFactor();
1476 if (totalScale == totalScaleFactor())
1479 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1480 double scaleRatio = scale / pageScaleFactor();
1481 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1482 scalePage(scale, scrollPositionAtNewScale);
1485 double WebPage::totalScaleFactor() const
1487 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1488 if (pluginView && pluginView->handlesPageScaleFactor())
1489 return pluginView->pageScaleFactor();
1491 return m_page->pageScaleFactor();
1494 double WebPage::pageScaleFactor() const
1496 return totalScaleFactor() / viewScaleFactor();
1499 double WebPage::viewScaleFactor() const
1501 return m_page->viewScaleFactor();
1504 void WebPage::scaleView(double scale)
1506 if (viewScaleFactor() == scale)
1509 float pageScale = pageScaleFactor();
1511 IntPoint scrollPositionAtNewScale;
1512 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1513 double scaleRatio = scale / viewScaleFactor();
1514 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1515 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1518 m_page->setViewScaleFactor(scale);
1519 scalePage(pageScale, scrollPositionAtNewScale);
1522 void WebPage::setDeviceScaleFactor(float scaleFactor)
1524 if (scaleFactor == m_page->deviceScaleFactor())
1527 m_page->setDeviceScaleFactor(scaleFactor);
1529 // Tell all our plug-in views that the device scale factor changed.
1531 for (auto* pluginView : m_pluginViews)
1532 pluginView->setDeviceScaleFactor(scaleFactor);
1534 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1537 if (m_findController.isShowingOverlay()) {
1538 // We must have updated layout to get the selection rects right.
1540 m_findController.deviceScaleFactorDidChange();
1543 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1544 if (m_drawingArea->layerTreeHost())
1545 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1549 float WebPage::deviceScaleFactor() const
1551 return m_page->deviceScaleFactor();
1554 void WebPage::setUseFixedLayout(bool fixed)
1556 // Do not overwrite current settings if initially setting it to false.
1557 if (m_useFixedLayout == fixed)
1559 m_useFixedLayout = fixed;
1562 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1564 #if USE(COORDINATED_GRAPHICS)
1565 m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1566 m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1567 m_page->settings().setDelegatesPageScaling(fixed);
1568 m_page->settings().setScrollingCoordinatorEnabled(fixed);
1571 #if USE(COORDINATED_GRAPHICS) && ENABLE(SMOOTH_SCROLLING)
1572 // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1573 // Ensure we don't do animated scrolling in the WebProcess in that case.
1574 m_page->settings().setScrollAnimatorEnabled(!fixed);
1577 FrameView* view = mainFrameView();
1581 #if USE(COORDINATED_GRAPHICS)
1582 view->setDelegatesScrolling(fixed);
1583 view->setPaintsEntireContents(fixed);
1585 view->setUseFixedLayout(fixed);
1587 setFixedLayoutSize(IntSize());
1589 send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1592 void WebPage::setFixedLayoutSize(const IntSize& size)
1594 FrameView* view = mainFrameView();
1595 if (!view || view->fixedLayoutSize() == size)
1598 view->setFixedLayoutSize(size);
1600 send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1603 IntSize WebPage::fixedLayoutSize() const
1605 FrameView* view = mainFrameView();
1608 return view->fixedLayoutSize();
1611 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1615 m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1618 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1620 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1623 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1625 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1628 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1630 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1633 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1635 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1636 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1639 void WebPage::setPaginationMode(uint32_t mode)
1641 Pagination pagination = m_page->pagination();
1642 pagination.mode = static_cast<Pagination::Mode>(mode);
1643 m_page->setPagination(pagination);
1646 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1648 Pagination pagination = m_page->pagination();
1649 pagination.behavesLikeColumns = behavesLikeColumns;
1650 m_page->setPagination(pagination);
1653 void WebPage::setPageLength(double pageLength)
1655 Pagination pagination = m_page->pagination();
1656 pagination.pageLength = pageLength;
1657 m_page->setPagination(pagination);
1660 void WebPage::setGapBetweenPages(double gap)
1662 Pagination pagination = m_page->pagination();
1663 pagination.gap = gap;
1664 m_page->setPagination(pagination);
1667 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1669 auto& webProcess = WebProcess::singleton();
1670 InjectedBundle* injectedBundle = webProcess.injectedBundle();
1671 if (!injectedBundle)
1674 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1678 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1681 m_headerBanner->detachFromPage();
1683 m_headerBanner = pageBanner;
1686 m_headerBanner->addToPage(PageBanner::Header, this);
1689 PageBanner* WebPage::headerPageBanner()
1691 return m_headerBanner.get();
1694 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1697 m_footerBanner->detachFromPage();
1699 m_footerBanner = pageBanner;
1702 m_footerBanner->addToPage(PageBanner::Footer, this);
1705 PageBanner* WebPage::footerPageBanner()
1707 return m_footerBanner.get();
1710 void WebPage::hidePageBanners()
1713 m_headerBanner->hide();
1715 m_footerBanner->hide();
1718 void WebPage::showPageBanners()
1721 m_headerBanner->showIfHidden();
1723 m_footerBanner->showIfHidden();
1725 #endif // !PLATFORM(IOS)
1727 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1729 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1730 snapshotOptions |= SnapshotOptionsShareable;
1732 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1734 ShareableBitmap::Handle handle;
1736 image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly);
1738 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1741 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1743 IntRect snapshotRect = rect;
1744 IntSize bitmapSize = snapshotRect.size();
1745 if (options & SnapshotOptionsPrinting) {
1746 ASSERT(additionalScaleFactor == 1);
1747 Frame* coreFrame = m_mainFrame->coreFrame();
1750 bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
1752 double scaleFactor = additionalScaleFactor;
1753 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1754 scaleFactor *= corePage()->deviceScaleFactor();
1755 bitmapSize.scale(scaleFactor);
1758 return snapshotAtSize(rect, bitmapSize, options);
1761 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1763 Frame* coreFrame = m_mainFrame->coreFrame();
1767 FrameView* frameView = coreFrame->view();
1771 IntRect snapshotRect = rect;
1772 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1773 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1774 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1776 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1777 if (!snapshot->bitmap())
1780 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1782 if (options & SnapshotOptionsPrinting) {
1783 PrintContext::spoolAllPagesWithBoundaries(*coreFrame, *graphicsContext, snapshotRect.size());
1784 return snapshot.release();
1787 Color documentBackgroundColor = frameView->documentBackgroundColor();
1788 Color backgroundColor = (coreFrame->settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView->baseBackgroundColor();
1789 graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
1791 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1792 double deviceScaleFactor = corePage()->deviceScaleFactor();
1793 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1794 scaleFactor /= deviceScaleFactor;
1797 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1798 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1800 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1801 if (options & SnapshotOptionsExcludeSelectionHighlighting)
1802 shouldPaintSelection = FrameView::ExcludeSelection;
1804 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1805 if (options & SnapshotOptionsInViewCoordinates)
1806 coordinateSpace = FrameView::ViewCoordinates;
1808 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
1810 if (options & SnapshotOptionsPaintSelectionRectangle) {
1811 FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1812 graphicsContext->setStrokeColor(Color(0xFF, 0, 0));
1813 graphicsContext->strokeRect(selectionRectangle, 1);
1816 return snapshot.release();
1819 PassRefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
1821 Frame* coreFrame = m_mainFrame->coreFrame();
1825 FrameView* frameView = coreFrame->view();
1829 if (!node.renderer())
1832 LayoutRect topLevelRect;
1833 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
1834 if (snapshotRect.isEmpty())
1837 double scaleFactor = 1;
1838 IntSize snapshotSize = snapshotRect.size();
1839 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
1840 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
1841 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
1842 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
1845 RefPtr<WebImage> snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options));
1846 if (!snapshot->bitmap())
1849 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1851 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1852 double deviceScaleFactor = corePage()->deviceScaleFactor();
1853 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1854 scaleFactor /= deviceScaleFactor;
1857 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1858 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1860 Color savedBackgroundColor = frameView->baseBackgroundColor();
1861 frameView->setBaseBackgroundColor(Color::transparent);
1862 frameView->setNodeToDraw(&node);
1864 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
1866 frameView->setBaseBackgroundColor(savedBackgroundColor);
1867 frameView->setNodeToDraw(nullptr);
1869 return snapshot.release();
1872 void WebPage::pageDidScroll()
1875 if (!m_inDynamicSizeUpdate)
1876 m_dynamicSizeUpdateHistory.clear();
1878 m_uiClient->pageDidScroll(this);
1880 m_pageScrolledHysteresis.impulse();
1882 send(Messages::WebPageProxy::PageDidScroll());
1885 void WebPage::pageStoppedScrolling()
1887 // Maintain the current history item's scroll position up-to-date.
1888 if (Frame* frame = m_mainFrame->coreFrame())
1889 frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
1892 #if USE(COORDINATED_GRAPHICS)
1893 void WebPage::pageDidRequestScroll(const IntPoint& point)
1895 #if USE(COORDINATED_GRAPHICS_THREADED)
1896 drawingArea()->scroll(IntRect(point, IntSize()), IntSize());
1897 #elif USE(COORDINATED_GRAPHICS_MULTIPROCESS)
1898 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1903 #if ENABLE(CONTEXT_MENUS)
1904 WebContextMenu* WebPage::contextMenu()
1907 m_contextMenu = WebContextMenu::create(this);
1908 return m_contextMenu.get();
1911 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1913 corePage()->contextMenuController().clearContextMenu();
1915 // Simulate a mouse click to generate the correct menu.
1916 PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick);
1917 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
1921 return contextMenu();
1927 static const WebEvent* g_currentEvent = 0;
1929 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1930 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1931 // platform events passed to the event handler code.
1932 const WebEvent* WebPage::currentEvent()
1934 return g_currentEvent;
1937 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
1939 auto* drawingArea = this->drawingArea();
1943 drawingArea->setLayerTreeStateIsFrozen(frozen);
1946 bool WebPage::markLayersVolatileImmediatelyIfPossible()
1948 auto* drawingArea = this->drawingArea();
1952 return drawingArea->markLayersVolatileImmediatelyIfPossible();
1955 class CurrentEvent {
1957 explicit CurrentEvent(const WebEvent& event)
1958 : m_previousCurrentEvent(g_currentEvent)
1960 g_currentEvent = &event;
1965 g_currentEvent = m_previousCurrentEvent;
1969 const WebEvent* m_previousCurrentEvent;
1972 #if ENABLE(CONTEXT_MENUS)
1973 static bool isContextClick(const PlatformMouseEvent& event)
1976 return WebEventFactory::shouldBeHandledAsContextClick(event);
1978 return event.button() == WebCore::RightButton;
1982 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1984 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
1985 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
1987 Frame* frame = &page->corePage()->mainFrame();
1988 if (result.innerNonSharedNode())
1989 frame = result.innerNonSharedNode()->document().frame();
1991 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
1993 page->contextMenu()->show();
1999 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
2001 Frame& frame = page->corePage()->mainFrame();
2005 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2007 switch (platformMouseEvent.type()) {
2008 case PlatformEvent::MousePressed: {
2009 #if ENABLE(CONTEXT_MENUS)
2010 if (isContextClick(platformMouseEvent))
2011 page->corePage()->contextMenuController().clearContextMenu();
2014 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2015 #if ENABLE(CONTEXT_MENUS)
2016 if (isContextClick(platformMouseEvent))
2017 handled = handleContextMenuEvent(platformMouseEvent, page);
2021 case PlatformEvent::MouseReleased:
2022 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2024 case PlatformEvent::MouseMoved:
2025 if (onlyUpdateScrollbars)
2026 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2027 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2029 case PlatformEvent::MouseForceChanged:
2030 case PlatformEvent::MouseForceDown:
2031 case PlatformEvent::MouseForceUp:
2032 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2035 ASSERT_NOT_REACHED();
2040 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2042 m_page->pageThrottler().didReceiveUserInput();
2044 bool shouldHandleEvent = true;
2046 #if ENABLE(CONTEXT_MENUS)
2047 // Don't try to handle any pending mouse events if a context menu is showing.
2048 if (m_isShowingContextMenu)
2049 shouldHandleEvent = false;
2051 #if ENABLE(DRAG_SUPPORT)
2052 if (m_isStartingDrag)
2053 shouldHandleEvent = false;
2056 if (!shouldHandleEvent) {
2057 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2061 bool handled = false;
2064 if (!handled && m_headerBanner)
2065 handled = m_headerBanner->mouseEvent(mouseEvent);
2066 if (!handled && m_footerBanner)
2067 handled = m_footerBanner->mouseEvent(mouseEvent);
2068 #endif // !PLATFORM(IOS)
2070 if (!handled && canHandleUserEvents()) {
2071 CurrentEvent currentEvent(mouseEvent);
2073 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2074 // button is currently pressed. It is possible that neither of those things will be true since on
2075 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2076 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2077 // efficient scrollbars-only version of the event.
2078 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
2079 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
2082 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2085 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2087 Frame& frame = page->mainFrame();
2091 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2092 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2095 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2097 m_page->pageThrottler().didReceiveUserInput();
2099 bool handled = false;
2101 if (canHandleUserEvents()) {
2102 CurrentEvent currentEvent(wheelEvent);
2104 handled = handleWheelEvent(wheelEvent, m_page.get());
2106 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2109 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2111 if (!page->mainFrame().view())
2114 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2115 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2116 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2119 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2121 m_page->pageThrottler().didReceiveUserInput();
2123 bool handled = false;
2125 if (canHandleUserEvents()) {
2126 CurrentEvent currentEvent(keyboardEvent);
2128 handled = handleKeyEvent(keyboardEvent, m_page.get());
2129 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2131 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2133 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2136 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
2138 bool isEnabled = false;
2140 Frame& frame = m_page->focusController().focusedOrMainFrame();
2141 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2142 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2144 Editor::Command command = frame.editor().command(commandName);
2145 state = command.state();
2146 isEnabled = command.isSupported() && command.isEnabled();
2149 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2152 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2154 executeEditingCommand(commandName, argument);
2157 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2159 for (const auto& itemState : itemStates)
2160 WebBackForwardListProxy::addItemFromUIProcess(itemState.identifier, toHistoryItem(itemState.pageState), m_pageID);
2163 #if ENABLE(TOUCH_EVENTS)
2164 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2166 if (!page->mainFrame().view())
2169 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2173 #if ENABLE(IOS_TOUCH_EVENTS)
2174 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2176 m_userIsInteracting = true;
2178 m_lastInteractionLocation = touchEvent.position();
2179 CurrentEvent currentEvent(touchEvent);
2180 handled = handleTouchEvent(touchEvent, m_page.get());
2182 m_userIsInteracting = false;
2185 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2187 EventDispatcher::TouchEventQueue queuedEvents;
2188 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2189 dispatchAsynchronousTouchEvents(queuedEvents);
2191 dispatchTouchEvent(touchEvent, handled);
2193 #elif ENABLE(TOUCH_EVENTS)
2194 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2197 bool handled = false;
2198 if (canHandleUserEvents()) {
2199 CurrentEvent currentEvent(touchEvent);
2201 handled = handleTouchEvent(touchEvent, m_page.get());
2203 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2207 #if ENABLE(MAC_GESTURE_EVENTS)
2208 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2210 if (!page->mainFrame().view())
2213 return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2216 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2218 bool handled = false;
2219 if (canHandleUserEvents()) {
2220 CurrentEvent currentEvent(gestureEvent);
2221 handled = handleGestureEvent(gestureEvent, m_page.get());
2223 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2228 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2230 return page->userInputBridge().scrollRecursively(direction, granularity);
2233 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2235 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2238 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2240 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2243 void WebPage::centerSelectionInVisibleArea()
2245 Frame& frame = m_page->focusController().focusedOrMainFrame();
2246 frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
2247 m_findController.showFindIndicatorInSelection();
2250 #if ENABLE(REMOTE_INSPECTOR)
2251 void WebPage::setAllowsRemoteInspection(bool allow)
2253 m_page->setRemoteInspectionAllowed(allow);
2256 void WebPage::setRemoteInspectionNameOverride(const String& name)
2258 m_page->setRemoteInspectionNameOverride(name);
2262 void WebPage::setDrawsBackground(bool drawsBackground)
2264 if (m_drawsBackground == drawsBackground)
2267 m_drawsBackground = drawsBackground;
2269 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2270 if (FrameView* view = coreFrame->view())
2271 view->setTransparent(!drawsBackground);
2274 m_drawingArea->pageBackgroundTransparencyChanged();
2275 m_drawingArea->setNeedsDisplay();
2278 void WebPage::setTopContentInset(float contentInset)
2280 if (contentInset == m_page->topContentInset())
2283 m_page->setTopContentInset(contentInset);
2285 for (auto* pluginView : m_pluginViews)
2286 pluginView->topContentInsetDidChange();
2289 void WebPage::viewWillStartLiveResize()
2294 // FIXME: This should propagate to all ScrollableAreas.
2295 Frame& frame = m_page->focusController().focusedOrMainFrame();
2296 if (FrameView* view = frame.view())
2297 view->willStartLiveResize();
2300 void WebPage::viewWillEndLiveResize()
2305 // FIXME: This should propagate to all ScrollableAreas.
2306 Frame& frame = m_page->focusController().focusedOrMainFrame();
2307 if (FrameView* view = frame.view())
2308 view->willEndLiveResize();
2311 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, uint64_t callbackID)
2317 TemporaryChange<bool> userIsInteractingChange { m_userIsInteracting, true };
2320 Frame& frame = m_page->focusController().focusedOrMainFrame();
2321 frame.document()->setFocusedElement(0);
2323 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2324 PlatformKeyboardEvent platformEvent(platform(event));
2325 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2326 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2328 send(Messages::WebPageProxy::VoidCallback(callbackID));
2332 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2333 send(Messages::WebPageProxy::VoidCallback(callbackID));
2336 void WebPage::setCanStartMediaTimerFired()
2339 m_page->setCanStartMedia(true);
2342 inline bool WebPage::canHandleUserEvents() const
2344 #if USE(COORDINATED_GRAPHICS)
2345 // Should apply only if the area was frozen by didStartPageTransition().
2346 return !m_drawingArea->layerTreeStateIsFrozen();
2351 void WebPage::updateIsInWindow(bool isInitialState)
2353 bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2356 m_setCanStartMediaTimer.stop();
2357 m_page->setCanStartMedia(false);
2359 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2360 if (!isInitialState)
2361 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2363 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2364 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2365 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2366 if (m_mayStartMediaWhenInWindow)
2367 m_setCanStartMediaTimer.startOneShot(0);
2369 WebProcess::singleton().pageDidEnterWindow(m_pageID);
2376 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState, const Vector<uint64_t>& callbackIDs)
2378 ViewState::Flags changed = m_viewState ^ viewState;
2379 m_viewState = viewState;
2382 updateUserActivity();
2384 m_page->setViewState(viewState);
2385 for (auto* pluginView : m_pluginViews)
2386 pluginView->viewStateDidChange(changed);
2388 m_drawingArea->viewStateDidChange(changed, wantsDidUpdateViewState, callbackIDs);
2390 if (changed & ViewState::IsInWindow)
2394 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2396 m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2398 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2400 for (auto* pluginView : m_pluginViews)
2401 pluginView->setLayerHostingMode(m_layerHostingMode);
2404 void WebPage::setSessionID(SessionID sessionID)
2406 if (sessionID.isEphemeral())
2407 WebProcess::singleton().ensurePrivateBrowsingSession(sessionID);
2408 m_page->setSessionID(sessionID);
2411 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, DownloadID downloadID)
2413 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2416 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID);
2419 void WebPage::didStartPageTransition()
2421 m_drawingArea->setLayerTreeStateIsFrozen(true);
2423 m_hasFocusedDueToUserInteraction = false;
2427 void WebPage::didCompletePageTransition()
2429 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
2430 // m_mainFrame can be null since r170163.
2431 if (m_mainFrame && m_mainFrame->coreFrame()->view()->delegatesScrolling()) {
2432 // Wait until the UI process sent us the visible rect it wants rendered.
2433 send(Messages::WebPageProxy::PageTransitionViewportReady());
2437 m_drawingArea->setLayerTreeStateIsFrozen(false);
2440 void WebPage::show()
2442 send(Messages::WebPageProxy::ShowPage());
2445 String WebPage::userAgent(const URL& webCoreURL) const
2447 return userAgent(nullptr, webCoreURL);
2450 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2452 if (frame && m_loaderClient.client().userAgentForURL) {
2453 API::String* apiString = m_loaderClient.userAgentForURL(frame, API::URL::create(webcoreURL).ptr());
2455 return apiString->string();
2458 String userAgent = platformUserAgent(webcoreURL);
2459 if (!userAgent.isEmpty())
2464 void WebPage::setUserAgent(const String& userAgent)
2466 m_userAgent = userAgent;
2469 void WebPage::suspendActiveDOMObjectsAndAnimations()
2471 m_page->suspendActiveDOMObjectsAndAnimations();
2474 void WebPage::resumeActiveDOMObjectsAndAnimations()
2476 m_page->resumeActiveDOMObjectsAndAnimations();
2479 IntPoint WebPage::screenToRootView(const IntPoint& point)
2481 IntPoint windowPoint;
2482 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2486 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2489 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2494 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2496 IntPoint windowPoint;
2497 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2501 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2504 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2509 KeyboardUIMode WebPage::keyboardUIMode()
2511 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
2512 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2515 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2517 // NOTE: We need to be careful when running scripts that the objects we depend on don't
2518 // disappear during script execution.
2520 RefPtr<SerializedScriptValue> serializedResultValue;
2521 JSLockHolder lock(JSDOMWindow::commonVM());
2522 bool hadException = true;
2523 ExceptionDetails details;
2524 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true, &details).jsValue()) {
2525 hadException = false;
2526 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
2527 toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr);
2530 IPC::DataReference dataReference;
2531 if (serializedResultValue)
2532 dataReference = serializedResultValue->data();
2533 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
2536 void WebPage::getContentsAsString(uint64_t callbackID)
2538 String resultString = m_mainFrame->contentsAsString();
2539 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2543 void WebPage::getContentsAsMHTMLData(uint64_t callbackID)
2545 RefPtr<SharedBuffer> buffer = MHTMLArchive::generateMHTMLData(m_page.get());
2547 // FIXME: Use SharedBufferDataReference.
2548 IPC::DataReference dataReference;
2550 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2551 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2555 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2557 String resultString = renderTreeExternalRepresentation();
2558 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2561 static Frame* frameWithSelection(Page* page)
2563 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2564 if (frame->selection().isRange())
2571 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2574 RetainPtr<CFDataRef> data;
2575 if (Frame* frame = frameWithSelection(m_page.get()))
2576 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
2579 IPC::DataReference dataReference;
2582 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2584 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2587 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2589 String resultString = m_mainFrame->selectionAsString();
2590 if (resultString.isEmpty())
2591 resultString = m_mainFrame->contentsAsString();
2592 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2595 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2597 String resultString;
2598 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2599 resultString = frame->source();
2601 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2604 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2606 RefPtr<SharedBuffer> buffer;
2607 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2608 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
2609 buffer = pluginView->liveResourceData();
2611 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
2612 buffer = loader->mainResourceData();
2616 // FIXME: Use SharedBufferDataReference.
2617 IPC::DataReference dataReference;
2619 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2620 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2623 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2625 DocumentLoader* loader = frame->loader().documentLoader();
2629 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2633 return subresource->data();
2636 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2638 RefPtr<SharedBuffer> buffer;
2639 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2640 URL resourceURL(URL(), resourceURLString);
2641 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2643 // Try to get the resource data from the cache.
2644 buffer = cachedResponseDataForURL(resourceURL);
2648 // FIXME: Use SharedBufferDataReference.
2649 IPC::DataReference dataReference;
2651 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2652 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2655 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2658 RetainPtr<CFDataRef> data;
2659 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2660 data = frame->webArchiveData(nullptr, nullptr);
2662 UNUSED_PARAM(frameID);
2665 IPC::DataReference dataReference;
2668 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2670 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2673 void WebPage::forceRepaintWithoutCallback()
2675 m_drawingArea->forceRepaint();
2678 void WebPage::forceRepaint(uint64_t callbackID)
2680 if (m_drawingArea->forceRepaintAsync(callbackID))
2683 forceRepaintWithoutCallback();
2684 send(Messages::WebPageProxy::VoidCallback(callbackID));
2687 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2689 WebPreferencesStore::removeTestRunnerOverrides();
2690 updatePreferences(store);
2693 void WebPage::updatePreferences(const WebPreferencesStore& store)
2695 Settings& settings = m_page->settings();
2697 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2698 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2699 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2700 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2702 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2705 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2708 // FIXME: This should be generated from macro expansion for all preferences,
2709 // but we currently don't match the naming of WebCore exactly so we are
2710 // handrolling the boolean and integer preferences until that is fixed.
2712 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2714 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2716 #undef INITIALIZE_SETTINGS
2718 settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2719 settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2720 settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2721 settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2722 settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2723 settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2724 settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));
2725 settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2726 settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2727 settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2728 settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2729 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
2730 setSessionID(SessionID::legacyPrivateSessionID());
2731 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
2732 setSessionID(SessionID::defaultSessionID());
2733 settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2734 settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
2735 settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2736 settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2737 settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2738 settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2739 settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2740 settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey()));
2741 #if ENABLE(WEB_ARCHIVE)
2742 settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2744 settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2745 settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2746 settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2747 settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2748 settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2749 settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2750 settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2751 settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2752 settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2753 settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2754 settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2756 settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2757 settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2758 settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2759 settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2760 settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2761 settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2762 settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2763 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2764 settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2766 settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2767 settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
2768 settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
2769 settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
2770 settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2771 settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2772 settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2773 settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey()));
2774 settings.setUseGiantTiles(store.getBoolValueForKey(WebPreferencesKey::useGiantTilesKey()));
2776 settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2777 settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
2778 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
2779 RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey()));
2781 #if ENABLE(WEB_ANIMATIONS)
2782 RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled(store.getBoolValueForKey(WebPreferencesKey::webAnimationsEnabledKey()));
2784 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2785 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2786 settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2787 settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2788 settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2789 settings.setRequiresUserGestureForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey()));
2790 settings.setAudioPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
2791 settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey()));
2792 settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute(store.getBoolValueForKey(WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey()));
2793 settings.setInvisibleAutoplayNotPermitted(store.getBoolValueForKey(WebPreferencesKey::invisibleAutoplayNotPermittedKey()));
2794 settings.setMediaDataLoadsAutomatically(store.getBoolValueForKey(WebPreferencesKey::mediaDataLoadsAutomaticallyKey()));
2795 settings.setAllowsPictureInPictureMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey()));
2796 settings.setMediaControlsScaleWithPageZoom(store.getBoolValueForKey(WebPreferencesKey::mediaControlsScaleWithPageZoomKey()));
2797 settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2798 settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2799 settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2800 #if ENABLE(SMOOTH_SCROLLING)
2801 settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2803 settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
2804 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2805 settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2807 settings.setHttpEquivEnabled(store.getBoolValueForKey(WebPreferencesKey::httpEquivEnabledKey()));
2809 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2811 #if ENABLE(FULLSCREEN_API)
2812 settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2815 #if USE(AVFOUNDATION)
2816 settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2820 settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2823 #if PLATFORM(IOS) && HAVE(AVKIT)
2824 settings.setAVKitEnabled(true);
2827 #if ENABLE(IOS_TEXT_AUTOSIZING)
2828 settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2831 #if ENABLE(WEB_AUDIO)
2832 settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2835 #if ENABLE(MEDIA_STREAM)
2836 settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2839 #if ENABLE(SERVICE_CONTROLS)
2840 settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2843 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2844 settings.setAllowsAirPlayForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsAirPlayForMediaPlaybackKey()));
2847 #if ENABLE(RESOURCE_USAGE_OVERLAY)
2848 settings.setResourceUsageOverlayVisible(store.getBoolValueForKey(WebPreferencesKey::resourceUsageOverlayVisibleKey()));
2851 settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2852 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2853 settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2854 settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2855 settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2857 #if ENABLE(VIDEO_TRACK)
2858 settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2859 settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2860 settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2863 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2864 settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2867 settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2868 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2869 settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2871 settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2873 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2875 settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2876 settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2877 settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2878 settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2879 settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2881 #if ENABLE(TEXT_AUTOSIZING)
2882 settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2885 settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2886 settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2888 settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2889 settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2890 settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2892 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2893 settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2896 settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2897 settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2898 settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2899 settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2901 settings.setNewBlockInsideInlineModelEnabled(store.getBoolValueForKey(WebPreferencesKey::newBlockInsideInlineModelEnabledKey()));
2902 settings.setAntialiasedFontDilationEnabled(store.getBoolValueForKey(WebPreferencesKey::antialiasedFontDilationEnabledKey()));
2904 settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
2906 settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2908 #if ENABLE(MEDIA_SOURCE)
2909 settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2912 #if ENABLE(MEDIA_STREAM)
2913 settings.setMockCaptureDevicesEnabled(store.getBoolValueForKey(WebPreferencesKey::mockCaptureDevicesEnabledKey()));
2916 settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2918 settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2919 settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2920 settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2921 settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2923 settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2924 settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2926 settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2927 settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2929 settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2931 settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
2934 settings.setUseImageDocumentForSubframePDF(true);
2938 RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
2941 #if ENABLE(SERVICE_CONTROLS)
2942 settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
2945 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
2946 if (m_processSuppressionEnabled != processSuppressionEnabled) {
2947 m_processSuppressionEnabled = processSuppressionEnabled;
2948 updateUserActivity();
2951 platformPreferencesDidChange(store);
2954 m_drawingArea->updatePreferences(store);
2957 m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
2958 m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
2959 m_viewportConfiguration.setForceAlwaysUserScalable(store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
2964 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2966 layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2967 layerTransaction.setScrollOrigin(corePage()->mainFrame().view()->scrollOrigin());
2968 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2969 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2970 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2972 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2973 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
2974 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
2975 layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
2976 layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
2977 layerTransaction.setAllowsUserScaling(allowsUserScaling());
2980 layerTransaction.setScrollPosition(corePage()->mainFrame().view()->scrollPosition());
2984 void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp)
2987 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) {
2988 std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
2989 m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero();
2991 m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20));
2994 UNUSED_PARAM(timestamp);
2999 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3003 if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3004 m_inspector = WebInspector::create(this);
3005 return m_inspector.get();
3008 WebInspectorUI* WebPage::inspectorUI()
3013 m_inspectorUI = WebInspectorUI::create(*this);
3014 return m_inspectorUI.get();
3018 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
3020 if (!m_videoFullscreenManager)
3021 m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
3022 return m_videoFullscreenManager.get();
3025 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3027 m_page->setAllowsMediaDocumentInlinePlayback(allows);
3031 #if ENABLE(FULLSCREEN_API)
3032 WebFullScreenManager* WebPage::fullScreenManager()
3034 if (!m_fullScreenManager)
3035 m_fullScreenManager = WebFullScreenManager::create(this);
3036 return m_fullScreenManager.get();
3040 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3042 if (m_notificationPermissionRequestManager)
3043 return m_notificationPermissionRequestManager.get();
3045 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3046 return m_notificationPermissionRequestManager.get();
3049 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
3050 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
3052 Node* node = evt->target()->toNode();
3054 Frame* frame = node->document().frame();
3057 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
3061 Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
3063 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
3064 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
3065 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
3066 // (e.g. Tab that inserts a Tab character, or Enter).
3067 return !command.isTextInsertion() && command.execute(evt);
3070 if (command.execute(evt))
3073 // Don't allow text insertion for nodes that cannot edit.
3074 if (!frame->editor().canEdit())
3077 // Don't insert null or control characters as they can result in unexpected behaviour
3078 if (evt->charCode() < ' ')
3081 return frame->editor().insertText(evt->keyEvent()->text(), evt);
3085 #if ENABLE(DRAG_SUPPORT)
3088 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
3091 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3092 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3098 case DragControllerActionEntered: {
3099 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3100 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3103 case DragControllerActionUpdated: {
3104 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3105 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3108 case DragControllerActionExited:
3109 m_page->dragController().dragExited(dragData);
3112 case DragControllerActionPerformDragOperation: {
3113 m_page->dragController().performDragOperation(dragData);
3118 ASSERT_NOT_REACHED();
3120 // DragData does not delete its platformData so we need to do that here.
3121 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3126 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)
3129 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3133 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3135 case DragControllerActionEntered: {
3136 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3137 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3141 case DragControllerActionUpdated: {
3142 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3143 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3146 case DragControllerActionExited:
3147 m_page->dragController().dragExited(dragData);
3150 case DragControllerActionPerformDragOperation: {
3151 ASSERT(!m_pendingDropSandboxExtension);
3153 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
3154 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3155 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
3156 m_pendingDropExtensionsForFileUpload.append(extension);
3159 m_page->dragController().performDragOperation(dragData);
3161 // If we started loading a local file, the sandbox extension tracker would have adopted this
3162 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3163 m_pendingDropSandboxExtension = nullptr;
3165 m_pendingDropExtensionsForFileUpload.clear();
3170 ASSERT_NOT_REACHED();
3175 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3177 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3178 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3180 m_page->dragController().dragEnded();
3181 FrameView* view = m_page->mainFrame().view();
3184 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3185 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime(), 0);
3186 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3189 void WebPage::willPerformLoadDragDestinationAction()
3191 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
3194 void WebPage::mayPerformUploadDragDestinationAction()
3196 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3197 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3198 m_pendingDropExtensionsForFileUpload.clear();
3201 #endif // ENABLE(DRAG_SUPPORT)
3203 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3205 return m_undoStepMap.get(stepID);
3208 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3210 m_undoStepMap.set(stepID, entry);
3213 void WebPage::removeWebEditCommand(uint64_t stepID)
3215 m_undoStepMap.remove(stepID);
3218 void WebPage::unapplyEditCommand(uint64_t stepID)
3220 WebUndoStep* step = webUndoStep(stepID);
3224 step->step()->unapply();
3227 void WebPage::reapplyEditCommand(uint64_t stepID)
3229 WebUndoStep* step = webUndoStep(stepID);
3234 step->step()->reapply();
3238 void WebPage::didRemoveEditCommand(uint64_t commandID)
3240 removeWebEditCommand(commandID);
3243 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3245 m_activePopupMenu = menu;
3248 #if ENABLE(INPUT_TYPE_COLOR)
3249 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3251 m_activeColorChooser = colorChooser;
3254 void WebPage::didEndColorPicker()
3256 m_activeColorChooser->didEndChooser();
3259 void WebPage::didChooseColor(const WebCore::Color& color)
3261 m_activeColorChooser->didChooseColor(color);
3265 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
3267 m_activeOpenPanelResultListener = openPanelResultListener;
3270 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3272 return m_page->findString(target, options);
3275 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3277 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
3280 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3282 m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3285 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3287 m_findController.getImageForFindMatch(matchIndex);
3290 void WebPage::selectFindMatch(uint32_t matchIndex)
3292 m_findController.selectFindMatch(matchIndex);
3295 void WebPage::hideFindUI()
3297 m_findController.hideFindUI();
3300 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3302 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3305 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3307 changeSelectedIndex(newIndex);
3308 m_activePopupMenu = nullptr;
3311 void WebPage::changeSelectedIndex(int32_t index)
3313 if (!m_activePopupMenu)
3316 m_activePopupMenu->didChangeSelectedIndex(index);
3320 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3322 if (!m_activeOpenPanelResultListener)
3326 if (!iconData.isEmpty()) {
3327 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3328 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3329 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3330 icon = Icon::createIconForImage(imageRef.get());
3333 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3334 m_activeOpenPanelResultListener = nullptr;
3338 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3340 if (!m_activeOpenPanelResultListener)
3343 m_activeOpenPanelResultListener->didChooseFiles(files);
3344 m_activeOpenPanelResultListener = nullptr;
3347 void WebPage::didCancelForOpenPanel()
3349 m_activeOpenPanelResultListener = nullptr;
3352 #if ENABLE(SANDBOX_EXTENSIONS)
3353 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3355 bool result = SandboxExtension::consumePermanently(handle);
3357 // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3358 WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3363 #if ENABLE(GEOLOCATION)
3364 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3366 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3370 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3372 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3375 #if ENABLE(MEDIA_STREAM)
3376 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed, const String& audioDeviceUID, const String& videoDeviceUID)
3378 m_userMediaPermissionRequestManager.didReceiveUserMediaPermissionDecision(userMediaID, allowed, audioDeviceUID, videoDeviceUID);
3381 void WebPage::didCompleteUserMediaPermissionCheck(uint64_t userMediaID, bool allowed)
3383 m_userMediaPermissionRequestManager.didCompleteUserMediaPermissionCheck(userMediaID, allowed);
3388 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3390 Frame& frame = m_page->focusController().focusedOrMainFrame();
3391 frame.editor().advanceToNextMisspelling(startBeforeSelection);
3395 void WebPage::changeSpellingToWord(const String& word)
3397 replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3400 void WebPage::unmarkAllMisspellings()
3402 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3403 if (Document* document = frame->document())
3404 document->markers().removeMarkers(DocumentMarker::Spelling);
3408 void WebPage::unmarkAllBadGrammar()
3410 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3411 if (Document* document = frame->document())
3412 document->markers().removeMarkers(DocumentMarker::Grammar);
3417 void WebPage::uppercaseWord()
3419 m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3422 void WebPage::lowercaseWord()
3424 m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3427 void WebPage::capitalizeWord()
3429 m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3433 void WebPage::setTextForActivePopupMenu(int32_t index)
3435 if (!m_activePopupMenu)
3438 m_activePopupMenu->setTextForIndex(index);
3442 void WebPage::failedToShowPopupMenu()
3444 if (!m_activePopupMenu)
3447 m_activePopupMenu->client()->popupDidHide();
3451 #if ENABLE(CONTEXT_MENUS)
3452 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3457 m_contextMenu->itemSelected(item);
3458 m_contextMenu = nullptr;
3462 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3464 bool selectReplacement = true;
3465 bool smartReplace = false;
3466 return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3470 void WebPage::clearSelection()
3472 m_page->focusController().focusedOrMainFrame().selection().clear();
3476 void WebPage::restoreSelectionInFocusedEditableElement()
3478 Frame& frame = m_page->focusController().focusedOrMainFrame();
3479 if (!frame.selection().isNone())
3482 if (auto document = frame.document()) {
3483 if (auto element = document->focusedElement())
3484 element->updateFocusAppearance(SelectionRestorationMode::Restore, SelectionRevealMode::DoNotReveal);
3488 bool WebPage::mainFrameHasCustomContentProvider() const
3490 if (Frame* frame = mainFrame()) {
3491 WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3492 ASSERT(webFrameLoaderClient);
3493 return webFrameLoaderClient->frameHasCustomContentProvider();
3499 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3501 m_mimeTypesWithCustomContentProviders.add(mimeType);
3504 void WebPage::updateMainFrameScrollOffsetPinning()
3506 Frame& frame = m_page->mainFrame();
3507 IntPoint scrollPosition = frame.view()->scrollPosition();
3508 IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3509 IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3511 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3512 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3513 bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3514 bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3516 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3517 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3519 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3520 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3521 m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3522 m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3526 void WebPage::mainFrameDidLayout()
3528 unsigned pageCount = m_page->pageCount();
3529 if (pageCount != m_cachedPageCount) {
3530 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3531 m_cachedPageCount = pageCount;
3535 m_viewGestureGeometryCollector.mainFrameDidLayout();
3538 if (FrameView* frameView = mainFrameView()) {
3539 IntSize newContentSize = frameView->contentsSizeRespectingOverflow();
3540 if (m_viewportConfiguration.setContentsSize(newContentSize))
3541 viewportConfigurationChanged();