2 * Copyright (C) 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
3 * Copyright (C) 2012 Intel Corporation. All rights reserved.
4 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
19 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
25 * THE POSSIBILITY OF SUCH DAMAGE.
31 #include "Arguments.h"
32 #include "DataReference.h"
33 #include "DecoderAdapter.h"
34 #include "DragControllerAction.h"
35 #include "DrawingArea.h"
36 #include "DrawingAreaMessages.h"
37 #include "EditingRange.h"
38 #include "EditorState.h"
39 #include "EventDispatcher.h"
40 #include "InjectedBundle.h"
41 #include "InjectedBundleBackForwardList.h"
42 #include "InjectedBundleUserMessageCoders.h"
43 #include "LayerTreeHost.h"
45 #include "NetscapePlugin.h"
46 #include "NotificationPermissionRequestManager.h"
47 #include "PageBanner.h"
48 #include "PageOverlay.h"
49 #include "PluginProcessAttributes.h"
50 #include "PluginProxy.h"
51 #include "PluginView.h"
52 #include "PrintInfo.h"
53 #include "SessionState.h"
54 #include "ShareableBitmap.h"
55 #include "VisitedLinkTableController.h"
56 #include "WKSharedAPICast.h"
57 #include "WebAlternativeTextClient.h"
58 #include "WebBackForwardListItem.h"
59 #include "WebBackForwardListProxy.h"
60 #include "WebChromeClient.h"
61 #include "WebColorChooser.h"
62 #include "WebContextMenu.h"
63 #include "WebContextMenuClient.h"
64 #include "WebContextMessages.h"
65 #include "WebCoreArgumentCoders.h"
66 #include "WebDocumentLoader.h"
67 #include "WebDragClient.h"
68 #include "WebEditorClient.h"
70 #include "WebEventConversion.h"
72 #include "WebFrameLoaderClient.h"
73 #include "WebFullScreenManager.h"
74 #include "WebFullScreenManagerMessages.h"
75 #include "WebGeolocationClient.h"
77 #include "WebInspector.h"
78 #include "WebInspectorClient.h"
79 #include "WebInspectorMessages.h"
80 #include "WebNotificationClient.h"
81 #include "WebOpenPanelResultListener.h"
82 #include "WebPageCreationParameters.h"
83 #include "WebPageGroupProxy.h"
84 #include "WebPageMessages.h"
85 #include "WebPageProxyMessages.h"
86 #include "WebPlugInClient.h"
87 #include "WebPopupMenu.h"
88 #include "WebPreferencesStore.h"
89 #include "WebProcess.h"
90 #include "WebProcessProxyMessages.h"
91 #include "WebProgressTrackerClient.h"
92 #include <JavaScriptCore/APICast.h>
93 #include <WebCore/ArchiveResource.h>
94 #include <WebCore/Chrome.h>
95 #include <WebCore/ContextMenuController.h>
96 #include <WebCore/DatabaseManager.h>
97 #include <WebCore/DocumentFragment.h>
98 #include <WebCore/DocumentLoader.h>
99 #include <WebCore/DocumentMarkerController.h>
100 #include <WebCore/DragController.h>
101 #include <WebCore/DragData.h>
102 #include <WebCore/DragSession.h>
103 #include <WebCore/ElementIterator.h>
104 #include <WebCore/EventHandler.h>
105 #include <WebCore/FocusController.h>
106 #include <WebCore/FormState.h>
107 #include <WebCore/FrameLoadRequest.h>
108 #include <WebCore/FrameLoaderTypes.h>
109 #include <WebCore/FrameView.h>
110 #include <WebCore/HTMLFormElement.h>
111 #include <WebCore/HTMLInputElement.h>
112 #include <WebCore/HTMLPlugInElement.h>
113 #include <WebCore/HTMLPlugInImageElement.h>
114 #include <WebCore/HistoryController.h>
115 #include <WebCore/HistoryItem.h>
116 #include <WebCore/HitTestResult.h>
117 #include <WebCore/JSDOMWindow.h>
118 #include <WebCore/KeyboardEvent.h>
119 #include <WebCore/MIMETypeRegistry.h>
120 #include <WebCore/MainFrame.h>
121 #include <WebCore/MouseEvent.h>
122 #include <WebCore/Page.h>
123 #include <WebCore/PageThrottler.h>
124 #include <WebCore/PlatformKeyboardEvent.h>
125 #include <WebCore/PluginDocument.h>
126 #include <WebCore/PrintContext.h>
127 #include <WebCore/Range.h>
128 #include <WebCore/RenderLayer.h>
129 #include <WebCore/RenderTreeAsText.h>
130 #include <WebCore/RenderView.h>
131 #include <WebCore/ResourceBuffer.h>
132 #include <WebCore/ResourceRequest.h>
133 #include <WebCore/ResourceResponse.h>
134 #include <WebCore/RuntimeEnabledFeatures.h>
135 #include <WebCore/SchemeRegistry.h>
136 #include <WebCore/ScriptController.h>
137 #include <WebCore/SerializedScriptValue.h>
138 #include <WebCore/SessionID.h>
139 #include <WebCore/Settings.h>
140 #include <WebCore/ShadowRoot.h>
141 #include <WebCore/SharedBuffer.h>
142 #include <WebCore/SubframeLoader.h>
143 #include <WebCore/SubstituteData.h>
144 #include <WebCore/TextIterator.h>
145 #include <WebCore/UserInputBridge.h>
146 #include <WebCore/VisiblePosition.h>
147 #include <WebCore/VisibleUnits.h>
148 #include <WebCore/markup.h>
149 #include <bindings/ScriptValue.h>
150 #include <runtime/JSCInlines.h>
151 #include <runtime/JSCJSValue.h>
152 #include <runtime/JSLock.h>
153 #include <wtf/RunLoop.h>
156 #include <WebCore/MHTMLArchive.h>
159 #if ENABLE(BATTERY_STATUS)
160 #include "WebBatteryClient.h"
163 #if ENABLE(NETWORK_INFO)
164 #include "WebNetworkInfoClient.h"
167 #if ENABLE(VIBRATION)
168 #include "WebVibrationClient.h"
171 #if ENABLE(PROXIMITY_EVENTS)
172 #include "WebDeviceProximityClient.h"
176 #include "PDFPlugin.h"
177 #include "RemoteLayerTreeTransaction.h"
178 #include <WebCore/LegacyWebArchive.h>
183 #include "DataObjectGtk.h"
184 #include "WebPrintOperationGtk.h"
188 #include "WebVideoFullscreenManager.h"
192 #include <wtf/RefCountedLeakCounter.h>
195 #if USE(COORDINATED_GRAPHICS)
196 #include "CoordinatedLayerTreeHostMessages.h"
200 using namespace WebCore;
204 class SendStopResponsivenessTimer {
206 SendStopResponsivenessTimer(WebPage* page)
211 ~SendStopResponsivenessTimer()
213 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
220 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
222 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
224 RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
226 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
227 WebProcess::shared().injectedBundle()->didCreatePage(page.get());
229 return page.release();
232 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
234 , m_viewSize(parameters.viewSize)
235 , m_hasSeenPlugin(false)
236 , m_useFixedLayout(false)
237 , m_drawsBackground(true)
238 , m_drawsTransparentBackground(false)
241 , m_tabToLinks(false)
242 , m_asynchronousPluginInitializationEnabled(false)
243 , m_asynchronousPluginInitializationEnabledForAllPlugins(false)
244 , m_artificialPluginInitializationDelayEnabled(false)
245 , m_scrollingPerformanceLoggingEnabled(false)
246 , m_mainFrameIsScrollable(true)
247 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
248 , m_readyToFindPrimarySnapshottedPlugin(false)
249 , m_didFindPrimarySnapshottedPlugin(false)
250 , m_numberOfPrimarySnapshotDetectionAttempts(0)
251 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
253 , m_layerHostingMode(parameters.layerHostingMode)
255 , m_pdfPluginEnabled(false)
256 , m_hasCachedWindowFrame(false)
257 , m_viewGestureGeometryCollector(*this)
258 #elif PLATFORM(GTK) && HAVE(ACCESSIBILITY)
259 , m_accessibilityObject(0)
261 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
262 , m_sendDidUpdateViewStateTimer(RunLoop::main(), this, &WebPage::didUpdateViewStateTimerFired)
263 , m_findController(this)
264 #if ENABLE(INPUT_TYPE_COLOR)
265 , m_activeColorChooser(0)
267 #if ENABLE(GEOLOCATION)
268 , m_geolocationPermissionRequestManager(this)
270 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
271 , m_canRunModal(parameters.canRunModal)
272 , m_isRunningModal(false)
273 , m_cachedMainFrameIsPinnedToLeftSide(false)
274 , m_cachedMainFrameIsPinnedToRightSide(false)
275 , m_cachedMainFrameIsPinnedToTopSide(false)
276 , m_cachedMainFrameIsPinnedToBottomSide(false)
277 , m_canShortCircuitHorizontalWheelEvents(false)
278 , m_numWheelEventHandlers(0)
279 , m_cachedPageCount(0)
280 , m_autoSizingShouldExpandToViewHeight(false)
281 #if ENABLE(CONTEXT_MENUS)
282 , m_isShowingContextMenu(false)
285 , m_shouldReturnWordAtSelection(false)
286 , m_lastVisibleContentRectUpdateID(0)
287 , m_scaleWasSetByUIProcess(false)
288 , m_userHasChangedPageScaleFactor(false)
289 , m_viewportScreenSize(parameters.viewportScreenSize)
291 , m_inspectorClient(0)
292 , m_backgroundColor(Color::white)
293 , m_maximumRenderingSuppressionToken(0)
294 , m_scrollPinningBehavior(DoNotPin)
295 , m_useAsyncScrolling(false)
296 , m_viewState(parameters.viewState)
297 , m_processSuppressionDisabledByWebPreference("Process suppression is disabled.")
298 , m_pendingNavigationID(0)
299 , m_pageScaleWithoutThumbnailScale(1)
300 , m_thumbnailScale(1)
302 , m_systemWebGLPolicy(WebGLAllowCreation)
306 // FIXME: This is a non-ideal location for this Setting and
307 // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
308 Settings::setDefaultMinDOMTimerInterval(0.004);
310 Page::PageClients pageClients;
311 pageClients.chromeClient = new WebChromeClient(this);
312 #if ENABLE(CONTEXT_MENUS)
313 pageClients.contextMenuClient = new WebContextMenuClient(this);
315 pageClients.editorClient = new WebEditorClient(this);
316 #if ENABLE(DRAG_SUPPORT)
317 pageClients.dragClient = new WebDragClient(this);
319 pageClients.backForwardClient = WebBackForwardListProxy::create(this);
320 #if ENABLE(INSPECTOR)
321 m_inspectorClient = new WebInspectorClient(this);
322 pageClients.inspectorClient = m_inspectorClient;
324 #if USE(AUTOCORRECTION_PANEL)
325 pageClients.alternativeTextClient = new WebAlternativeTextClient(this);
327 pageClients.plugInClient = new WebPlugInClient(this);
328 pageClients.loaderClientForMainFrame = new WebFrameLoaderClient;
329 pageClients.progressTrackerClient = new WebProgressTrackerClient(*this);
331 pageClients.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
333 m_page = adoptPtr(new Page(pageClients));
335 m_drawingArea = DrawingArea::create(this, parameters);
336 m_drawingArea->setPaintingEnabled(false);
338 #if ENABLE(ASYNC_SCROLLING)
339 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
340 if (!m_drawingArea->supportsAsyncScrolling())
341 m_useAsyncScrolling = false;
342 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
345 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
347 #if ENABLE(BATTERY_STATUS)
348 WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
350 #if ENABLE(GEOLOCATION)
351 WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
353 #if ENABLE(NETWORK_INFO)
354 WebCore::provideNetworkInfoTo(m_page.get(), new WebNetworkInfoClient(this));
356 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
357 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
359 #if ENABLE(VIBRATION)
360 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
362 #if ENABLE(PROXIMITY_EVENTS)
363 WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this));
366 #if ENABLE(REMOTE_INSPECTOR)
367 m_page->setRemoteInspectionAllowed(true);
370 m_page->setCanStartMedia(false);
371 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
373 m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
374 m_page->setGroupName(m_pageGroup->identifier());
375 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
377 updatePreferences(parameters.store);
378 platformInitialize();
380 setUseFixedLayout(parameters.useFixedLayout);
382 setDrawsBackground(parameters.drawsBackground);
383 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
385 setUnderlayColor(parameters.underlayColor);
387 setPaginationMode(parameters.paginationMode);
388 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
389 setPageLength(parameters.pageLength);
390 setGapBetweenPages(parameters.gapBetweenPages);
392 setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
394 // If the page is created off-screen, its visibilityState should be prerender.
395 m_page->setViewState(m_viewState);
397 m_page->setIsPrerender();
399 updateIsInWindow(true);
401 setMinimumLayoutSize(parameters.minimumLayoutSize);
402 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
404 setScrollPinningBehavior(parameters.scrollPinningBehavior);
405 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
407 setTopContentInset(parameters.topContentInset);
409 m_userAgent = parameters.userAgent;
411 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
413 if (!parameters.sessionState.isEmpty())
414 restoreSession(parameters.sessionState);
416 m_drawingArea->setPaintingEnabled(true);
418 setMediaVolume(parameters.mediaVolume);
420 // We use the DidFirstLayout milestone to determine when to unfreeze the layer tree.
421 m_page->addLayoutMilestones(DidFirstLayout);
423 WebProcess::shared().addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
425 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
426 WebProcess::shared().addMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID, *this);
427 #if USE(COORDINATED_GRAPHICS)
428 WebProcess::shared().addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this);
430 #if ENABLE(INSPECTOR)
431 WebProcess::shared().addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
433 #if ENABLE(FULLSCREEN_API)
434 WebProcess::shared().addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
438 webPageCounter.increment();
441 #if ENABLE(ASYNC_SCROLLING)
442 if (m_useAsyncScrolling)
443 WebProcess::shared().eventDispatcher().addScrollingTreeForPage(this);
447 void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters)
449 if (m_viewState != parameters.viewState)
450 setViewState(parameters.viewState);
451 if (m_layerHostingMode != parameters.layerHostingMode)
452 setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode));
457 if (m_backForwardList)
458 m_backForwardList->detach();
462 #if ENABLE(ASYNC_SCROLLING)
463 if (m_useAsyncScrolling)
464 WebProcess::shared().eventDispatcher().removeScrollingTreeForPage(this);
467 m_sandboxExtensionTracker.invalidate();
469 for (auto* pluginView : m_pluginViews)
470 pluginView->webPageDestroyed();
474 m_headerBanner->detachFromPage();
476 m_footerBanner->detachFromPage();
477 #endif // !PLATFORM(IOS)
479 WebProcess::shared().removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
481 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
482 WebProcess::shared().removeMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID);
483 #if USE(COORDINATED_GRAPHICS)
484 WebProcess::shared().removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID);
486 #if ENABLE(INSPECTOR)
487 WebProcess::shared().removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
489 #if ENABLE(FULLSCREEN_API)
490 WebProcess::shared().removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
494 webPageCounter.decrement();
498 void WebPage::dummy(bool&)
502 IPC::Connection* WebPage::messageSenderConnection()
504 return WebProcess::shared().parentProcessConnection();
507 uint64_t WebPage::messageSenderDestinationID()
512 #if ENABLE(CONTEXT_MENUS)
513 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClientBase* client)
515 m_contextMenuClient.initialize(client);
519 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* client)
521 m_editorClient.initialize(client);
524 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClientBase* client)
526 m_formClient.initialize(client);
529 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client)
531 m_loaderClient.initialize(client);
533 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
534 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
535 // for backwards compatibility.
536 LayoutMilestones milestones = 0;
538 if (m_loaderClient.client().didFirstLayoutForFrame)
539 milestones |= WebCore::DidFirstLayout;
540 if (m_loaderClient.client().didFirstVisuallyNonEmptyLayoutForFrame)
541 milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
545 listenForLayoutMilestones(milestones);
548 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
550 m_policyClient.initialize(client);
553 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase* client)
555 m_resourceLoadClient.initialize(client);
558 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClientBase* client)
560 m_uiClient.initialize(client);
563 #if ENABLE(FULLSCREEN_API)
564 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
566 m_fullScreenClient.initialize(client);
570 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase* client)
572 m_logDiagnosticMessageClient.initialize(client);
575 #if ENABLE(NETSCAPE_PLUGIN_API)
576 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
578 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
579 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
580 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
582 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin);
584 uint64_t pluginProcessToken;
585 uint32_t pluginLoadPolicy;
586 String unavailabilityDescription;
587 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)))
590 bool isBlockedPlugin = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy) == PluginModuleBlocked;
592 if (isBlockedPlugin || !pluginProcessToken) {
593 #if ENABLE(PDFKIT_PLUGIN)
594 String path = parameters.url.path();
595 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
596 RefPtr<PDFPlugin> pdfPlugin = PDFPlugin::create(frame);
597 return pdfPlugin.release();
604 if (isBlockedPlugin) {
605 bool replacementObscured = false;
606 if (pluginElement->renderer()->isEmbeddedObject()) {
607 RenderEmbeddedObject* renderObject = toRenderEmbeddedObject(pluginElement->renderer());
608 renderObject->setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
609 replacementObscured = renderObject->isReplacementObscured();
610 renderObject->setUnavailablePluginIndicatorIsHidden(replacementObscured);
613 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
617 if (!pluginProcessToken)
620 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
621 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
624 #endif // ENABLE(NETSCAPE_PLUGIN_API)
626 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
627 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
629 return WebGLAllowCreation;
632 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
634 return WebGLAllowCreation;
638 EditorState WebPage::editorState() const
640 Frame& frame = m_page->focusController().focusedOrMainFrame();
644 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
645 if (!pluginView->getSelectionString().isNull()) {
646 result.selectionIsNone = false;
647 result.selectionIsRange = true;
648 result.isInPlugin = true;
653 const VisibleSelection& selection = frame.selection().selection();
655 result.selectionIsNone = selection.isNone();
656 result.selectionIsRange = selection.isRange();
657 result.isContentEditable = selection.isContentEditable();
658 result.isContentRichlyEditable = selection.isContentRichlyEditable();
659 result.isInPasswordField = selection.isInPasswordField();
660 result.hasComposition = frame.editor().hasComposition();
661 result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange();
664 if (frame.editor().hasComposition()) {
665 RefPtr<Range> compositionRange = frame.editor().compositionRange();
666 Vector<WebCore::SelectionRect> compositionRects;
667 compositionRange->collectSelectionRects(compositionRects);
668 if (compositionRects.size())
669 result.firstMarkedRect = compositionRects[0].rect();
670 if (compositionRects.size() > 1)
671 result.lastMarkedRect = compositionRects.last().rect();
673 result.lastMarkedRect = result.firstMarkedRect;
674 result.markedText = plainText(compositionRange.get());
676 FrameView* view = frame.view();
677 if (selection.isCaret()) {
678 result.caretRectAtStart = view->contentsToRootView(frame.selection().absoluteCaretBounds());
679 result.caretRectAtEnd = result.caretRectAtStart;
680 if (m_shouldReturnWordAtSelection)
681 result.wordAtSelection = plainText(wordRangeFromPosition(selection.start()).get());
682 } else if (selection.isRange()) {
683 result.caretRectAtStart = view->contentsToRootView(VisiblePosition(selection.start()).absoluteCaretBounds());
684 result.caretRectAtEnd = view->contentsToRootView(VisiblePosition(selection.end()).absoluteCaretBounds());
685 RefPtr<Range> selectedRange = selection.toNormalizedRange();
686 selectedRange->collectSelectionRects(result.selectionRects);
687 convertSelectionRectsToRootView(view, result.selectionRects);
688 result.selectedTextLength = plainText(selectedRange.get(), TextIteratorDefaultBehavior, true).length();
693 result.cursorRect = frame.selection().absoluteCaretBounds();
699 String WebPage::renderTreeExternalRepresentation() const
701 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
704 String WebPage::renderTreeExternalRepresentationForPrinting() const
706 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
709 uint64_t WebPage::renderTreeSize() const
713 return m_page->renderTreeSize();
716 void WebPage::setTracksRepaints(bool trackRepaints)
718 if (FrameView* view = mainFrameView())
719 view->setTracksRepaints(trackRepaints);
722 bool WebPage::isTrackingRepaints() const
724 if (FrameView* view = mainFrameView())
725 return view->isTrackingRepaints();
730 void WebPage::resetTrackedRepaints()
732 if (FrameView* view = mainFrameView())
733 view->resetTrackedRepaints();
736 PassRefPtr<API::Array> WebPage::trackedRepaintRects()
738 FrameView* view = mainFrameView();
740 return API::Array::create();
742 Vector<RefPtr<API::Object>> repaintRects;
743 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
745 for (const auto& repaintRect : view->trackedRepaintRects())
746 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
748 return API::Array::create(std::move(repaintRects));
751 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
753 if (!frame.document()->isPluginDocument())
756 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
758 if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
761 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
765 PluginView* WebPage::pluginViewForFrame(Frame* frame)
767 if (!frame->document()->isPluginDocument())
770 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
771 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
775 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
777 Frame& frame = m_page->focusController().focusedOrMainFrame();
779 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
780 pluginView->handleEditingCommand(commandName, argument);
784 frame.editor().command(commandName).execute(argument);
787 bool WebPage::isEditingCommandEnabled(const String& commandName)
789 Frame& frame = m_page->focusController().focusedOrMainFrame();
791 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
792 return pluginView->isEditingCommandEnabled(commandName);
794 Editor::Command command = frame.editor().command(commandName);
795 return command.isSupported() && command.isEnabled();
798 void WebPage::clearMainFrameName()
800 if (Frame* frame = mainFrame())
801 frame->tree().clearName();
804 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
806 m_drawingArea->setRootCompositingLayer(layer);
809 void WebPage::exitAcceleratedCompositingMode()
811 m_drawingArea->setRootCompositingLayer(0);
814 void WebPage::close()
821 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
822 if (!mainWebFrame()->url().isEmpty())
823 reportUsedFeatures();
825 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
826 WebProcess::shared().injectedBundle()->willDestroyPage(this);
828 #if ENABLE(INSPECTOR)
831 #if ENABLE(FULLSCREEN_API)
832 m_fullScreenManager = 0;
835 if (m_activePopupMenu) {
836 m_activePopupMenu->disconnectFromPage();
837 m_activePopupMenu = 0;
840 if (m_activeOpenPanelResultListener) {
841 m_activeOpenPanelResultListener->disconnectFromPage();
842 m_activeOpenPanelResultListener = 0;
845 #if ENABLE(INPUT_TYPE_COLOR)
846 if (m_activeColorChooser) {
847 m_activeColorChooser->disconnectFromPage();
848 m_activeColorChooser = 0;
853 if (m_printOperation) {
854 m_printOperation->disconnectFromPage();
855 m_printOperation = nullptr;
859 m_sandboxExtensionTracker.invalidate();
861 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
862 m_determinePrimarySnapshottedPlugInTimer.stop();
865 #if ENABLE(CONTEXT_MENUS)
866 m_contextMenuClient.initialize(0);
868 m_editorClient.initialize(0);
869 m_formClient.initialize(0);
870 m_loaderClient.initialize(0);
871 m_policyClient.initialize(0);
872 m_resourceLoadClient.initialize(0);
873 m_uiClient.initialize(0);
874 #if ENABLE(FULLSCREEN_API)
875 m_fullScreenClient.initialize(0);
877 m_logDiagnosticMessageClient.initialize(0);
879 m_printContext = nullptr;
880 m_mainFrame->coreFrame()->loader().detachFromParent();
882 m_drawingArea = nullptr;
884 bool isRunningModal = m_isRunningModal;
885 m_isRunningModal = false;
887 // The WebPage can be destroyed by this call.
888 WebProcess::shared().removeWebPage(m_pageID);
891 RunLoop::main().stop();
894 void WebPage::tryClose()
896 SendStopResponsivenessTimer stopper(this);
898 if (!corePage()->userInputBridge().tryClosePage()) {
899 send(Messages::WebPageProxy::StopResponsivenessTimer());
903 send(Messages::WebPageProxy::ClosePage(true));
906 void WebPage::sendClose()
908 send(Messages::WebPageProxy::ClosePage(false));
911 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
913 WebFrame* frame = WebProcess::shared().webFrame(frameID);
917 frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url))));
920 void WebPage::loadRequest(uint64_t navigationID, const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, IPC::MessageDecoder& decoder)
922 SendStopResponsivenessTimer stopper(this);
924 RefPtr<API::Object> userData;
925 InjectedBundleUserMessageDecoder userMessageDecoder(userData);
926 if (!decoder.decode(userMessageDecoder))
929 ASSERT(!m_pendingNavigationID);
930 m_pendingNavigationID = navigationID;
932 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
934 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
935 // to all the client to set up any needed state.
936 m_loaderClient.willLoadURLRequest(this, request, userData.get());
938 // Initate the load in WebCore.
939 corePage()->userInputBridge().loadRequest(FrameLoadRequest(m_mainFrame->coreFrame(), request));
941 ASSERT(!m_pendingNavigationID);
944 void WebPage::loadDataImpl(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder)
946 SendStopResponsivenessTimer stopper(this);
948 RefPtr<API::Object> userData;
949 InjectedBundleUserMessageDecoder userMessageDecoder(userData);
950 if (!decoder.decode(userMessageDecoder))
953 ResourceRequest request(baseURL);
954 SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
956 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
957 // to all the client to set up any needed state.
958 m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), userData.get());
960 // Initate the load in WebCore.
961 m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, substituteData));
964 void WebPage::loadString(const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder)
966 if (!htmlString.isNull() && htmlString.is8Bit()) {
967 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
968 loadDataImpl(sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, decoder);
970 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
971 loadDataImpl(sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, decoder);
975 void WebPage::loadData(const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, IPC::MessageDecoder& decoder)
977 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
978 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
979 loadDataImpl(sharedBuffer, MIMEType, encodingName, baseURL, URL(), decoder);
982 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString, IPC::MessageDecoder& decoder)
984 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
985 loadString(htmlString, ASCIILiteral("text/html"), baseURL, URL(), decoder);
988 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, IPC::MessageDecoder& decoder)
990 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
991 URL unreachableURL = unreachableURLString.isEmpty() ? URL() : URL(URL(), unreachableURLString);
992 loadString(htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, decoder);
995 void WebPage::loadPlainTextString(const String& string, IPC::MessageDecoder& decoder)
997 loadString(string, ASCIILiteral("text/plain"), blankURL(), URL(), decoder);
1000 void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, IPC::MessageDecoder& decoder)
1002 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
1003 loadDataImpl(sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), decoder);
1006 void WebPage::stopLoadingFrame(uint64_t frameID)
1008 WebFrame* frame = WebProcess::shared().webFrame(frameID);
1012 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1015 void WebPage::stopLoading()
1017 SendStopResponsivenessTimer stopper(this);
1019 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1022 void WebPage::setDefersLoading(bool defersLoading)
1024 m_page->setDefersLoading(defersLoading);
1027 void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
1029 SendStopResponsivenessTimer stopper(this);
1031 ASSERT(!m_pendingNavigationID);
1032 m_pendingNavigationID = navigationID;
1034 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1035 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin);
1038 void WebPage::goForward(uint64_t backForwardItemID)
1040 SendStopResponsivenessTimer stopper(this);
1042 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1047 m_page->goToItem(item, FrameLoadTypeForward);
1050 void WebPage::goBack(uint64_t backForwardItemID)
1052 SendStopResponsivenessTimer stopper(this);
1054 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1059 m_page->goToItem(item, FrameLoadTypeBack);
1062 void WebPage::goToBackForwardItem(uint64_t backForwardItemID)
1064 SendStopResponsivenessTimer stopper(this);
1066 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1071 m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
1074 void WebPage::tryRestoreScrollPosition()
1076 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1079 void WebPage::layoutIfNeeded()
1081 if (m_mainFrame->coreFrame()->view())
1082 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1085 WebPage* WebPage::fromCorePage(Page* page)
1087 return static_cast<WebChromeClient&>(page->chrome().client()).page();
1090 void WebPage::setSize(const WebCore::IntSize& viewSize)
1092 if (m_viewSize == viewSize)
1095 FrameView* view = m_page->mainFrame().view();
1096 view->resize(viewSize);
1097 m_drawingArea->setNeedsDisplay();
1099 m_viewSize = viewSize;
1101 #if USE(TILED_BACKING_STORE)
1102 if (view->useFixedLayout())
1103 sendViewportAttributesChanged();
1107 #if USE(TILED_BACKING_STORE)
1108 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1110 ASSERT(m_useFixedLayout);
1112 m_page->mainFrame().view()->setFixedVisibleContentRect(rect);
1115 void WebPage::sendViewportAttributesChanged()
1117 ASSERT(m_useFixedLayout);
1119 // Viewport properties have no impact on zero sized fixed viewports.
1120 if (m_viewSize.isEmpty())
1123 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1124 Settings& settings = m_page->settings();
1126 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1128 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1129 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1130 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1132 ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1134 FrameView* view = m_page->mainFrame().view();
1136 // If no layout was done yet set contentFixedOrigin to (0,0).
1137 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1139 // Put the width and height to the viewport width and height. In css units however.
1140 // Use FloatSize to avoid truncated values during scale.
1141 FloatSize contentFixedSize = m_viewSize;
1143 #if ENABLE(CSS_DEVICE_ADAPTATION)
1144 // CSS viewport descriptors might be applied to already affected viewport size
1145 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1146 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1149 contentFixedSize.scale(1 / attr.initialScale);
1150 setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1152 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1154 // This also takes care of the relayout.
1155 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1157 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1161 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1163 FrameView* frameView = m_page->mainFrame().view();
1165 IntPoint scrollPosition = frameView->scrollPosition();
1166 IntPoint maximumScrollPosition = frameView->maximumScrollPosition();
1168 // If the current scroll position in a direction is the max scroll position
1169 // we don't want to scroll at all.
1170 IntSize newScrollOffset;
1171 if (scrollPosition.x() < maximumScrollPosition.x())
1172 newScrollOffset.setWidth(scrollOffset.width());
1173 if (scrollPosition.y() < maximumScrollPosition.y())
1174 newScrollOffset.setHeight(scrollOffset.height());
1176 if (newScrollOffset.isZero())
1179 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1182 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1184 GraphicsContextStateSaver stateSaver(graphicsContext);
1185 graphicsContext.clip(rect);
1187 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1190 void WebPage::drawPageOverlay(PageOverlay* pageOverlay, GraphicsContext& graphicsContext, const IntRect& rect)
1192 ASSERT(pageOverlay);
1194 GraphicsContextStateSaver stateSaver(graphicsContext);
1195 graphicsContext.clip(rect);
1196 pageOverlay->drawRect(graphicsContext, rect);
1199 double WebPage::textZoomFactor() const
1201 Frame* frame = m_mainFrame->coreFrame();
1204 return frame->textZoomFactor();
1207 void WebPage::setTextZoomFactor(double zoomFactor)
1209 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1210 if (pluginView && pluginView->handlesPageScaleFactor())
1213 Frame* frame = m_mainFrame->coreFrame();
1216 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1219 double WebPage::pageZoomFactor() const
1221 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1222 if (pluginView && pluginView->handlesPageScaleFactor())
1223 return pluginView->pageScaleFactor();
1225 Frame* frame = m_mainFrame->coreFrame();
1228 return frame->pageZoomFactor();
1231 void WebPage::setPageZoomFactor(double zoomFactor)
1233 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1234 if (pluginView && pluginView->handlesPageScaleFactor()) {
1235 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1239 Frame* frame = m_mainFrame->coreFrame();
1242 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1245 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1247 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1248 if (pluginView && pluginView->handlesPageScaleFactor()) {
1249 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1253 Frame* frame = m_mainFrame->coreFrame();
1256 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1259 void WebPage::windowScreenDidChange(uint64_t displayID)
1261 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1264 void WebPage::scalePage(double scale, const IntPoint& origin)
1266 if (scale == pageScaleFactor())
1270 m_scaleWasSetByUIProcess = false;
1272 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1273 if (pluginView && pluginView->handlesPageScaleFactor()) {
1274 pluginView->setPageScaleFactor(scale, origin);
1278 m_page->setPageScaleFactor(scale, origin);
1280 for (auto* pluginView : m_pluginViews)
1281 pluginView->pageScaleFactorDidChange();
1283 if (m_drawingArea->layerTreeHost())
1284 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1286 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1289 double WebPage::pageScaleFactor() const
1291 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1292 if (pluginView && pluginView->handlesPageScaleFactor())
1293 return pluginView->pageScaleFactor();
1295 return m_page->pageScaleFactor();
1298 void WebPage::setDeviceScaleFactor(float scaleFactor)
1300 if (scaleFactor == m_page->deviceScaleFactor())
1303 m_page->setDeviceScaleFactor(scaleFactor);
1305 // Tell all our plug-in views that the device scale factor changed.
1307 for (auto* pluginView : m_pluginViews)
1308 pluginView->setDeviceScaleFactor(scaleFactor);
1310 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1313 if (m_findController.isShowingOverlay()) {
1314 // We must have updated layout to get the selection rects right.
1316 m_findController.deviceScaleFactorDidChange();
1319 if (m_drawingArea->layerTreeHost())
1320 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1323 float WebPage::deviceScaleFactor() const
1325 return m_page->deviceScaleFactor();
1328 void WebPage::setUseFixedLayout(bool fixed)
1330 // Do not overwrite current settings if initially setting it to false.
1331 if (m_useFixedLayout == fixed)
1333 m_useFixedLayout = fixed;
1336 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1338 #if USE(COORDINATED_GRAPHICS)
1339 m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1340 m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1341 m_page->settings().setDelegatesPageScaling(fixed);
1342 m_page->settings().setScrollingCoordinatorEnabled(fixed);
1345 #if USE(TILED_BACKING_STORE) && ENABLE(SMOOTH_SCROLLING)
1346 // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1347 // Ensure we don't do animated scrolling in the WebProcess in that case.
1348 m_page->settings().setScrollAnimatorEnabled(!fixed);
1351 FrameView* view = mainFrameView();
1355 #if USE(TILED_BACKING_STORE)
1356 view->setDelegatesScrolling(fixed);
1357 view->setPaintsEntireContents(fixed);
1359 view->setUseFixedLayout(fixed);
1361 setFixedLayoutSize(IntSize());
1364 void WebPage::setFixedLayoutSize(const IntSize& size)
1366 FrameView* view = mainFrameView();
1367 if (!view || view->fixedLayoutSize() == size)
1370 view->setFixedLayoutSize(size);
1371 // Do not force it until the first layout, this would then become our first layout prematurely.
1372 if (view->didFirstLayout())
1373 view->forceLayout();
1376 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1380 m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1383 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1385 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1388 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1390 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1391 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1394 void WebPage::setPaginationMode(uint32_t mode)
1396 Pagination pagination = m_page->pagination();
1397 pagination.mode = static_cast<Pagination::Mode>(mode);
1398 m_page->setPagination(pagination);
1401 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1403 Pagination pagination = m_page->pagination();
1404 pagination.behavesLikeColumns = behavesLikeColumns;
1405 m_page->setPagination(pagination);
1408 void WebPage::setPageLength(double pageLength)
1410 Pagination pagination = m_page->pagination();
1411 pagination.pageLength = pageLength;
1412 m_page->setPagination(pagination);
1415 void WebPage::setGapBetweenPages(double gap)
1417 Pagination pagination = m_page->pagination();
1418 pagination.gap = gap;
1419 m_page->setPagination(pagination);
1422 void WebPage::postInjectedBundleMessage(const String& messageName, IPC::MessageDecoder& decoder)
1424 InjectedBundle* injectedBundle = WebProcess::shared().injectedBundle();
1425 if (!injectedBundle)
1428 RefPtr<API::Object> messageBody;
1429 InjectedBundleUserMessageDecoder messageBodyDecoder(messageBody);
1430 if (!decoder.decode(messageBodyDecoder))
1433 injectedBundle->didReceiveMessageToPage(this, messageName, messageBody.get());
1436 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay, bool shouldFadeIn)
1438 RefPtr<PageOverlay> overlay = pageOverlay;
1440 if (m_pageOverlays.contains(overlay.get()))
1443 m_pageOverlays.append(overlay);
1444 overlay->setPage(this);
1447 overlay->startFadeInAnimation();
1449 m_drawingArea->didInstallPageOverlay(overlay.get());
1452 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool shouldFadeOut)
1454 size_t existingOverlayIndex = m_pageOverlays.find(pageOverlay);
1455 if (existingOverlayIndex == notFound)
1458 if (shouldFadeOut) {
1459 pageOverlay->startFadeOutAnimation();
1463 pageOverlay->setPage(0);
1464 m_pageOverlays.remove(existingOverlayIndex);
1466 m_drawingArea->didUninstallPageOverlay(pageOverlay);
1470 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1473 m_headerBanner->detachFromPage();
1475 m_headerBanner = pageBanner;
1478 m_headerBanner->addToPage(PageBanner::Header, this);
1481 PageBanner* WebPage::headerPageBanner()
1483 return m_headerBanner.get();
1486 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1489 m_footerBanner->detachFromPage();
1491 m_footerBanner = pageBanner;
1494 m_footerBanner->addToPage(PageBanner::Footer, this);
1497 PageBanner* WebPage::footerPageBanner()
1499 return m_footerBanner.get();
1502 void WebPage::hidePageBanners()
1505 m_headerBanner->hide();
1507 m_footerBanner->hide();
1510 void WebPage::showPageBanners()
1513 m_headerBanner->showIfHidden();
1515 m_footerBanner->showIfHidden();
1517 #endif // !PLATFORM(IOS)
1519 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1521 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1522 snapshotOptions |= SnapshotOptionsShareable;
1524 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1526 ShareableBitmap::Handle handle;
1528 image->bitmap()->createHandle(handle, SharedMemory::ReadOnly);
1530 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1533 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double scaleFactor, SnapshotOptions options)
1535 IntRect snapshotRect = rect;
1536 if (options & SnapshotOptionsRespectDrawingAreaTransform)
1537 snapshotRect = m_drawingArea->rootLayerTransform().inverse().mapRect(snapshotRect);
1539 IntSize bitmapSize = snapshotRect.size();
1540 bitmapSize.scale(scaleFactor * corePage()->deviceScaleFactor());
1542 return snapshotAtSize(rect, bitmapSize, options);
1545 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1547 Frame* coreFrame = m_mainFrame->coreFrame();
1551 FrameView* frameView = coreFrame->view();
1555 IntRect snapshotRect = rect;
1556 if (options & SnapshotOptionsRespectDrawingAreaTransform)
1557 snapshotRect = m_drawingArea->rootLayerTransform().inverse().mapRect(snapshotRect);
1559 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1560 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1561 float scaleFactor = std::min(horizontalScaleFactor, verticalScaleFactor);
1563 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1564 if (!snapshot->bitmap())
1567 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1569 graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), frameView->baseBackgroundColor(), ColorSpaceDeviceRGB);
1571 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1572 graphicsContext->applyDeviceScaleFactor(corePage()->deviceScaleFactor());
1574 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1575 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1577 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1578 if (options & SnapshotOptionsExcludeSelectionHighlighting)
1579 shouldPaintSelection = FrameView::ExcludeSelection;
1581 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1582 if (options & SnapshotOptionsInViewCoordinates)
1583 coordinateSpace = FrameView::ViewCoordinates;
1585 frameView->paintContentsForSnapshot(graphicsContext.get(), snapshotRect, shouldPaintSelection, coordinateSpace);
1587 if (options & SnapshotOptionsPaintSelectionRectangle) {
1588 FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1589 graphicsContext->setStrokeColor(Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
1590 graphicsContext->strokeRect(selectionRectangle, 1);
1593 return snapshot.release();
1596 void WebPage::pageDidScroll()
1598 m_uiClient.pageDidScroll(this);
1600 send(Messages::WebPageProxy::PageDidScroll());
1603 #if USE(TILED_BACKING_STORE)
1604 void WebPage::pageDidRequestScroll(const IntPoint& point)
1606 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1610 #if ENABLE(CONTEXT_MENUS)
1611 WebContextMenu* WebPage::contextMenu()
1614 m_contextMenu = WebContextMenu::create(this);
1615 return m_contextMenu.get();
1618 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1620 corePage()->contextMenuController().clearContextMenu();
1622 // Simulate a mouse click to generate the correct menu.
1623 PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime());
1624 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
1628 return contextMenu();
1634 static const WebEvent* g_currentEvent = 0;
1636 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1637 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1638 // platform events passed to the event handler code.
1639 const WebEvent* WebPage::currentEvent()
1641 return g_currentEvent;
1644 class CurrentEvent {
1646 explicit CurrentEvent(const WebEvent& event)
1647 : m_previousCurrentEvent(g_currentEvent)
1649 g_currentEvent = &event;
1654 g_currentEvent = m_previousCurrentEvent;
1658 const WebEvent* m_previousCurrentEvent;
1661 #if ENABLE(CONTEXT_MENUS)
1662 static bool isContextClick(const PlatformMouseEvent& event)
1664 if (event.button() == WebCore::RightButton)
1668 // FIXME: this really should be about OSX-style UI, not about the Mac port
1669 if (event.button() == WebCore::LeftButton && event.ctrlKey())
1676 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1678 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
1679 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
1681 Frame* frame = &page->corePage()->mainFrame();
1682 if (result.innerNonSharedNode())
1683 frame = result.innerNonSharedNode()->document().frame();
1685 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
1687 page->contextMenu()->show();
1693 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1695 Frame& frame = page->corePage()->mainFrame();
1699 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1701 switch (platformMouseEvent.type()) {
1702 case PlatformEvent::MousePressed: {
1703 #if ENABLE(CONTEXT_MENUS)
1704 if (isContextClick(platformMouseEvent))
1705 page->corePage()->contextMenuController().clearContextMenu();
1708 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
1709 #if ENABLE(CONTEXT_MENUS)
1710 if (isContextClick(platformMouseEvent))
1711 handled = handleContextMenuEvent(platformMouseEvent, page);
1715 case PlatformEvent::MouseReleased:
1716 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
1718 case PlatformEvent::MouseMoved:
1719 if (onlyUpdateScrollbars)
1720 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
1721 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
1723 ASSERT_NOT_REACHED();
1728 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1730 m_page->pageThrottler().didReceiveUserInput();
1732 #if ENABLE(CONTEXT_MENUS)
1733 // Don't try to handle any pending mouse events if a context menu is showing.
1734 if (m_isShowingContextMenu) {
1735 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1739 bool handled = false;
1740 if (m_pageOverlays.size()) {
1741 // Let the page overlay handle the event.
1742 PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1743 for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it)
1744 if ((handled = (*it)->mouseEvent(mouseEvent)))
1749 if (!handled && m_headerBanner)
1750 handled = m_headerBanner->mouseEvent(mouseEvent);
1751 if (!handled && m_footerBanner)
1752 handled = m_footerBanner->mouseEvent(mouseEvent);
1753 #endif // !PLATFORM(IOS)
1755 if (!handled && canHandleUserEvents()) {
1756 CurrentEvent currentEvent(mouseEvent);
1758 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1759 // button is currently pressed. It is possible that neither of those things will be true since on
1760 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1761 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1762 // efficient scrollbars-only version of the event.
1763 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1764 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1767 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1770 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1774 if (m_pageOverlays.size()) {
1775 PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1776 for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it)
1777 if ((handled = (*it)->mouseEvent(mouseEvent)))
1781 if (!handled && m_headerBanner)
1782 handled = m_headerBanner->mouseEvent(mouseEvent);
1783 if (!handled && m_footerBanner)
1784 handled = m_footerBanner->mouseEvent(mouseEvent);
1785 #endif // !PLATFORM(IOS)
1788 CurrentEvent currentEvent(mouseEvent);
1790 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1791 // button is currently pressed. It is possible that neither of those things will be true since on
1792 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1793 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1794 // efficient scrollbars-only version of the event.
1795 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1796 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1800 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1802 Frame& frame = page->mainFrame();
1806 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1807 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
1810 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1812 m_page->pageThrottler().didReceiveUserInput();
1814 bool handled = false;
1816 if (canHandleUserEvents()) {
1817 CurrentEvent currentEvent(wheelEvent);
1819 handled = handleWheelEvent(wheelEvent, m_page.get());
1821 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1824 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1826 CurrentEvent currentEvent(wheelEvent);
1828 handled = handleWheelEvent(wheelEvent, m_page.get());
1831 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1833 if (!page->mainFrame().view())
1836 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1837 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
1838 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
1841 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1843 m_page->pageThrottler().didReceiveUserInput();
1845 bool handled = false;
1847 if (canHandleUserEvents()) {
1848 CurrentEvent currentEvent(keyboardEvent);
1850 handled = handleKeyEvent(keyboardEvent, m_page.get());
1851 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1853 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1855 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1858 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
1860 CurrentEvent currentEvent(keyboardEvent);
1862 Frame& frame = m_page->focusController().focusedOrMainFrame();
1863 frame.document()->updateStyleIfNeeded();
1865 handled = handleKeyEvent(keyboardEvent, m_page.get());
1867 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1870 WKTypeRef WebPage::pageOverlayCopyAccessibilityAttributeValue(WKStringRef attribute, WKTypeRef parameter)
1872 if (!m_pageOverlays.size())
1874 PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1875 for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) {
1876 WKTypeRef value = (*it)->copyAccessibilityAttributeValue(attribute, parameter);
1883 WKArrayRef WebPage::pageOverlayCopyAccessibilityAttributesNames(bool parameterizedNames)
1885 if (!m_pageOverlays.size())
1887 PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1888 for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) {
1889 WKArrayRef value = (*it)->copyAccessibilityAttributeNames(parameterizedNames);
1896 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1898 bool isEnabled = false;
1900 Frame& frame = m_page->focusController().focusedOrMainFrame();
1901 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1902 isEnabled = pluginView->isEditingCommandEnabled(commandName);
1904 Editor::Command command = frame.editor().command(commandName);
1905 state = command.state();
1906 isEnabled = command.isSupported() && command.isEnabled();
1909 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1912 void WebPage::executeEditCommand(const String& commandName)
1914 executeEditingCommand(commandName, String());
1917 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1919 const BackForwardListItemVector& list = sessionState.list();
1920 size_t size = list.size();
1921 uint64_t currentItemID = 0;
1922 for (size_t i = 0; i < size; ++i) {
1923 WebBackForwardListItem* webItem = list[i].get();
1924 DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1926 RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1928 LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1932 if (i == sessionState.currentIndex())
1933 currentItemID = webItem->itemID();
1935 WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1937 ASSERT(currentItemID);
1938 return currentItemID;
1941 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState)
1943 if (uint64_t currentItemID = restoreSession(sessionState))
1944 goToBackForwardItem(currentItemID);
1947 #if ENABLE(TOUCH_EVENTS)
1948 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1950 if (!page->mainFrame().view())
1953 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
1956 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1958 bool handled = false;
1960 if (canHandleUserEvents()) {
1961 CurrentEvent currentEvent(touchEvent);
1963 handled = handleTouchEvent(touchEvent, m_page.get());
1965 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1968 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
1970 CurrentEvent currentEvent(touchEvent);
1971 handled = handleTouchEvent(touchEvent, m_page.get());
1975 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1977 return page->userInputBridge().scrollRecursively(direction, granularity);
1980 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1982 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
1985 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1987 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1990 void WebPage::centerSelectionInVisibleArea()
1992 Frame& frame = m_page->focusController().focusedOrMainFrame();
1993 frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
1994 m_findController.showFindIndicatorInSelection();
1997 #if ENABLE(REMOTE_INSPECTOR)
1998 void WebPage::setAllowsRemoteInspection(bool allow)
2000 m_page->setRemoteInspectionAllowed(allow);
2004 void WebPage::setDrawsBackground(bool drawsBackground)
2006 if (m_drawsBackground == drawsBackground)
2009 m_drawsBackground = drawsBackground;
2011 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2012 if (FrameView* view = coreFrame->view())
2013 view->setTransparent(!drawsBackground);
2016 m_drawingArea->pageBackgroundTransparencyChanged();
2017 m_drawingArea->setNeedsDisplay();
2020 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
2022 if (m_drawsTransparentBackground == drawsTransparentBackground)
2025 m_drawsTransparentBackground = drawsTransparentBackground;
2027 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2028 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2029 if (FrameView* view = coreFrame->view())
2030 view->setBaseBackgroundColor(backgroundColor);
2033 m_drawingArea->pageBackgroundTransparencyChanged();
2034 m_drawingArea->setNeedsDisplay();
2037 void WebPage::setTopContentInset(float contentInset)
2039 m_page->setTopContentInset(contentInset);
2042 void WebPage::viewWillStartLiveResize()
2047 // FIXME: This should propagate to all ScrollableAreas.
2048 Frame& frame = m_page->focusController().focusedOrMainFrame();
2049 if (FrameView* view = frame.view())
2050 view->willStartLiveResize();
2053 void WebPage::viewWillEndLiveResize()
2058 // FIXME: This should propagate to all ScrollableAreas.
2059 Frame& frame = m_page->focusController().focusedOrMainFrame();
2060 if (FrameView* view = frame.view())
2061 view->willEndLiveResize();
2064 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
2069 Frame& frame = m_page->focusController().focusedOrMainFrame();
2070 frame.document()->setFocusedElement(0);
2072 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2073 PlatformKeyboardEvent platformEvent(platform(event));
2074 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2075 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2079 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2082 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
2084 if (m_windowResizerSize == windowResizerSize)
2087 m_windowResizerSize = windowResizerSize;
2089 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2090 FrameView* view = coreFrame->view();
2092 view->windowResizerRectChanged();
2096 void WebPage::setCanStartMediaTimerFired()
2099 m_page->setCanStartMedia(true);
2103 void WebPage::didUpdateViewStateTimerFired()
2105 send(Messages::WebPageProxy::DidUpdateViewState());
2109 inline bool WebPage::canHandleUserEvents() const
2111 #if USE(TILED_BACKING_STORE)
2112 // Should apply only if the area was frozen by didStartPageTransition().
2113 return !m_drawingArea->layerTreeStateIsFrozen();
2118 void WebPage::updateIsInWindow(bool isInitialState)
2120 bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2123 m_setCanStartMediaTimer.stop();
2124 m_page->setCanStartMedia(false);
2126 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2127 if (!isInitialState)
2128 WebProcess::shared().pageWillLeaveWindow(m_pageID);
2130 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2131 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2132 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2133 if (m_mayStartMediaWhenInWindow)
2134 m_setCanStartMediaTimer.startOneShot(0);
2136 WebProcess::shared().pageDidEnterWindow(m_pageID);
2143 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState)
2145 ViewState::Flags changed = m_viewState ^ viewState;
2146 m_viewState = viewState;
2148 m_drawingArea->viewStateDidChange(changed);
2149 m_page->setViewState(viewState);
2150 for (auto* pluginView : m_pluginViews)
2151 pluginView->viewStateDidChange(changed);
2153 if (changed & ViewState::IsInWindow)
2156 if (wantsDidUpdateViewState)
2157 m_sendDidUpdateViewStateTimer.startOneShot(0);
2160 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2162 m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2164 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2166 for (auto* pluginView : m_pluginViews)
2167 pluginView->setLayerHostingMode(m_layerHostingMode);
2170 SessionID WebPage::sessionID() const
2172 if (m_page->isSessionIDSet())
2173 return m_page->sessionID();
2175 return m_page->settings().privateBrowsingEnabled() ? SessionID::legacyPrivateSessionID() : SessionID::defaultSessionID();
2178 bool WebPage::isUsingEphemeralSession() const
2180 return sessionID().isEphemeral();
2183 void WebPage::setSessionID(SessionID sessionID)
2185 m_page->setSessionID(sessionID);
2186 if (sessionID.isEphemeral())
2187 WebProcess::shared().ensurePrivateBrowsingSession(sessionID);
2190 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
2192 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2195 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
2198 void WebPage::didStartPageTransition()
2200 m_drawingArea->setLayerTreeStateIsFrozen(true);
2203 void WebPage::didCompletePageTransition()
2205 #if USE(TILED_BACKING_STORE)
2206 if (m_mainFrame->coreFrame()->view()->delegatesScrolling())
2207 // Wait until the UI process sent us the visible rect it wants rendered.
2208 send(Messages::WebPageProxy::PageTransitionViewportReady());
2212 m_drawingArea->setLayerTreeStateIsFrozen(false);
2215 void WebPage::show()
2217 send(Messages::WebPageProxy::ShowPage());
2220 void WebPage::setUserAgent(const String& userAgent)
2222 m_userAgent = userAgent;
2225 void WebPage::suspendActiveDOMObjectsAndAnimations()
2227 m_page->suspendActiveDOMObjectsAndAnimations();
2230 void WebPage::resumeActiveDOMObjectsAndAnimations()
2232 m_page->resumeActiveDOMObjectsAndAnimations();
2235 IntPoint WebPage::screenToRootView(const IntPoint& point)
2237 IntPoint windowPoint;
2238 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2242 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2245 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2249 IntRect WebPage::windowResizerRect() const
2251 if (m_windowResizerSize.isEmpty())
2254 IntSize frameViewSize;
2255 if (Frame* coreFrame = m_mainFrame->coreFrame()) {
2256 if (FrameView* view = coreFrame->view())
2257 frameViewSize = view->size();
2260 return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(),
2261 m_windowResizerSize.width(), m_windowResizerSize.height());
2264 KeyboardUIMode WebPage::keyboardUIMode()
2266 bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
2267 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2270 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2272 // NOTE: We need to be careful when running scripts that the objects we depend on don't
2273 // disappear during script execution.
2275 // Retain the SerializedScriptValue at this level so it (and the internal data) lives
2276 // long enough for the DataReference to be encoded by the sent message.
2277 RefPtr<SerializedScriptValue> serializedResultValue;
2278 IPC::DataReference dataReference;
2280 JSLockHolder lock(JSDOMWindow::commonVM());
2281 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) {
2282 if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
2283 dataReference = serializedResultValue->data();
2286 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2289 void WebPage::getContentsAsString(uint64_t callbackID)
2291 String resultString = m_mainFrame->contentsAsString();
2292 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2296 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2298 IPC::DataReference dataReference;
2300 RefPtr<SharedBuffer> buffer = useBinaryEncoding
2301 ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2302 : MHTMLArchive::generateMHTMLData(m_page.get());
2305 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2307 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2311 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2313 String resultString = renderTreeExternalRepresentation();
2314 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2317 static Frame* frameWithSelection(Page* page)
2319 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2320 if (frame->selection().isRange())
2327 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2329 IPC::DataReference dataReference;
2332 RefPtr<LegacyWebArchive> archive;
2333 RetainPtr<CFDataRef> data;
2335 Frame* frame = frameWithSelection(m_page.get());
2337 archive = LegacyWebArchive::createFromSelection(frame);
2338 data = archive->rawDataRepresentation();
2339 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2343 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2346 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2348 String resultString = m_mainFrame->selectionAsString();
2349 if (resultString.isEmpty())
2350 resultString = m_mainFrame->contentsAsString();
2351 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2354 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2356 String resultString;
2357 if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
2358 resultString = frame->source();
2360 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2363 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2365 IPC::DataReference dataReference;
2367 RefPtr<ResourceBuffer> buffer;
2368 RefPtr<SharedBuffer> pdfResource;
2369 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2370 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame())) {
2371 if ((pdfResource = pluginView->liveResourceData()))
2372 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(pdfResource->data()), pdfResource->size());
2375 if (dataReference.isEmpty()) {
2376 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader()) {
2377 if ((buffer = loader->mainResourceData()))
2378 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2383 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2386 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2388 DocumentLoader* loader = frame->loader().documentLoader();
2392 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2396 return subresource->data();
2399 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2401 IPC::DataReference dataReference;
2402 URL resourceURL(URL(), resourceURLString);
2404 RefPtr<SharedBuffer> buffer;
2405 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2406 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2408 // Try to get the resource data from the cache.
2409 buffer = cachedResponseDataForURL(resourceURL);
2413 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2416 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2419 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2421 IPC::DataReference dataReference;
2424 RetainPtr<CFDataRef> data;
2425 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2426 if ((data = frame->webArchiveData(0, 0)))
2427 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2430 UNUSED_PARAM(frameID);
2433 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2436 void WebPage::forceRepaintWithoutCallback()
2438 m_drawingArea->forceRepaint();
2441 void WebPage::forceRepaint(uint64_t callbackID)
2443 if (m_drawingArea->forceRepaintAsync(callbackID))
2446 forceRepaintWithoutCallback();
2447 send(Messages::WebPageProxy::VoidCallback(callbackID));
2450 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2452 WebPreferencesStore::removeTestRunnerOverrides();
2453 updatePreferences(store);
2456 void WebPage::updatePreferences(const WebPreferencesStore& store)
2458 Settings& settings = m_page->settings();
2460 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2461 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2462 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2463 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2465 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2468 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2471 // FIXME: This should be generated from macro expansion for all preferences,
2472 // but we currently don't match the naming of WebCore exactly so we are
2473 // handrolling the boolean and integer preferences until that is fixed.
2475 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2477 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2479 #undef INITIALIZE_SETTINGS
2481 settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2482 settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2483 settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2484 settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2485 settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2486 settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2487 settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));
2488 settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2489 settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2490 settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2491 settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2492 if (m_page->isSessionIDSet())
2493 settings.setPrivateBrowsingEnabled(m_page->sessionID().isEphemeral());
2495 settings.setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
2496 settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2497 settings.setJavaScriptExperimentsEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptExperimentsEnabledKey()));
2498 settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2499 settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2500 settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2501 settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2502 settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2503 #if ENABLE(WEB_ARCHIVE)
2504 settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2506 settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2507 settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2508 settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2509 settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2510 settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2511 settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2512 settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2513 settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2514 settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2515 settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2516 settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2518 settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2519 settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2520 settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2521 settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2522 settings.setScreenFontSubstitutionEnabled(store.getBoolValueForKey(WebPreferencesKey::screenFontSubstitutionEnabledKey())
2524 || WebProcess::shared().shouldForceScreenFontSubstitution()
2527 settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2528 settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2529 settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2530 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2531 settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2533 settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2534 settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2535 settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2536 settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2537 settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2538 settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2539 settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2540 settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2541 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2542 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2543 #if ENABLE(CSS_GRID_LAYOUT)
2544 settings.setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
2546 settings.setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
2547 settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2548 settings.setMultithreadedWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::multithreadedWebGLEnabledKey()));
2549 settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2550 settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2551 settings.setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
2552 settings.setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
2553 settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2554 settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2555 settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2556 #if ENABLE(SMOOTH_SCROLLING)
2557 settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2559 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2560 settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2562 #if ENABLE(SQL_DATABASE)
2563 DatabaseManager::manager().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2566 #if ENABLE(FULLSCREEN_API)
2567 settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2570 #if USE(AVFOUNDATION)
2571 settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2575 settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2578 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2579 settings.setVideoPluginProxyEnabled(false);
2583 settings.setAVKitEnabled(true);
2586 #if ENABLE(IOS_TEXT_AUTOSIZING)
2587 settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2590 #if ENABLE(WEB_AUDIO)
2591 settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2594 #if ENABLE(MEDIA_STREAM)
2595 settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2598 #if ENABLE(IMAGE_CONTROLS)
2599 settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2602 settings.setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2603 settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2604 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2605 settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2606 settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2607 settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2609 #if ENABLE(VIDEO_TRACK)
2610 settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2611 settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2612 settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2615 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2616 settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2619 settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2620 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2621 settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2623 settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2625 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2627 settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2628 settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2629 settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2630 settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2631 settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2633 #if ENABLE(TEXT_AUTOSIZING)
2634 settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2637 settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2638 settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2640 settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2641 settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2642 settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2644 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2645 settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2647 #if ENABLE(PAGE_VISIBILITY_API)
2648 settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2651 settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2652 settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2653 settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2655 settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2657 #if ENABLE(MEDIA_SOURCE)
2658 settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2661 settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2663 settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2664 settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2665 settings.setAlwaysUseBaselineOfPrimaryFont(store.getBoolValueForKey(WebPreferencesKey::alwaysUseBaselineOfPrimaryFontKey()));
2666 settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2667 settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2669 settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2670 settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2672 settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2673 settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2675 settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2677 if (store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey()))
2678 m_processSuppressionDisabledByWebPreference.stop();
2680 m_processSuppressionDisabledByWebPreference.start();
2682 platformPreferencesDidChange(store);
2685 m_drawingArea->updatePreferences(store);
2689 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2691 layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2692 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2693 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2694 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2696 layerTransaction.setLastVisibleContentRectUpdateID(m_lastVisibleContentRectUpdateID);
2697 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2698 layerTransaction.setMinimumScaleFactor(minimumPageScaleFactor());
2699 layerTransaction.setMaximumScaleFactor(maximumPageScaleFactor());
2700 layerTransaction.setAllowsUserScaling(allowsUserScaling());
2706 #if ENABLE(INSPECTOR)
2707 WebInspector* WebPage::inspector()
2712 m_inspector = WebInspector::create(this, m_inspectorClient);
2713 return m_inspector.get();
2718 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
2720 if (!m_videoFullscreenManager)
2721 m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
2722 return m_videoFullscreenManager.get();
2726 #if ENABLE(FULLSCREEN_API)
2727 WebFullScreenManager* WebPage::fullScreenManager()
2729 if (!m_fullScreenManager)
2730 m_fullScreenManager = WebFullScreenManager::create(this);
2731 return m_fullScreenManager.get();
2735 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2737 if (m_notificationPermissionRequestManager)
2738 return m_notificationPermissionRequestManager.get();
2740 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2741 return m_notificationPermissionRequestManager.get();
2744 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
2745 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2747 Node* node = evt->target()->toNode();
2749 Frame* frame = node->document().frame();
2752 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2756 Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
2758 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2759 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2760 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2761 // (e.g. Tab that inserts a Tab character, or Enter).
2762 return !command.isTextInsertion() && command.execute(evt);
2765 if (command.execute(evt))
2768 // Don't allow text insertion for nodes that cannot edit.
2769 if (!frame->editor().canEdit())
2772 // Don't insert null or control characters as they can result in unexpected behaviour
2773 if (evt->charCode() < ' ')
2776 return frame->editor().insertText(evt->keyEvent()->text(), evt);
2780 #if ENABLE(DRAG_SUPPORT)
2783 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2786 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2787 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2793 case DragControllerActionEntered:
2794 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData)));
2797 case DragControllerActionUpdated:
2798 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData)));
2801 case DragControllerActionExited:
2802 m_page->dragController().dragExited(dragData);
2805 case DragControllerActionPerformDrag: {
2806 m_page->dragController().performDrag(dragData);
2811 ASSERT_NOT_REACHED();
2813 // DragData does not delete its platformData so we need to do that here.
2814 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2819 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)
2822 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2826 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2828 case DragControllerActionEntered:
2829 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData)));
2832 case DragControllerActionUpdated:
2833 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData)));
2836 case DragControllerActionExited:
2837 m_page->dragController().dragExited(dragData);
2840 case DragControllerActionPerformDrag: {
2841 ASSERT(!m_pendingDropSandboxExtension);
2843 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2844 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
2845 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
2846 m_pendingDropExtensionsForFileUpload.append(extension);
2849 m_page->dragController().performDrag(dragData);
2851 // If we started loading a local file, the sandbox extension tracker would have adopted this
2852 // pending drop sandbox extension. If not, we'll play it safe and clear it.
2853 m_pendingDropSandboxExtension = nullptr;
2855 m_pendingDropExtensionsForFileUpload.clear();
2860 ASSERT_NOT_REACHED();
2865 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2867 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
2868 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
2870 m_page->dragController().dragEnded();
2871 FrameView* view = m_page->mainFrame().view();
2874 // FIXME: These are fake modifier keys here, but they should be real ones instead.
2875 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2876 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
2879 void WebPage::willPerformLoadDragDestinationAction()
2881 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2884 void WebPage::mayPerformUploadDragDestinationAction()
2886 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2887 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
2888 m_pendingDropExtensionsForFileUpload.clear();
2891 #endif // ENABLE(DRAG_SUPPORT)
2893 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2895 return m_undoStepMap.get(stepID);
2898 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2900 m_undoStepMap.set(stepID, entry);
2903 void WebPage::removeWebEditCommand(uint64_t stepID)
2905 m_undoStepMap.remove(stepID);
2908 void WebPage::unapplyEditCommand(uint64_t stepID)
2910 WebUndoStep* step = webUndoStep(stepID);
2914 step->step()->unapply();
2917 void WebPage::reapplyEditCommand(uint64_t stepID)
2919 WebUndoStep* step = webUndoStep(stepID);
2924 step->step()->reapply();
2928 void WebPage::didRemoveEditCommand(uint64_t commandID)
2930 removeWebEditCommand(commandID);
2933 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2935 m_activePopupMenu = menu;
2938 #if ENABLE(INPUT_TYPE_COLOR)
2939 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
2941 m_activeColorChooser = colorChooser;
2944 void WebPage::didEndColorPicker()
2946 m_activeColorChooser->didEndChooser();
2949 void WebPage::didChooseColor(const WebCore::Color& color)
2951 m_activeColorChooser->didChooseColor(color);
2955 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2957 m_activeOpenPanelResultListener = openPanelResultListener;
2960 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2962 return m_page->findString(target, options);
2965 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2967 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2970 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2972 m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2975 void WebPage::getImageForFindMatch(uint32_t matchIndex)
2977 m_findController.getImageForFindMatch(matchIndex);
2980 void WebPage::selectFindMatch(uint32_t matchIndex)
2982 m_findController.selectFindMatch(matchIndex);
2985 void WebPage::hideFindUI()
2987 m_findController.hideFindUI();
2990 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2992 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2995 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2997 changeSelectedIndex(newIndex);
2998 m_activePopupMenu = 0;
3001 void WebPage::changeSelectedIndex(int32_t index)
3003 if (!m_activePopupMenu)
3006 m_activePopupMenu->didChangeSelectedIndex(index);
3009 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3011 if (!m_activeOpenPanelResultListener)
3014 m_activeOpenPanelResultListener->didChooseFiles(files);
3015 m_activeOpenPanelResultListener = 0;
3018 void WebPage::didCancelForOpenPanel()
3020 m_activeOpenPanelResultListener = 0;
3023 #if ENABLE(WEB_PROCESS_SANDBOX)
3024 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3026 SandboxExtension::create(handle)->consumePermanently();
3030 #if ENABLE(GEOLOCATION)
3031 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3033 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3037 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3039 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3043 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3045 Frame& frame = m_page->focusController().focusedOrMainFrame();
3046 frame.editor().advanceToNextMisspelling(startBeforeSelection);
3050 void WebPage::changeSpellingToWord(const String& word)
3052 replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3055 void WebPage::unmarkAllMisspellings()
3057 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3058 if (Document* document = frame->document())
3059 document->markers().removeMarkers(DocumentMarker::Spelling);
3063 void WebPage::unmarkAllBadGrammar()
3065 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3066 if (Document* document = frame->document())
3067 document->markers().removeMarkers(DocumentMarker::Grammar);
3072 void WebPage::uppercaseWord()
3074 m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3077 void WebPage::lowercaseWord()
3079 m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3082 void WebPage::capitalizeWord()
3084 m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3088 void WebPage::setTextForActivePopupMenu(int32_t index)
3090 if (!m_activePopupMenu)
3093 m_activePopupMenu->setTextForIndex(index);
3097 void WebPage::failedToShowPopupMenu()
3099 if (!m_activePopupMenu)
3102 m_activePopupMenu->client()->popupDidHide();
3106 #if ENABLE(CONTEXT_MENUS)
3107 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3112 m_contextMenu->itemSelected(item);
3117 #if ENABLE(IMAGE_CONTROLS)
3118 void WebPage::replaceControlledImage(const ShareableBitmap::Handle& bitmapHandle)
3120 RefPtr<ShareableBitmap> bitmap = ShareableBitmap::create(bitmapHandle);
3122 m_contextMenu->replaceControlledImage(bitmap->createImage());
3126 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3128 bool selectReplacement = true;
3129 bool smartReplace = false;
3130 return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3134 void WebPage::clearSelection()
3136 m_page->focusController().focusedOrMainFrame().selection().clear();
3140 bool WebPage::mainFrameHasCustomContentProvider() const
3142 if (Frame* frame = mainFrame()) {
3143 WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3144 ASSERT(webFrameLoaderClient);
3145 return webFrameLoaderClient->frameHasCustomContentProvider();
3151 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3153 m_mimeTypesWithCustomContentProviders.add(mimeType);
3156 void WebPage::updateMainFrameScrollOffsetPinning()
3158 Frame& frame = m_page->mainFrame();
3159 IntPoint scrollPosition = frame.view()->scrollPosition();
3160 IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3161 IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3163 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3164 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3165 bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3166 bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3168 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3169 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3171 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3172 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3173 m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3174 m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3178 void WebPage::mainFrameDidLayout()
3180 unsigned pageCount = m_page->pageCount();
3181 if (pageCount != m_cachedPageCount) {
3182 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3183 m_cachedPageCount = pageCount;
3186 #if USE(TILED_BACKING_STORE)
3187 if (m_drawingArea && m_drawingArea->layerTreeHost()) {
3188 double red, green, blue, alpha;
3189 m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha);
3190 RGBA32 rgba = makeRGBA32FromFloats(red, green, blue, alpha);
3191 if (m_backgroundColor.rgb() != rgba) {
3192 m_backgroundColor.setRGB(rgba);
3193 m_drawingArea->layerTreeHost()->setBackgroundColor(m_backgroundColor);
3199 m_viewGestureGeometryCollector.mainFrameDidLayout();
3202 if (FrameView* frameView = mainFrameView()) {
3203 m_viewportConfiguration.setContentsSize(frameView->contentsSize());
3204 viewportConfigurationChanged();
3209 void WebPage::addPluginView(PluginView* pluginView)
3211 ASSERT(!m_pluginViews.contains(pluginView));
3213 m_pluginViews.add(pluginView);
3214 m_hasSeenPlugin = true;
3215 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3216 LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3217 m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3221 void WebPage::removePluginView(PluginView* pluginView)
3223 ASSERT(m_pluginViews.contains(pluginView));
3225 m_pluginViews.remove(pluginView);
3226 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3227 LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3231 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3234 m_hasCachedWindowFrame = false;
3236 send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3240 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3242 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3243 m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3244 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3245 m_accessibilityPosition = accessibilityViewCoordinates;
3247 // Tell all our plug-in views that the window and view frames have changed.
3248 for (auto* pluginView : m_pluginViews)
3249 pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3251 m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3255 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3257 m_mainFrameIsScrollable = isScrollable;
3258 m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3260 if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3261 frameView->setCanHaveScrollbars(isScrollable);
3262 frameView->setProhibitsScrolling(!isScrollable);
3266 bool WebPage::windowIsFocused() const
3268 return m_page->focusController().isActive();
3271 bool WebPage::windowAndWebPageAreFocused() const
3276 return m_page->focusController().isFocused() && m_page->focusController().isActive();
3279 void WebPage::didReceiveMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder)
3281 if (decoder.messageReceiverName() == Messages::DrawingArea::messageReceiverName()) {
3283 m_drawingArea->didReceiveDrawingAreaMessage(connection, decoder);
3287 #if USE(TILED_BACKING_STORE)
3288 if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
3290 m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
3295 #if ENABLE(INSPECTOR)
3296 if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
3297 if (WebInspector* inspector = this->inspector())
3298 inspector->didReceiveWebInspectorMessage(connection, decoder);
3303 #if ENABLE(FULLSCREEN_API)
3304 if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
3305 fullScreenManager()->didReceiveMessage(connection, decoder);
3310 didReceiveWebPageMessage(connection, decoder);
3313 void WebPage::didReceiveSyncMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder)
3315 didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
3318 InjectedBundleBackForwardList* WebPage::backForwardList()
3320 if (!m_backForwardList)
3321 m_backForwardList = InjectedBundleBackForwardList::create(this);
3322 return m_backForwardList.get();
3325 #if ENABLE(ASYNC_SCROLLING)
3326 ScrollingCoordinator* WebPage::scrollingCoordinator() const
3328 return m_page->scrollingCoordinator();
3332 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3337 void WebPage::SandboxExtensionTracker::invalidate()
3339 m_pendingProvisionalSandboxExtension = nullptr;
3341 if (m_provisionalSandboxExtension) {
3342 m_provisionalSandboxExtension->revoke();
3343 m_provisionalSandboxExtension = nullptr;
3346 if (m_committedSandboxExtension) {
3347 m_committedSandboxExtension->revoke();
3348 m_committedSandboxExtension = nullptr;
3352 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3354 setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3357 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3359 ASSERT_UNUSED(frame, frame->isMainFrame());
3361 setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3364 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3366 m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;
3369 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3371 ASSERT(frame->isMainFrame());
3373 FrameLoader& frameLoader = frame->coreFrame()->loader();
3374 FrameLoadType frameLoadType = frameLoader.loadType();
3376 // If the page is being reloaded, it should reuse whatever extension is committed.
3377 if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
3380 DocumentLoader* documentLoader = frameLoader.documentLoader();
3381 DocumentLoader* provisionalDocumentLoader = frameLoader.provisionalDocumentLoader();
3382 if (!documentLoader || !provisionalDocumentLoader)
3385 if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3391 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3393 if (!frame->isMainFrame())
3396 // We should only reuse the commited sandbox extension if it is not null. It can be
3397 // null if the last load was for an error page.
3398 if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame))
3399 m_pendingProvisionalSandboxExtension = m_committedSandboxExtension;
3401 ASSERT(!m_provisionalSandboxExtension);
3403 m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3404 if (!m_provisionalSandboxExtension)
3407 ASSERT(!m_provisionalSandboxExtension || frame->coreFrame()->loader().provisionalDocumentLoader()->url().isLocalFile());
3409 m_provisionalSandboxExtension->consume();
3412 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3414 if (!frame->isMainFrame())
3417 if (m_committedSandboxExtension)
3418 m_committedSandboxExtension->revoke();
3420 m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3422 // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started.
3423 // This extension is not cleared, because it does not pertain to the failed load, and will be needed.
3426 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3428 if (!frame->isMainFrame())
3431 if (!m_provisionalSandboxExtension)
3434 m_provisionalSandboxExtension->revoke();
3435 m_provisionalSandboxExtension = nullptr;
3437 // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started
3438 // (notably, if the current one fails because the new one cancels it). This extension is not cleared,
3439 // because it does not pertain to the failed load, and will be needed.
3442 bool WebPage::hasLocalDataForURL(const URL& url)
3444 if (url.isLocalFile())
3447 DocumentLoader* documentLoader = m_page->mainFrame().loader().documentLoader();
3448 if (documentLoader && documentLoader->subresource(url))
3451 return platformHasLocalDataForURL(url);
3454 void WebPage::setCustomTextEncodingName(const String& encoding)
3456 m_page->mainFrame().loader().reloadWithOverrideEncoding(encoding);
3459 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3461 WebBackForwardListProxy::removeItem(itemID);
3466 bool WebPage::isSpeaking()
3469 return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3472 void WebPage::speak(const String& string)
3474 send(Messages::WebPageProxy::Speak(string));
3477 void WebPage::stopSpeaking()
3479 send(Messages::WebPageProxy::StopSpeaking());
3485 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3487 Document* document = coreFrame->document();
3491 if (!document->isPluginDocument())
3494 PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
3498 return pluginView->pdfDocumentForPrinting();
3500 #endif // PLATFORM(MAC)
3502 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3504 WebFrame* frame = WebProcess::shared().webFrame(frameID);
3508 Frame* coreFrame = frame->coreFrame();
3513 if (pdfDocumentForPrintingFrame(coreFrame))
3515 #endif // PLATFORM(MAC)
3517 if (!m_printContext)
3518 m_printContext = adoptPtr(new PrintContext(coreFrame));
3520 drawingArea()->setLayerTreeStateIsFrozen(true);
3521 m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3523 float fullPageHeight;
3524 m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3527 if (!m_printOperation)
3528 m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3532 void WebPage::endPrinting()
3534 drawingArea()->setLayerTreeStateIsFrozen(false);
3535 m_printContext = nullptr;
3538 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3540 Vector<IntRect> resultPageRects;
3541 double resultTotalScaleFactorForPrinting = 1;
3543 beginPrinting(frameID, printInfo);
3545 if (m_printContext) {
3546 resultPageRects = m_printContext->pageRects();
3547 resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3551 computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3552 #endif // PLATFORM(COCOA)
3554 // If we're asked to print, we should actually print at least a blank page.
3555 if (resultPageRects.isEmpty())
3556 resultPageRects.append(IntRect(0, 0, 1, 1));
3558 send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));