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 "DragControllerAction.h"
34 #include "DrawingArea.h"
35 #include "DrawingAreaMessages.h"
36 #include "EditingRange.h"
37 #include "EditorState.h"
38 #include "EventDispatcher.h"
39 #include "InjectedBundle.h"
40 #include "InjectedBundleBackForwardList.h"
41 #include "InjectedBundleUserMessageCoders.h"
42 #include "LayerTreeHost.h"
44 #include "NetscapePlugin.h"
45 #include "NotificationPermissionRequestManager.h"
46 #include "PageBanner.h"
47 #include "PluginProcessAttributes.h"
48 #include "PluginProxy.h"
49 #include "PluginView.h"
50 #include "PrintInfo.h"
51 #include "ServicesOverlayController.h"
52 #include "SessionState.h"
53 #include "SessionStateConversion.h"
54 #include "SessionTracker.h"
55 #include "ShareableBitmap.h"
56 #include "VisitedLinkTableController.h"
57 #include "WKBundleAPICast.h"
58 #include "WKRetainPtr.h"
59 #include "WKSharedAPICast.h"
60 #include "WebAlternativeTextClient.h"
61 #include "WebBackForwardListItem.h"
62 #include "WebBackForwardListProxy.h"
63 #include "WebChromeClient.h"
64 #include "WebColorChooser.h"
65 #include "WebContextMenu.h"
66 #include "WebContextMenuClient.h"
67 #include "WebContextMessages.h"
68 #include "WebCoreArgumentCoders.h"
69 #include "WebDocumentLoader.h"
70 #include "WebDragClient.h"
71 #include "WebEditorClient.h"
73 #include "WebEventConversion.h"
75 #include "WebFrameLoaderClient.h"
76 #include "WebFullScreenManager.h"
77 #include "WebFullScreenManagerMessages.h"
78 #include "WebGeolocationClient.h"
80 #include "WebInspector.h"
81 #include "WebInspectorClient.h"
82 #include "WebInspectorMessages.h"
83 #include "WebNotificationClient.h"
84 #include "WebOpenPanelResultListener.h"
85 #include "WebPageCreationParameters.h"
86 #include "WebPageGroupProxy.h"
87 #include "WebPageMessages.h"
88 #include "WebPageProxyMessages.h"
89 #include "WebPlugInClient.h"
90 #include "WebPopupMenu.h"
91 #include "WebPreferencesDefinitions.h"
92 #include "WebPreferencesKeys.h"
93 #include "WebPreferencesStore.h"
94 #include "WebProcess.h"
95 #include "WebProcessProxyMessages.h"
96 #include "WebProgressTrackerClient.h"
97 #include "WebUndoStep.h"
98 #include "WebUserContentController.h"
99 #include <JavaScriptCore/APICast.h>
100 #include <WebCore/ArchiveResource.h>
101 #include <WebCore/Chrome.h>
102 #include <WebCore/ContextMenuController.h>
103 #include <WebCore/DatabaseManager.h>
104 #include <WebCore/DocumentFragment.h>
105 #include <WebCore/DocumentLoader.h>
106 #include <WebCore/DocumentMarkerController.h>
107 #include <WebCore/DragController.h>
108 #include <WebCore/DragData.h>
109 #include <WebCore/ElementIterator.h>
110 #include <WebCore/EventHandler.h>
111 #include <WebCore/FocusController.h>
112 #include <WebCore/FormState.h>
113 #include <WebCore/FrameLoadRequest.h>
114 #include <WebCore/FrameLoaderTypes.h>
115 #include <WebCore/FrameView.h>
116 #include <WebCore/HTMLFormElement.h>
117 #include <WebCore/HTMLInputElement.h>
118 #include <WebCore/HTMLPlugInElement.h>
119 #include <WebCore/HTMLPlugInImageElement.h>
120 #include <WebCore/HistoryController.h>
121 #include <WebCore/HistoryItem.h>
122 #include <WebCore/HitTestResult.h>
123 #include <WebCore/JSDOMWindow.h>
124 #include <WebCore/KeyboardEvent.h>
125 #include <WebCore/MIMETypeRegistry.h>
126 #include <WebCore/MainFrame.h>
127 #include <WebCore/MouseEvent.h>
128 #include <WebCore/Page.h>
129 #include <WebCore/PageThrottler.h>
130 #include <WebCore/PlatformKeyboardEvent.h>
131 #include <WebCore/PluginDocument.h>
132 #include <WebCore/PrintContext.h>
133 #include <WebCore/Range.h>
134 #include <WebCore/RenderLayer.h>
135 #include <WebCore/RenderTreeAsText.h>
136 #include <WebCore/RenderView.h>
137 #include <WebCore/ResourceBuffer.h>
138 #include <WebCore/ResourceRequest.h>
139 #include <WebCore/ResourceResponse.h>
140 #include <WebCore/RuntimeEnabledFeatures.h>
141 #include <WebCore/SchemeRegistry.h>
142 #include <WebCore/ScriptController.h>
143 #include <WebCore/SerializedScriptValue.h>
144 #include <WebCore/SessionID.h>
145 #include <WebCore/Settings.h>
146 #include <WebCore/ShadowRoot.h>
147 #include <WebCore/SharedBuffer.h>
148 #include <WebCore/SubframeLoader.h>
149 #include <WebCore/SubstituteData.h>
150 #include <WebCore/TextIterator.h>
151 #include <WebCore/UserInputBridge.h>
152 #include <WebCore/VisiblePosition.h>
153 #include <WebCore/VisibleUnits.h>
154 #include <WebCore/markup.h>
155 #include <bindings/ScriptValue.h>
156 #include <profiler/ProfilerDatabase.h>
157 #include <runtime/JSCInlines.h>
158 #include <runtime/JSCJSValue.h>
159 #include <runtime/JSLock.h>
160 #include <wtf/RunLoop.h>
163 #include <WebCore/MHTMLArchive.h>
166 #if ENABLE(BATTERY_STATUS)
167 #include "WebBatteryClient.h"
170 #if ENABLE(VIBRATION)
171 #include "WebVibrationClient.h"
174 #if ENABLE(PROXIMITY_EVENTS)
175 #include "WebDeviceProximityClient.h"
179 #include "PDFPlugin.h"
180 #include "RemoteLayerTreeTransaction.h"
181 #include "WKStringCF.h"
182 #include <WebCore/LegacyWebArchive.h>
187 #include "DataObjectGtk.h"
188 #include "WebPrintOperationGtk.h"
192 #include "RemoteLayerTreeDrawingArea.h"
193 #include "WebVideoFullscreenManager.h"
194 #include <CoreGraphics/CoreGraphics.h>
195 #include <CoreText/CTFontDescriptorPriv.h>
196 #include <CoreText/CTFontPriv.h>
197 #include <WebCore/Icon.h>
201 #include <wtf/RefCountedLeakCounter.h>
204 #if USE(COORDINATED_GRAPHICS)
205 #include "CoordinatedLayerTreeHostMessages.h"
209 using namespace WebCore;
213 class SendStopResponsivenessTimer {
215 SendStopResponsivenessTimer(WebPage* page)
220 ~SendStopResponsivenessTimer()
222 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
229 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
231 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
233 RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
235 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
236 WebProcess::shared().injectedBundle()->didCreatePage(page.get());
238 return page.release();
241 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
243 , m_viewSize(parameters.viewSize)
244 , m_hasSeenPlugin(false)
245 , m_useFixedLayout(false)
246 , m_drawsBackground(true)
247 , m_drawsTransparentBackground(false)
250 , m_tabToLinks(false)
251 , m_asynchronousPluginInitializationEnabled(false)
252 , m_asynchronousPluginInitializationEnabledForAllPlugins(false)
253 , m_artificialPluginInitializationDelayEnabled(false)
254 , m_scrollingPerformanceLoggingEnabled(false)
255 , m_mainFrameIsScrollable(true)
256 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
257 , m_readyToFindPrimarySnapshottedPlugin(false)
258 , m_didFindPrimarySnapshottedPlugin(false)
259 , m_numberOfPrimarySnapshotDetectionAttempts(0)
260 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
262 #if ENABLE(SERVICE_CONTROLS)
263 , m_serviceControlsEnabled(false)
265 , m_layerHostingMode(parameters.layerHostingMode)
267 , m_pdfPluginEnabled(false)
268 , m_hasCachedWindowFrame(false)
269 , m_viewGestureGeometryCollector(*this)
270 #elif PLATFORM(GTK) && HAVE(ACCESSIBILITY)
271 , m_accessibilityObject(0)
273 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
274 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
275 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
276 , m_findController(this)
277 #if ENABLE(INPUT_TYPE_COLOR)
278 , m_activeColorChooser(0)
280 , m_userContentController(parameters.userContentControllerID ? WebUserContentController::getOrCreate(parameters.userContentControllerID) : nullptr)
281 #if ENABLE(GEOLOCATION)
282 , m_geolocationPermissionRequestManager(this)
284 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
285 , m_canRunModal(parameters.canRunModal)
286 , m_isRunningModal(false)
287 , m_cachedMainFrameIsPinnedToLeftSide(true)
288 , m_cachedMainFrameIsPinnedToRightSide(true)
289 , m_cachedMainFrameIsPinnedToTopSide(true)
290 , m_cachedMainFrameIsPinnedToBottomSide(true)
291 , m_canShortCircuitHorizontalWheelEvents(false)
292 , m_numWheelEventHandlers(0)
293 , m_cachedPageCount(0)
294 , m_autoSizingShouldExpandToViewHeight(false)
295 #if ENABLE(CONTEXT_MENUS)
296 , m_isShowingContextMenu(false)
299 , m_firstLayerTreeTransactionIDAfterDidCommitLoad(0)
300 , m_hasReceivedVisibleContentRectsAfterDidCommitLoad(false)
301 , m_scaleWasSetByUIProcess(false)
302 , m_userHasChangedPageScaleFactor(false)
303 , m_hasStablePageScaleFactor(true)
304 , m_userIsInteracting(false)
305 , m_hasPendingBlurNotification(false)
306 , m_useTestingViewportConfiguration(false)
307 , m_isInStableState(true)
308 , m_oldestNonStableUpdateVisibleContentRectsTimestamp(std::chrono::milliseconds::zero())
309 , m_estimatedLatency(std::chrono::milliseconds::zero())
310 , m_screenSize(parameters.screenSize)
311 , m_availableScreenSize(parameters.availableScreenSize)
312 , m_deviceOrientation(0)
313 , m_inDynamicSizeUpdate(false)
315 , m_inspectorClient(0)
316 , m_backgroundColor(Color::white)
317 , m_maximumRenderingSuppressionToken(0)
318 , m_scrollPinningBehavior(DoNotPin)
319 , m_useAsyncScrolling(false)
320 , m_viewState(parameters.viewState)
321 , m_processSuppressionDisabledByWebPreference("Process suppression is disabled.")
322 , m_pendingNavigationID(0)
323 , m_pageScaleWithoutThumbnailScale(1)
324 , m_thumbnailScale(1)
326 , m_systemWebGLPolicy(WebGLAllowCreation)
328 , m_pageOverlayController(*this)
331 // FIXME: This is a non-ideal location for this Setting and
332 // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
333 Settings::setDefaultMinDOMTimerInterval(0.004);
336 Settings::setShouldManageAudioSessionCategory(true);
339 Page::PageClients pageClients;
340 pageClients.chromeClient = new WebChromeClient(this);
341 #if ENABLE(CONTEXT_MENUS)
342 pageClients.contextMenuClient = new WebContextMenuClient(this);
344 pageClients.editorClient = new WebEditorClient(this);
345 #if ENABLE(DRAG_SUPPORT)
346 pageClients.dragClient = new WebDragClient(this);
348 pageClients.backForwardClient = WebBackForwardListProxy::create(this);
349 #if ENABLE(INSPECTOR)
350 m_inspectorClient = new WebInspectorClient(this);
351 pageClients.inspectorClient = m_inspectorClient;
353 #if USE(AUTOCORRECTION_PANEL)
354 pageClients.alternativeTextClient = new WebAlternativeTextClient(this);
356 pageClients.plugInClient = new WebPlugInClient(this);
357 pageClients.loaderClientForMainFrame = new WebFrameLoaderClient;
358 pageClients.progressTrackerClient = new WebProgressTrackerClient(*this);
360 pageClients.userContentController = m_userContentController ? &m_userContentController->userContentController() : nullptr;
361 pageClients.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
363 m_page = std::make_unique<Page>(pageClients);
365 m_drawingArea = DrawingArea::create(*this, parameters);
366 m_drawingArea->setPaintingEnabled(false);
367 m_pageOverlayController.initialize();
369 #if ENABLE(ASYNC_SCROLLING)
370 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
371 if (!m_drawingArea->supportsAsyncScrolling())
372 m_useAsyncScrolling = false;
373 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
376 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
378 #if ENABLE(BATTERY_STATUS)
379 WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
381 #if ENABLE(GEOLOCATION)
382 WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
384 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
385 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
387 #if ENABLE(VIBRATION)
388 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
390 #if ENABLE(PROXIMITY_EVENTS)
391 WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this));
394 #if ENABLE(REMOTE_INSPECTOR)
395 m_page->setRemoteInspectionAllowed(true);
398 m_page->setCanStartMedia(false);
399 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
401 m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
402 m_page->setGroupName(m_pageGroup->identifier());
403 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
405 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
408 updatePreferences(parameters.store);
409 platformInitialize();
411 setUseFixedLayout(parameters.useFixedLayout);
413 setDrawsBackground(parameters.drawsBackground);
414 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
416 setUnderlayColor(parameters.underlayColor);
418 setPaginationMode(parameters.paginationMode);
419 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
420 setPageLength(parameters.pageLength);
421 setGapBetweenPages(parameters.gapBetweenPages);
423 // If the page is created off-screen, its visibilityState should be prerender.
424 m_page->setViewState(m_viewState);
426 m_page->setIsPrerender();
427 m_page->createPageThrottler();
429 updateIsInWindow(true);
431 setMinimumLayoutSize(parameters.minimumLayoutSize);
432 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
434 setScrollPinningBehavior(parameters.scrollPinningBehavior);
435 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
437 setTopContentInset(parameters.topContentInset);
439 m_userAgent = parameters.userAgent;
441 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
443 if (!parameters.itemStates.isEmpty())
444 restoreSession(parameters.itemStates);
446 if (parameters.sessionID.isValid())
447 setSessionID(parameters.sessionID);
449 m_drawingArea->setPaintingEnabled(true);
451 setMediaVolume(parameters.mediaVolume);
453 // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
454 m_page->addLayoutMilestones(DidFirstLayout | DidFirstVisuallyNonEmptyLayout);
456 WebProcess::shared().addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
458 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
459 WebProcess::shared().addMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID, *this);
460 #if USE(COORDINATED_GRAPHICS)
461 WebProcess::shared().addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this);
463 #if ENABLE(INSPECTOR)
464 WebProcess::shared().addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
466 #if ENABLE(FULLSCREEN_API)
467 WebProcess::shared().addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
471 webPageCounter.increment();
474 #if ENABLE(ASYNC_SCROLLING)
475 if (m_useAsyncScrolling)
476 WebProcess::shared().eventDispatcher().addScrollingTreeForPage(this);
479 for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
480 m_mimeTypesWithCustomContentProviders.add(mimeType);
483 void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters)
485 if (m_viewState != parameters.viewState)
486 setViewState(parameters.viewState);
487 if (m_layerHostingMode != parameters.layerHostingMode)
488 setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode));
493 if (m_backForwardList)
494 m_backForwardList->detach();
498 #if ENABLE(ASYNC_SCROLLING)
499 if (m_useAsyncScrolling)
500 WebProcess::shared().eventDispatcher().removeScrollingTreeForPage(this);
503 m_sandboxExtensionTracker.invalidate();
505 for (auto* pluginView : m_pluginViews)
506 pluginView->webPageDestroyed();
510 m_headerBanner->detachFromPage();
512 m_footerBanner->detachFromPage();
513 #endif // !PLATFORM(IOS)
515 WebProcess::shared().removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
517 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
518 WebProcess::shared().removeMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID);
519 #if USE(COORDINATED_GRAPHICS)
520 WebProcess::shared().removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID);
522 #if ENABLE(INSPECTOR)
523 WebProcess::shared().removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
525 #if ENABLE(FULLSCREEN_API)
526 WebProcess::shared().removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
530 webPageCounter.decrement();
534 void WebPage::dummy(bool&)
538 IPC::Connection* WebPage::messageSenderConnection()
540 return WebProcess::shared().parentProcessConnection();
543 uint64_t WebPage::messageSenderDestinationID()
548 #if ENABLE(CONTEXT_MENUS)
549 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClientBase* client)
551 m_contextMenuClient.initialize(client);
555 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* client)
557 m_editorClient.initialize(client);
560 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient> formClient)
563 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
567 m_formClient = WTF::move(formClient);
570 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client)
572 m_loaderClient.initialize(client);
574 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
575 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
576 // for backwards compatibility.
577 LayoutMilestones milestones = 0;
579 if (m_loaderClient.client().didFirstLayoutForFrame)
580 milestones |= WebCore::DidFirstLayout;
581 if (m_loaderClient.client().didFirstVisuallyNonEmptyLayoutForFrame)
582 milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
586 listenForLayoutMilestones(milestones);
589 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
591 m_policyClient.initialize(client);
594 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase* client)
596 m_resourceLoadClient.initialize(client);
599 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient> uiClient)
602 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
606 m_uiClient = WTF::move(uiClient);
609 #if ENABLE(FULLSCREEN_API)
610 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
612 m_fullScreenClient.initialize(client);
616 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase* client)
618 m_logDiagnosticMessageClient.initialize(client);
621 #if ENABLE(NETSCAPE_PLUGIN_API)
622 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
624 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
625 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
627 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
628 HTMLPlugInImageElement& pluginImageElement = toHTMLPlugInImageElement(*pluginElement);
629 unsigned pluginArea = 0;
630 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
632 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
635 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin);
637 uint64_t pluginProcessToken;
638 uint32_t pluginLoadPolicy;
639 String unavailabilityDescription;
640 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)))
643 bool isBlockedPlugin = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy) == PluginModuleBlocked;
645 if (isBlockedPlugin || !pluginProcessToken) {
646 #if ENABLE(PDFKIT_PLUGIN)
647 String path = parameters.url.path();
648 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
649 RefPtr<PDFPlugin> pdfPlugin = PDFPlugin::create(frame);
650 return pdfPlugin.release();
657 if (isBlockedPlugin) {
658 bool replacementObscured = false;
659 if (pluginElement->renderer()->isEmbeddedObject()) {
660 RenderEmbeddedObject* renderObject = toRenderEmbeddedObject(pluginElement->renderer());
661 renderObject->setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
662 replacementObscured = renderObject->isReplacementObscured();
663 renderObject->setUnavailablePluginIndicatorIsHidden(replacementObscured);
666 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
670 if (!pluginProcessToken)
673 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
674 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
677 #endif // ENABLE(NETSCAPE_PLUGIN_API)
679 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
680 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
682 return WebGLAllowCreation;
685 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
687 return WebGLAllowCreation;
691 EditorState WebPage::editorState() const
693 Frame& frame = m_page->focusController().focusedOrMainFrame();
697 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
698 if (!pluginView->getSelectionString().isNull()) {
699 result.selectionIsNone = false;
700 result.selectionIsRange = true;
701 result.isInPlugin = true;
706 const VisibleSelection& selection = frame.selection().selection();
708 result.selectionIsNone = selection.isNone();
709 result.selectionIsRange = selection.isRange();
710 result.isContentEditable = selection.isContentEditable();
711 result.isContentRichlyEditable = selection.isContentRichlyEditable();
712 result.isInPasswordField = selection.isInPasswordField();
713 result.hasComposition = frame.editor().hasComposition();
714 result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange();
717 if (frame.editor().hasComposition()) {
718 RefPtr<Range> compositionRange = frame.editor().compositionRange();
719 Vector<WebCore::SelectionRect> compositionRects;
720 compositionRange->collectSelectionRects(compositionRects);
721 if (compositionRects.size())
722 result.firstMarkedRect = compositionRects[0].rect();
723 if (compositionRects.size() > 1)
724 result.lastMarkedRect = compositionRects.last().rect();
726 result.lastMarkedRect = result.firstMarkedRect;
727 result.markedText = plainTextReplacingNoBreakSpace(compositionRange.get());
729 FrameView* view = frame.view();
730 if (selection.isCaret()) {
731 result.caretRectAtStart = view->contentsToRootView(frame.selection().absoluteCaretBounds());
732 result.caretRectAtEnd = result.caretRectAtStart;
733 // FIXME: The following check should take into account writing direction.
734 result.isReplaceAllowed = result.isContentEditable && atBoundaryOfGranularity(selection.start(), WordGranularity, DirectionForward);
735 result.wordAtSelection = plainTextReplacingNoBreakSpace(wordRangeFromPosition(selection.start()).get());
736 if (selection.isContentEditable()) {
737 charactersAroundPosition(selection.start(), result.characterAfterSelection, result.characterBeforeSelection, result.twoCharacterBeforeSelection);
738 Node* root = selection.rootEditableElement();
739 result.hasContent = root && root->hasChildNodes() && !isEndOfEditableOrNonEditableContent(firstPositionInNode(root));
741 } else if (selection.isRange()) {
742 result.caretRectAtStart = view->contentsToRootView(VisiblePosition(selection.start()).absoluteCaretBounds());
743 result.caretRectAtEnd = view->contentsToRootView(VisiblePosition(selection.end()).absoluteCaretBounds());
744 RefPtr<Range> selectedRange = selection.toNormalizedRange();
745 selectedRange->collectSelectionRects(result.selectionRects);
746 convertSelectionRectsToRootView(view, result.selectionRects);
747 String selectedText = plainTextReplacingNoBreakSpace(selectedRange.get(), TextIteratorDefaultBehavior, true);
748 // FIXME: We should disallow replace when the string contains only CJ characters.
749 result.isReplaceAllowed = result.isContentEditable && !result.isInPasswordField && !selectedText.containsOnlyWhitespace();
750 result.selectedTextLength = selectedText.length();
751 const int maxSelectedTextLength = 200;
752 if (selectedText.length() <= maxSelectedTextLength)
753 result.wordAtSelection = selectedText;
755 if (!selection.isNone()) {
757 if (RenderStyle* style = Editor::styleForSelectionStart(&frame, nodeToRemove)) {
758 CTFontRef font = style->font().primaryFont()->getCTFont();
759 CTFontSymbolicTraits traits = font ? CTFontGetSymbolicTraits(font) : 0;
761 if (traits & kCTFontTraitBold)
762 result.typingAttributes |= AttributeBold;
763 if (traits & kCTFontTraitItalic)
764 result.typingAttributes |= AttributeItalics;
766 if (style->textDecorationsInEffect() & TextDecorationUnderline)
767 result.typingAttributes |= AttributeUnderline;
770 nodeToRemove->remove(ASSERT_NO_EXCEPTION);
776 result.cursorRect = frame.selection().absoluteCaretBounds();
782 String WebPage::renderTreeExternalRepresentation() const
784 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
787 String WebPage::renderTreeExternalRepresentationForPrinting() const
789 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
792 uint64_t WebPage::renderTreeSize() const
796 return m_page->renderTreeSize();
799 void WebPage::setTracksRepaints(bool trackRepaints)
801 if (FrameView* view = mainFrameView())
802 view->setTracksRepaints(trackRepaints);
805 bool WebPage::isTrackingRepaints() const
807 if (FrameView* view = mainFrameView())
808 return view->isTrackingRepaints();
813 void WebPage::resetTrackedRepaints()
815 if (FrameView* view = mainFrameView())
816 view->resetTrackedRepaints();
819 PassRefPtr<API::Array> WebPage::trackedRepaintRects()
821 FrameView* view = mainFrameView();
823 return API::Array::create();
825 Vector<RefPtr<API::Object>> repaintRects;
826 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
828 for (const auto& repaintRect : view->trackedRepaintRects())
829 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
831 return API::Array::create(WTF::move(repaintRects));
834 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
836 if (!frame.document()->isPluginDocument())
839 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
841 if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
844 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
848 PluginView* WebPage::pluginViewForFrame(Frame* frame)
850 if (!frame->document()->isPluginDocument())
853 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
854 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
858 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
860 Frame& frame = m_page->focusController().focusedOrMainFrame();
862 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
863 pluginView->handleEditingCommand(commandName, argument);
867 frame.editor().command(commandName).execute(argument);
870 bool WebPage::isEditingCommandEnabled(const String& commandName)
872 Frame& frame = m_page->focusController().focusedOrMainFrame();
874 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
875 return pluginView->isEditingCommandEnabled(commandName);
877 Editor::Command command = frame.editor().command(commandName);
878 return command.isSupported() && command.isEnabled();
881 void WebPage::clearMainFrameName()
883 if (Frame* frame = mainFrame())
884 frame->tree().clearName();
887 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
889 m_drawingArea->setRootCompositingLayer(layer);
892 void WebPage::exitAcceleratedCompositingMode()
894 m_drawingArea->setRootCompositingLayer(0);
897 void WebPage::close()
904 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
905 if (!mainWebFrame()->url().isEmpty())
906 reportUsedFeatures();
908 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
909 WebProcess::shared().injectedBundle()->willDestroyPage(this);
911 #if ENABLE(INSPECTOR)
914 #if ENABLE(FULLSCREEN_API)
915 m_fullScreenManager = 0;
918 if (m_activePopupMenu) {
919 m_activePopupMenu->disconnectFromPage();
920 m_activePopupMenu = 0;
923 if (m_activeOpenPanelResultListener) {
924 m_activeOpenPanelResultListener->disconnectFromPage();
925 m_activeOpenPanelResultListener = 0;
928 #if ENABLE(INPUT_TYPE_COLOR)
929 if (m_activeColorChooser) {
930 m_activeColorChooser->disconnectFromPage();
931 m_activeColorChooser = 0;
936 if (m_printOperation) {
937 m_printOperation->disconnectFromPage();
938 m_printOperation = nullptr;
942 m_sandboxExtensionTracker.invalidate();
944 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
945 m_determinePrimarySnapshottedPlugInTimer.stop();
948 #if ENABLE(CONTEXT_MENUS)
949 m_contextMenuClient.initialize(0);
951 m_editorClient.initialize(0);
952 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
953 m_loaderClient.initialize(0);
954 m_policyClient.initialize(0);
955 m_resourceLoadClient.initialize(0);
956 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
957 #if ENABLE(FULLSCREEN_API)
958 m_fullScreenClient.initialize(0);
960 m_logDiagnosticMessageClient.initialize(0);
962 m_printContext = nullptr;
963 m_mainFrame->coreFrame()->loader().detachFromParent();
965 m_drawingArea = nullptr;
967 bool isRunningModal = m_isRunningModal;
968 m_isRunningModal = false;
970 // The WebPage can be destroyed by this call.
971 WebProcess::shared().removeWebPage(m_pageID);
974 RunLoop::main().stop();
977 void WebPage::tryClose()
979 SendStopResponsivenessTimer stopper(this);
981 if (!corePage()->userInputBridge().tryClosePage()) {
982 send(Messages::WebPageProxy::StopResponsivenessTimer());
986 send(Messages::WebPageProxy::ClosePage(true));
989 void WebPage::sendClose()
991 send(Messages::WebPageProxy::ClosePage(false));
994 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
996 WebFrame* frame = WebProcess::shared().webFrame(frameID);
1000 frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url))));
1003 void WebPage::loadRequest(uint64_t navigationID, const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, IPC::MessageDecoder& decoder)
1005 SendStopResponsivenessTimer stopper(this);
1007 RefPtr<API::Object> userData;
1008 InjectedBundleUserMessageDecoder userMessageDecoder(userData);
1009 if (!decoder.decode(userMessageDecoder))
1012 m_pendingNavigationID = navigationID;
1014 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1016 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1017 // to all the client to set up any needed state.
1018 m_loaderClient.willLoadURLRequest(this, request, userData.get());
1020 // Initate the load in WebCore.
1021 corePage()->userInputBridge().loadRequest(FrameLoadRequest(m_mainFrame->coreFrame(), request));
1023 ASSERT(!m_pendingNavigationID);
1026 void WebPage::loadDataImpl(uint64_t navigationID, PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder)
1028 SendStopResponsivenessTimer stopper(this);
1030 RefPtr<API::Object> userData;
1031 InjectedBundleUserMessageDecoder userMessageDecoder(userData);
1032 if (!decoder.decode(userMessageDecoder))
1035 m_pendingNavigationID = navigationID;
1037 ResourceRequest request(baseURL);
1038 SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
1040 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1041 // to all the client to set up any needed state.
1042 m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), userData.get());
1044 // Initate the load in WebCore.
1045 m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, substituteData));
1048 void WebPage::loadString(uint64_t navigationID, const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder)
1050 if (!htmlString.isNull() && htmlString.is8Bit()) {
1051 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
1052 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, decoder);
1054 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
1055 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, decoder);
1059 void WebPage::loadData(const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, IPC::MessageDecoder& decoder)
1061 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
1062 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1063 loadDataImpl(0, sharedBuffer, MIMEType, encodingName, baseURL, URL(), decoder);
1066 void WebPage::loadHTMLString(uint64_t navigationID, const String& htmlString, const String& baseURLString, IPC::MessageDecoder& decoder)
1068 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1069 loadString(navigationID, htmlString, ASCIILiteral("text/html"), baseURL, URL(), decoder);
1072 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, IPC::MessageDecoder& decoder)
1074 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1075 URL unreachableURL = unreachableURLString.isEmpty() ? URL() : URL(URL(), unreachableURLString);
1076 loadString(0, htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, decoder);
1079 void WebPage::loadPlainTextString(const String& string, IPC::MessageDecoder& decoder)
1081 loadString(0, string, ASCIILiteral("text/plain"), blankURL(), URL(), decoder);
1084 void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, IPC::MessageDecoder& decoder)
1086 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
1087 loadDataImpl(0, sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), decoder);
1090 void WebPage::stopLoadingFrame(uint64_t frameID)
1092 WebFrame* frame = WebProcess::shared().webFrame(frameID);
1096 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1099 void WebPage::stopLoading()
1101 SendStopResponsivenessTimer stopper(this);
1103 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1106 bool WebPage::defersLoading() const
1108 return m_page->defersLoading();
1111 void WebPage::setDefersLoading(bool defersLoading)
1113 m_page->setDefersLoading(defersLoading);
1116 void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
1118 SendStopResponsivenessTimer stopper(this);
1120 ASSERT(!m_pendingNavigationID);
1121 m_pendingNavigationID = navigationID;
1123 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1124 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin);
1127 void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID)
1129 SendStopResponsivenessTimer stopper(this);
1131 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1136 ASSERT(!m_pendingNavigationID);
1137 if (!item->isInPageCache())
1138 m_pendingNavigationID = navigationID;
1140 m_page->goToItem(item, FrameLoadType::Forward);
1143 void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID)
1145 SendStopResponsivenessTimer stopper(this);
1147 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1152 ASSERT(!m_pendingNavigationID);
1153 if (!item->isInPageCache())
1154 m_pendingNavigationID = navigationID;
1156 m_page->goToItem(item, FrameLoadType::Back);
1159 void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID)
1161 SendStopResponsivenessTimer stopper(this);
1163 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1168 ASSERT(!m_pendingNavigationID);
1169 if (!item->isInPageCache())
1170 m_pendingNavigationID = navigationID;
1172 m_page->goToItem(item, FrameLoadType::IndexedBackForward);
1175 void WebPage::tryRestoreScrollPosition()
1177 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1180 void WebPage::layoutIfNeeded()
1182 if (m_mainFrame->coreFrame()->view())
1183 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1186 WebPage* WebPage::fromCorePage(Page* page)
1188 return static_cast<WebChromeClient&>(page->chrome().client()).page();
1191 void WebPage::setSize(const WebCore::IntSize& viewSize)
1193 if (m_viewSize == viewSize)
1196 FrameView* view = m_page->mainFrame().view();
1197 view->resize(viewSize);
1198 m_drawingArea->setNeedsDisplay();
1200 m_viewSize = viewSize;
1202 #if USE(TILED_BACKING_STORE)
1203 if (view->useFixedLayout())
1204 sendViewportAttributesChanged();
1207 m_pageOverlayController.didChangeViewSize();
1210 #if USE(TILED_BACKING_STORE)
1211 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1213 ASSERT(m_useFixedLayout);
1215 m_page->mainFrame().view()->setFixedVisibleContentRect(rect);
1218 void WebPage::sendViewportAttributesChanged()
1220 ASSERT(m_useFixedLayout);
1222 // Viewport properties have no impact on zero sized fixed viewports.
1223 if (m_viewSize.isEmpty())
1226 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1227 Settings& settings = m_page->settings();
1229 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1231 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1232 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1233 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1235 ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1237 FrameView* view = m_page->mainFrame().view();
1239 // If no layout was done yet set contentFixedOrigin to (0,0).
1240 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1242 // Put the width and height to the viewport width and height. In css units however.
1243 // Use FloatSize to avoid truncated values during scale.
1244 FloatSize contentFixedSize = m_viewSize;
1246 #if ENABLE(CSS_DEVICE_ADAPTATION)
1247 // CSS viewport descriptors might be applied to already affected viewport size
1248 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1249 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1252 contentFixedSize.scale(1 / attr.initialScale);
1253 setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1255 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1257 // This also takes care of the relayout.
1258 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1260 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1264 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1266 FrameView* frameView = m_page->mainFrame().view();
1268 IntPoint scrollPosition = frameView->scrollPosition();
1269 IntPoint maximumScrollPosition = frameView->maximumScrollPosition();
1271 // If the current scroll position in a direction is the max scroll position
1272 // we don't want to scroll at all.
1273 IntSize newScrollOffset;
1274 if (scrollPosition.x() < maximumScrollPosition.x())
1275 newScrollOffset.setWidth(scrollOffset.width());
1276 if (scrollPosition.y() < maximumScrollPosition.y())
1277 newScrollOffset.setHeight(scrollOffset.height());
1279 if (newScrollOffset.isZero())
1282 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1285 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1287 GraphicsContextStateSaver stateSaver(graphicsContext);
1288 graphicsContext.clip(rect);
1290 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1293 double WebPage::textZoomFactor() const
1295 Frame* frame = m_mainFrame->coreFrame();
1298 return frame->textZoomFactor();
1301 void WebPage::setTextZoomFactor(double zoomFactor)
1303 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1304 if (pluginView && pluginView->handlesPageScaleFactor())
1307 Frame* frame = m_mainFrame->coreFrame();
1310 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1313 double WebPage::pageZoomFactor() const
1315 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1316 if (pluginView && pluginView->handlesPageScaleFactor())
1317 return pluginView->pageScaleFactor();
1319 Frame* frame = m_mainFrame->coreFrame();
1322 return frame->pageZoomFactor();
1325 void WebPage::setPageZoomFactor(double zoomFactor)
1327 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1328 if (pluginView && pluginView->handlesPageScaleFactor()) {
1329 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1333 Frame* frame = m_mainFrame->coreFrame();
1336 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1339 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1341 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1342 if (pluginView && pluginView->handlesPageScaleFactor()) {
1343 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1347 Frame* frame = m_mainFrame->coreFrame();
1350 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1353 void WebPage::windowScreenDidChange(uint64_t displayID)
1355 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1358 void WebPage::scalePage(double scale, const IntPoint& origin)
1360 bool willChangeScaleFactor = scale != pageScaleFactor();
1363 if (willChangeScaleFactor) {
1364 if (!m_inDynamicSizeUpdate)
1365 m_dynamicSizeUpdateHistory.clear();
1366 m_scaleWasSetByUIProcess = false;
1369 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1370 if (pluginView && pluginView->handlesPageScaleFactor()) {
1371 pluginView->setPageScaleFactor(scale, origin);
1375 m_page->setPageScaleFactor(scale, origin);
1377 // We can't early return before setPageScaleFactor because the origin might be different.
1378 if (!willChangeScaleFactor)
1381 for (auto* pluginView : m_pluginViews)
1382 pluginView->pageScaleFactorDidChange();
1384 if (m_drawingArea->layerTreeHost())
1385 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1387 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1390 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1392 if (scale == pageScaleFactor())
1395 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1396 double scaleRatio = scale / pageScaleFactor();
1397 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1398 scalePage(scale, scrollPositionAtNewScale);
1401 double WebPage::pageScaleFactor() const
1403 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1404 if (pluginView && pluginView->handlesPageScaleFactor())
1405 return pluginView->pageScaleFactor();
1407 return m_page->pageScaleFactor();
1410 void WebPage::setDeviceScaleFactor(float scaleFactor)
1412 if (scaleFactor == m_page->deviceScaleFactor())
1415 m_page->setDeviceScaleFactor(scaleFactor);
1417 // Tell all our plug-in views that the device scale factor changed.
1419 for (auto* pluginView : m_pluginViews)
1420 pluginView->setDeviceScaleFactor(scaleFactor);
1422 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1425 if (m_findController.isShowingOverlay()) {
1426 // We must have updated layout to get the selection rects right.
1428 m_findController.deviceScaleFactorDidChange();
1431 if (m_drawingArea->layerTreeHost())
1432 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1434 m_pageOverlayController.didChangeDeviceScaleFactor();
1437 float WebPage::deviceScaleFactor() const
1439 return m_page->deviceScaleFactor();
1442 void WebPage::setUseFixedLayout(bool fixed)
1444 // Do not overwrite current settings if initially setting it to false.
1445 if (m_useFixedLayout == fixed)
1447 m_useFixedLayout = fixed;
1450 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1452 #if USE(COORDINATED_GRAPHICS)
1453 m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1454 m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1455 m_page->settings().setDelegatesPageScaling(fixed);
1456 m_page->settings().setScrollingCoordinatorEnabled(fixed);
1459 #if USE(TILED_BACKING_STORE) && ENABLE(SMOOTH_SCROLLING)
1460 // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1461 // Ensure we don't do animated scrolling in the WebProcess in that case.
1462 m_page->settings().setScrollAnimatorEnabled(!fixed);
1465 FrameView* view = mainFrameView();
1469 #if USE(TILED_BACKING_STORE)
1470 view->setDelegatesScrolling(fixed);
1471 view->setPaintsEntireContents(fixed);
1473 view->setUseFixedLayout(fixed);
1475 setFixedLayoutSize(IntSize());
1478 void WebPage::setFixedLayoutSize(const IntSize& size)
1480 FrameView* view = mainFrameView();
1481 if (!view || view->fixedLayoutSize() == size)
1484 view->setFixedLayoutSize(size);
1487 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1491 m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1494 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1496 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1499 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1501 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1504 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1506 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1509 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1511 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1512 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1515 void WebPage::setPaginationMode(uint32_t mode)
1517 Pagination pagination = m_page->pagination();
1518 pagination.mode = static_cast<Pagination::Mode>(mode);
1519 m_page->setPagination(pagination);
1522 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1524 Pagination pagination = m_page->pagination();
1525 pagination.behavesLikeColumns = behavesLikeColumns;
1526 m_page->setPagination(pagination);
1529 void WebPage::setPageLength(double pageLength)
1531 Pagination pagination = m_page->pagination();
1532 pagination.pageLength = pageLength;
1533 m_page->setPagination(pagination);
1536 void WebPage::setGapBetweenPages(double gap)
1538 Pagination pagination = m_page->pagination();
1539 pagination.gap = gap;
1540 m_page->setPagination(pagination);
1543 void WebPage::postInjectedBundleMessage(const String& messageName, IPC::MessageDecoder& decoder)
1545 InjectedBundle* injectedBundle = WebProcess::shared().injectedBundle();
1546 if (!injectedBundle)
1549 RefPtr<API::Object> messageBody;
1550 InjectedBundleUserMessageDecoder messageBodyDecoder(messageBody);
1551 if (!decoder.decode(messageBodyDecoder))
1554 injectedBundle->didReceiveMessageToPage(this, messageName, messageBody.get());
1557 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay, PageOverlay::FadeMode fadeMode)
1559 m_pageOverlayController.installPageOverlay(pageOverlay, fadeMode);
1562 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, PageOverlay::FadeMode fadeMode)
1564 m_pageOverlayController.uninstallPageOverlay(pageOverlay, fadeMode);
1568 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1571 m_headerBanner->detachFromPage();
1573 m_headerBanner = pageBanner;
1576 m_headerBanner->addToPage(PageBanner::Header, this);
1579 PageBanner* WebPage::headerPageBanner()
1581 return m_headerBanner.get();
1584 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1587 m_footerBanner->detachFromPage();
1589 m_footerBanner = pageBanner;
1592 m_footerBanner->addToPage(PageBanner::Footer, this);
1595 PageBanner* WebPage::footerPageBanner()
1597 return m_footerBanner.get();
1600 void WebPage::hidePageBanners()
1603 m_headerBanner->hide();
1605 m_footerBanner->hide();
1608 void WebPage::showPageBanners()
1611 m_headerBanner->showIfHidden();
1613 m_footerBanner->showIfHidden();
1615 #endif // !PLATFORM(IOS)
1617 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1619 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1620 snapshotOptions |= SnapshotOptionsShareable;
1622 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1624 ShareableBitmap::Handle handle;
1626 image->bitmap()->createHandle(handle, SharedMemory::ReadOnly);
1628 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1631 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1633 IntRect snapshotRect = rect;
1634 if (options & SnapshotOptionsRespectDrawingAreaTransform)
1635 snapshotRect = m_drawingArea->rootLayerTransform().inverse().mapRect(snapshotRect);
1637 IntSize bitmapSize = snapshotRect.size();
1638 double scaleFactor = additionalScaleFactor;
1639 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1640 scaleFactor *= corePage()->deviceScaleFactor();
1641 bitmapSize.scale(scaleFactor);
1643 return snapshotAtSize(rect, bitmapSize, options);
1646 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1648 Frame* coreFrame = m_mainFrame->coreFrame();
1652 FrameView* frameView = coreFrame->view();
1656 IntRect snapshotRect = rect;
1657 if (options & SnapshotOptionsRespectDrawingAreaTransform)
1658 snapshotRect = m_drawingArea->rootLayerTransform().inverse().mapRect(snapshotRect);
1660 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1661 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1662 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1664 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1665 if (!snapshot->bitmap())
1668 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1670 graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), frameView->baseBackgroundColor(), ColorSpaceDeviceRGB);
1672 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1673 double deviceScaleFactor = corePage()->deviceScaleFactor();
1674 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1675 scaleFactor /= deviceScaleFactor;
1678 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1679 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1681 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1682 if (options & SnapshotOptionsExcludeSelectionHighlighting)
1683 shouldPaintSelection = FrameView::ExcludeSelection;
1685 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1686 if (options & SnapshotOptionsInViewCoordinates)
1687 coordinateSpace = FrameView::ViewCoordinates;
1689 frameView->paintContentsForSnapshot(graphicsContext.get(), snapshotRect, shouldPaintSelection, coordinateSpace);
1691 if (options & SnapshotOptionsPaintSelectionRectangle) {
1692 FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1693 graphicsContext->setStrokeColor(Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
1694 graphicsContext->strokeRect(selectionRectangle, 1);
1697 return snapshot.release();
1700 PassRefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
1702 Frame* coreFrame = m_mainFrame->coreFrame();
1706 FrameView* frameView = coreFrame->view();
1710 if (!node.renderer())
1713 LayoutRect topLevelRect;
1714 IntRect snapshotRect = pixelSnappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
1716 double scaleFactor = 1;
1717 IntSize snapshotSize = snapshotRect.size();
1718 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
1719 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
1720 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
1721 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
1724 RefPtr<WebImage> snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options));
1725 if (!snapshot->bitmap())
1728 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1730 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1731 double deviceScaleFactor = corePage()->deviceScaleFactor();
1732 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1733 scaleFactor /= deviceScaleFactor;
1736 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1737 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1739 Color savedBackgroundColor = frameView->baseBackgroundColor();
1740 frameView->setBaseBackgroundColor(Color::transparent);
1741 frameView->setNodeToDraw(&node);
1743 frameView->paintContentsForSnapshot(graphicsContext.get(), snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
1745 frameView->setBaseBackgroundColor(savedBackgroundColor);
1746 frameView->setNodeToDraw(nullptr);
1748 return snapshot.release();
1751 void WebPage::pageDidScroll()
1754 if (!m_inDynamicSizeUpdate)
1755 m_dynamicSizeUpdateHistory.clear();
1757 m_uiClient->pageDidScroll(this);
1759 send(Messages::WebPageProxy::PageDidScroll());
1762 #if USE(TILED_BACKING_STORE)
1763 void WebPage::pageDidRequestScroll(const IntPoint& point)
1765 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1769 #if ENABLE(CONTEXT_MENUS)
1770 WebContextMenu* WebPage::contextMenu()
1773 m_contextMenu = WebContextMenu::create(this);
1774 return m_contextMenu.get();
1777 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1779 corePage()->contextMenuController().clearContextMenu();
1781 // Simulate a mouse click to generate the correct menu.
1782 PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime());
1783 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
1787 return contextMenu();
1793 static const WebEvent* g_currentEvent = 0;
1795 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1796 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1797 // platform events passed to the event handler code.
1798 const WebEvent* WebPage::currentEvent()
1800 return g_currentEvent;
1803 class CurrentEvent {
1805 explicit CurrentEvent(const WebEvent& event)
1806 : m_previousCurrentEvent(g_currentEvent)
1808 g_currentEvent = &event;
1813 g_currentEvent = m_previousCurrentEvent;
1817 const WebEvent* m_previousCurrentEvent;
1820 #if ENABLE(CONTEXT_MENUS)
1821 static bool isContextClick(const PlatformMouseEvent& event)
1823 if (event.button() == WebCore::RightButton)
1827 // FIXME: this really should be about OSX-style UI, not about the Mac port
1828 if (event.button() == WebCore::LeftButton && event.ctrlKey())
1835 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1837 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
1838 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
1840 Frame* frame = &page->corePage()->mainFrame();
1841 if (result.innerNonSharedNode())
1842 frame = result.innerNonSharedNode()->document().frame();
1844 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
1846 page->contextMenu()->show();
1852 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1854 Frame& frame = page->corePage()->mainFrame();
1858 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1860 switch (platformMouseEvent.type()) {
1861 case PlatformEvent::MousePressed: {
1862 #if ENABLE(CONTEXT_MENUS)
1863 if (isContextClick(platformMouseEvent))
1864 page->corePage()->contextMenuController().clearContextMenu();
1867 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
1868 #if ENABLE(CONTEXT_MENUS)
1869 if (isContextClick(platformMouseEvent))
1870 handled = handleContextMenuEvent(platformMouseEvent, page);
1874 case PlatformEvent::MouseReleased:
1875 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
1877 case PlatformEvent::MouseMoved:
1878 if (onlyUpdateScrollbars)
1879 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
1880 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
1882 ASSERT_NOT_REACHED();
1887 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1889 ASSERT(m_page->pageThrottler());
1890 m_page->pageThrottler()->didReceiveUserInput();
1892 #if ENABLE(CONTEXT_MENUS)
1893 // Don't try to handle any pending mouse events if a context menu is showing.
1894 if (m_isShowingContextMenu) {
1895 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1899 bool handled = m_pageOverlayController.handleMouseEvent(mouseEvent);
1902 if (!handled && m_headerBanner)
1903 handled = m_headerBanner->mouseEvent(mouseEvent);
1904 if (!handled && m_footerBanner)
1905 handled = m_footerBanner->mouseEvent(mouseEvent);
1906 #endif // !PLATFORM(IOS)
1908 if (!handled && canHandleUserEvents()) {
1909 CurrentEvent currentEvent(mouseEvent);
1911 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1912 // button is currently pressed. It is possible that neither of those things will be true since on
1913 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1914 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1915 // efficient scrollbars-only version of the event.
1916 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1917 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1920 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1923 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1925 handled = m_pageOverlayController.handleMouseEvent(mouseEvent);
1927 if (!handled && m_headerBanner)
1928 handled = m_headerBanner->mouseEvent(mouseEvent);
1929 if (!handled && m_footerBanner)
1930 handled = m_footerBanner->mouseEvent(mouseEvent);
1931 #endif // !PLATFORM(IOS)
1934 CurrentEvent currentEvent(mouseEvent);
1936 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1937 // button is currently pressed. It is possible that neither of those things will be true since on
1938 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1939 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1940 // efficient scrollbars-only version of the event.
1941 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1942 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1946 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1948 Frame& frame = page->mainFrame();
1952 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1953 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
1956 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1958 ASSERT(m_page->pageThrottler());
1959 m_page->pageThrottler()->didReceiveUserInput();
1961 bool handled = false;
1963 if (canHandleUserEvents()) {
1964 CurrentEvent currentEvent(wheelEvent);
1966 handled = handleWheelEvent(wheelEvent, m_page.get());
1968 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1971 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1973 CurrentEvent currentEvent(wheelEvent);
1975 if (ScrollingCoordinator* scrollingCoordinator = m_page->scrollingCoordinator())
1976 scrollingCoordinator->commitTreeStateIfNeeded();
1978 handled = handleWheelEvent(wheelEvent, m_page.get());
1981 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1983 if (!page->mainFrame().view())
1986 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1987 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
1988 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
1991 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1993 ASSERT(m_page->pageThrottler());
1994 m_page->pageThrottler()->didReceiveUserInput();
1996 bool handled = false;
1998 if (canHandleUserEvents()) {
1999 CurrentEvent currentEvent(keyboardEvent);
2001 handled = handleKeyEvent(keyboardEvent, m_page.get());
2002 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2004 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2006 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2009 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
2011 CurrentEvent currentEvent(keyboardEvent);
2013 Frame& frame = m_page->focusController().focusedOrMainFrame();
2014 frame.document()->updateStyleIfNeeded();
2016 handled = handleKeyEvent(keyboardEvent, m_page.get());
2018 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2021 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
2023 bool isEnabled = false;
2025 Frame& frame = m_page->focusController().focusedOrMainFrame();
2026 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2027 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2029 Editor::Command command = frame.editor().command(commandName);
2030 state = command.state();
2031 isEnabled = command.isSupported() && command.isEnabled();
2034 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2037 void WebPage::executeEditCommand(const String& commandName)
2039 executeEditingCommand(commandName, String());
2042 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2044 for (const auto& itemState : itemStates)
2045 WebBackForwardListProxy::addItemFromUIProcess(itemState.identifier, toHistoryItem(itemState.pageState), m_pageID);
2048 #if ENABLE(TOUCH_EVENTS)
2049 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2051 if (!page->mainFrame().view())
2054 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2058 #if ENABLE(IOS_TOUCH_EVENTS)
2059 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2061 RefPtr<Frame> oldFocusedFrame = m_page->focusController().focusedFrame();
2062 RefPtr<Element> oldFocusedElement = oldFocusedFrame ? oldFocusedFrame->document()->focusedElement() : nullptr;
2063 m_userIsInteracting = true;
2065 m_lastInteractionLocation = touchEvent.position();
2066 CurrentEvent currentEvent(touchEvent);
2067 handled = handleTouchEvent(touchEvent, m_page.get());
2069 RefPtr<Frame> newFocusedFrame = m_page->focusController().focusedFrame();
2070 RefPtr<Element> newFocusedElement = newFocusedFrame ? newFocusedFrame->document()->focusedElement() : nullptr;
2072 // If the focus has not changed, we need to notify the client anyway, since it might be
2073 // necessary to start assisting the node.
2074 // If the node has been focused by JavaScript without user interaction, the
2075 // keyboard is not on screen.
2076 if (newFocusedElement && newFocusedElement == oldFocusedElement)
2077 elementDidFocus(newFocusedElement.get());
2079 m_userIsInteracting = false;
2082 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2084 EventDispatcher::TouchEventQueue queuedEvents;
2085 WebProcess::shared().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2086 dispatchAsynchronousTouchEvents(queuedEvents);
2088 dispatchTouchEvent(touchEvent, handled);
2090 #elif ENABLE(TOUCH_EVENTS)
2091 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2094 bool handled = false;
2095 if (canHandleUserEvents()) {
2096 CurrentEvent currentEvent(touchEvent);
2098 handled = handleTouchEvent(touchEvent, m_page.get());
2100 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2103 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
2105 CurrentEvent currentEvent(touchEvent);
2106 handled = handleTouchEvent(touchEvent, m_page.get());
2110 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2112 return page->userInputBridge().scrollRecursively(direction, granularity);
2115 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2117 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2120 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2122 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2125 void WebPage::centerSelectionInVisibleArea()
2127 Frame& frame = m_page->focusController().focusedOrMainFrame();
2128 frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
2129 m_findController.showFindIndicatorInSelection();
2132 #if ENABLE(REMOTE_INSPECTOR)
2133 void WebPage::setAllowsRemoteInspection(bool allow)
2135 m_page->setRemoteInspectionAllowed(allow);
2139 void WebPage::setDrawsBackground(bool drawsBackground)
2141 if (m_drawsBackground == drawsBackground)
2144 m_drawsBackground = drawsBackground;
2146 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2147 if (FrameView* view = coreFrame->view())
2148 view->setTransparent(!drawsBackground);
2151 m_drawingArea->pageBackgroundTransparencyChanged();
2152 m_drawingArea->setNeedsDisplay();
2155 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
2157 if (m_drawsTransparentBackground == drawsTransparentBackground)
2160 m_drawsTransparentBackground = drawsTransparentBackground;
2162 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2163 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2164 if (FrameView* view = coreFrame->view())
2165 view->setBaseBackgroundColor(backgroundColor);
2168 m_drawingArea->pageBackgroundTransparencyChanged();
2169 m_drawingArea->setNeedsDisplay();
2172 void WebPage::setTopContentInset(float contentInset)
2174 if (contentInset == m_page->topContentInset())
2177 m_page->setTopContentInset(contentInset);
2179 for (auto* pluginView : m_pluginViews)
2180 pluginView->topContentInsetDidChange();
2183 void WebPage::viewWillStartLiveResize()
2188 // FIXME: This should propagate to all ScrollableAreas.
2189 Frame& frame = m_page->focusController().focusedOrMainFrame();
2190 if (FrameView* view = frame.view())
2191 view->willStartLiveResize();
2194 void WebPage::viewWillEndLiveResize()
2199 // FIXME: This should propagate to all ScrollableAreas.
2200 Frame& frame = m_page->focusController().focusedOrMainFrame();
2201 if (FrameView* view = frame.view())
2202 view->willEndLiveResize();
2205 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
2210 Frame& frame = m_page->focusController().focusedOrMainFrame();
2211 frame.document()->setFocusedElement(0);
2213 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2214 PlatformKeyboardEvent platformEvent(platform(event));
2215 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2216 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2220 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2223 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
2225 if (m_windowResizerSize == windowResizerSize)
2228 m_windowResizerSize = windowResizerSize;
2230 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2231 FrameView* view = coreFrame->view();
2233 view->windowResizerRectChanged();
2237 void WebPage::setCanStartMediaTimerFired()
2240 m_page->setCanStartMedia(true);
2243 inline bool WebPage::canHandleUserEvents() const
2245 #if USE(TILED_BACKING_STORE)
2246 // Should apply only if the area was frozen by didStartPageTransition().
2247 return !m_drawingArea->layerTreeStateIsFrozen();
2252 void WebPage::updateIsInWindow(bool isInitialState)
2254 bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2257 m_setCanStartMediaTimer.stop();
2258 m_page->setCanStartMedia(false);
2260 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2261 if (!isInitialState)
2262 WebProcess::shared().pageWillLeaveWindow(m_pageID);
2264 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2265 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2266 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2267 if (m_mayStartMediaWhenInWindow)
2268 m_setCanStartMediaTimer.startOneShot(0);
2270 WebProcess::shared().pageDidEnterWindow(m_pageID);
2277 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState)
2279 ViewState::Flags changed = m_viewState ^ viewState;
2280 m_viewState = viewState;
2282 m_page->setViewState(viewState);
2283 for (auto* pluginView : m_pluginViews)
2284 pluginView->viewStateDidChange(changed);
2286 m_drawingArea->viewStateDidChange(changed, wantsDidUpdateViewState);
2288 if (changed & ViewState::IsInWindow)
2292 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2294 m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2296 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2298 for (auto* pluginView : m_pluginViews)
2299 pluginView->setLayerHostingMode(m_layerHostingMode);
2302 void WebPage::setSessionID(SessionID sessionID)
2304 if (sessionID.isEphemeral())
2305 WebProcess::shared().ensurePrivateBrowsingSession(sessionID);
2306 m_page->setSessionID(sessionID);
2309 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, uint64_t downloadID)
2311 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2314 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID);
2317 void WebPage::didStartPageTransition()
2319 m_drawingArea->setLayerTreeStateIsFrozen(true);
2322 void WebPage::didCompletePageTransition()
2324 #if USE(TILED_BACKING_STORE)
2325 // m_mainFrame can be null since r170163.
2326 if (m_mainFrame && m_mainFrame->coreFrame()->view()->delegatesScrolling()) {
2327 // Wait until the UI process sent us the visible rect it wants rendered.
2328 send(Messages::WebPageProxy::PageTransitionViewportReady());
2332 m_drawingArea->setLayerTreeStateIsFrozen(false);
2335 void WebPage::show()
2337 send(Messages::WebPageProxy::ShowPage());
2340 String WebPage::userAgent(const URL& webCoreURL) const
2342 return userAgent(nullptr, webCoreURL);
2345 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2347 if (frame && m_loaderClient.client().userAgentForURL) {
2348 RefPtr<API::URL> url = API::URL::create(webcoreURL);
2350 API::String* apiString = m_loaderClient.userAgentForURL(frame, url.get());
2352 return apiString->string();
2355 String userAgent = platformUserAgent(webcoreURL);
2356 if (!userAgent.isEmpty())
2361 void WebPage::setUserAgent(const String& userAgent)
2363 m_userAgent = userAgent;
2366 void WebPage::suspendActiveDOMObjectsAndAnimations()
2368 m_page->suspendActiveDOMObjectsAndAnimations();
2371 void WebPage::resumeActiveDOMObjectsAndAnimations()
2373 m_page->resumeActiveDOMObjectsAndAnimations();
2376 IntPoint WebPage::screenToRootView(const IntPoint& point)
2378 IntPoint windowPoint;
2379 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2383 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2386 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2391 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2393 IntPoint windowPoint;
2394 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2398 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2401 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2406 IntRect WebPage::windowResizerRect() const
2408 if (m_windowResizerSize.isEmpty())
2411 IntSize frameViewSize;
2412 if (Frame* coreFrame = m_mainFrame->coreFrame()) {
2413 if (FrameView* view = coreFrame->view())
2414 frameViewSize = view->size();
2417 return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(),
2418 m_windowResizerSize.width(), m_windowResizerSize.height());
2421 KeyboardUIMode WebPage::keyboardUIMode()
2423 bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
2424 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2427 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2429 // NOTE: We need to be careful when running scripts that the objects we depend on don't
2430 // disappear during script execution.
2432 // Retain the SerializedScriptValue at this level so it (and the internal data) lives
2433 // long enough for the DataReference to be encoded by the sent message.
2434 RefPtr<SerializedScriptValue> serializedResultValue;
2435 IPC::DataReference dataReference;
2437 JSLockHolder lock(JSDOMWindow::commonVM());
2438 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) {
2439 if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
2440 dataReference = serializedResultValue->data();
2443 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2446 void WebPage::getContentsAsString(uint64_t callbackID)
2448 String resultString = m_mainFrame->contentsAsString();
2449 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2453 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2455 IPC::DataReference dataReference;
2457 RefPtr<SharedBuffer> buffer = useBinaryEncoding
2458 ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2459 : MHTMLArchive::generateMHTMLData(m_page.get());
2462 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2464 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2468 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2470 String resultString = renderTreeExternalRepresentation();
2471 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2474 static Frame* frameWithSelection(Page* page)
2476 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2477 if (frame->selection().isRange())
2484 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2486 IPC::DataReference dataReference;
2489 RefPtr<LegacyWebArchive> archive;
2490 RetainPtr<CFDataRef> data;
2492 Frame* frame = frameWithSelection(m_page.get());
2494 archive = LegacyWebArchive::createFromSelection(frame);
2495 data = archive->rawDataRepresentation();
2496 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2500 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2503 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2505 String resultString = m_mainFrame->selectionAsString();
2506 if (resultString.isEmpty())
2507 resultString = m_mainFrame->contentsAsString();
2508 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2511 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2513 String resultString;
2514 if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
2515 resultString = frame->source();
2517 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2520 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2522 IPC::DataReference dataReference;
2524 RefPtr<ResourceBuffer> buffer;
2525 RefPtr<SharedBuffer> pdfResource;
2526 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2527 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame())) {
2528 if ((pdfResource = pluginView->liveResourceData()))
2529 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(pdfResource->data()), pdfResource->size());
2532 if (dataReference.isEmpty()) {
2533 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader()) {
2534 if ((buffer = loader->mainResourceData()))
2535 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2540 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2543 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2545 DocumentLoader* loader = frame->loader().documentLoader();
2549 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2553 return subresource->data();
2556 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2558 IPC::DataReference dataReference;
2559 URL resourceURL(URL(), resourceURLString);
2561 RefPtr<SharedBuffer> buffer;
2562 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2563 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2565 // Try to get the resource data from the cache.
2566 buffer = cachedResponseDataForURL(resourceURL);
2570 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2573 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2576 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2578 IPC::DataReference dataReference;
2581 RetainPtr<CFDataRef> data;
2582 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2583 if ((data = frame->webArchiveData(0, 0)))
2584 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2587 UNUSED_PARAM(frameID);
2590 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2593 void WebPage::forceRepaintWithoutCallback()
2595 m_drawingArea->forceRepaint();
2598 void WebPage::forceRepaint(uint64_t callbackID)
2600 if (m_drawingArea->forceRepaintAsync(callbackID))
2603 forceRepaintWithoutCallback();
2604 send(Messages::WebPageProxy::VoidCallback(callbackID));
2607 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2609 WebPreferencesStore::removeTestRunnerOverrides();
2610 updatePreferences(store);
2613 void WebPage::updatePreferences(const WebPreferencesStore& store)
2615 Settings& settings = m_page->settings();
2617 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2618 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2619 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2620 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2622 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2625 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2628 #if ENABLE(SERVICE_CONTROLS)
2629 m_serviceControlsEnabled = store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey());
2632 // FIXME: This should be generated from macro expansion for all preferences,
2633 // but we currently don't match the naming of WebCore exactly so we are
2634 // handrolling the boolean and integer preferences until that is fixed.
2636 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2638 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2640 #undef INITIALIZE_SETTINGS
2642 settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2643 settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2644 settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2645 settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2646 settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2647 settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2648 settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));
2649 settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2650 settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2651 settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2652 settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2653 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
2654 setSessionID(SessionID::legacyPrivateSessionID());
2655 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
2656 setSessionID(SessionID::defaultSessionID());
2657 settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2658 settings.setJavaScriptExperimentsEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptExperimentsEnabledKey()));
2659 settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2660 settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2661 settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2662 settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2663 settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2664 #if ENABLE(WEB_ARCHIVE)
2665 settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2667 settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2668 settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2669 settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2670 settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2671 settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2672 settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2673 settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2674 settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2675 settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2676 settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2677 settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2679 settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2680 settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2681 settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2682 settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2683 settings.setScreenFontSubstitutionEnabled(store.getBoolValueForKey(WebPreferencesKey::screenFontSubstitutionEnabledKey())
2685 || WebProcess::shared().shouldForceScreenFontSubstitution()
2688 settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2689 settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2690 settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2691 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2692 settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2694 settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2695 settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
2696 settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
2697 settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
2698 settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2699 settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2700 settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2701 settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2702 settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
2703 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2704 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2705 settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2706 settings.setMultithreadedWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::multithreadedWebGLEnabledKey()));
2707 settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2708 settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2709 settings.setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
2710 settings.setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
2711 settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2712 settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2713 settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2714 #if ENABLE(SMOOTH_SCROLLING)
2715 settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2717 settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
2718 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2719 settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2721 #if ENABLE(SQL_DATABASE)
2722 DatabaseManager::manager().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2725 #if ENABLE(FULLSCREEN_API)
2726 settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2729 #if USE(AVFOUNDATION)
2730 settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2734 settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2738 settings.setAVKitEnabled(true);
2741 #if ENABLE(IOS_TEXT_AUTOSIZING)
2742 settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2745 #if ENABLE(WEB_AUDIO)
2746 settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2749 #if ENABLE(MEDIA_STREAM)
2750 settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2753 #if ENABLE(SERVICE_CONTROLS)
2754 settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2757 #if ENABLE(IOS_AIRPLAY)
2758 settings.setMediaPlaybackAllowsAirPlay(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsAirPlayKey()));
2761 settings.setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2762 settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2763 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2764 settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2765 settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2766 settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2768 #if ENABLE(VIDEO_TRACK)
2769 settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2770 settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2771 settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2774 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2775 settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2778 settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2779 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2780 settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2782 settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2784 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2786 settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2787 settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2788 settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2789 settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2790 settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2792 #if ENABLE(TEXT_AUTOSIZING)
2793 settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2796 settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2797 settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2799 settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2800 settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2801 settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2803 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2804 settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2807 settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2808 settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2809 settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2810 settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2812 settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
2814 settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2816 #if ENABLE(MEDIA_SOURCE)
2817 settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2820 settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2822 settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2823 settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2824 settings.setAlwaysUseBaselineOfPrimaryFont(store.getBoolValueForKey(WebPreferencesKey::alwaysUseBaselineOfPrimaryFontKey()));
2825 settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2826 settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2828 settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2829 settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2831 settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2832 settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2834 settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2836 settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
2839 settings.setUseImageDocumentForSubframePDF(true);
2843 RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
2846 if (store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey()))
2847 m_processSuppressionDisabledByWebPreference.stop();
2849 m_processSuppressionDisabledByWebPreference.start();
2851 platformPreferencesDidChange(store);
2854 m_drawingArea->updatePreferences(store);
2856 m_pageOverlayController.didChangePreferences();
2860 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2862 layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2863 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2864 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2865 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2867 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2868 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
2869 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
2870 layerTransaction.setAllowsUserScaling(allowsUserScaling());
2874 void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp)
2877 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) {
2878 std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
2879 m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero();
2881 m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20));
2884 UNUSED_PARAM(timestamp);
2890 #if ENABLE(INSPECTOR)
2891 WebInspector* WebPage::inspector()
2896 m_inspector = WebInspector::create(this, m_inspectorClient);
2897 return m_inspector.get();
2902 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
2904 if (!m_videoFullscreenManager)
2905 m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
2906 return m_videoFullscreenManager.get();
2910 #if ENABLE(FULLSCREEN_API)
2911 WebFullScreenManager* WebPage::fullScreenManager()
2913 if (!m_fullScreenManager)
2914 m_fullScreenManager = WebFullScreenManager::create(this);
2915 return m_fullScreenManager.get();
2919 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2921 if (m_notificationPermissionRequestManager)
2922 return m_notificationPermissionRequestManager.get();
2924 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2925 return m_notificationPermissionRequestManager.get();
2928 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
2929 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2931 Node* node = evt->target()->toNode();
2933 Frame* frame = node->document().frame();
2936 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2940 Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
2942 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2943 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2944 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2945 // (e.g. Tab that inserts a Tab character, or Enter).
2946 return !command.isTextInsertion() && command.execute(evt);
2949 if (command.execute(evt))
2952 // Don't allow text insertion for nodes that cannot edit.
2953 if (!frame->editor().canEdit())
2956 // Don't insert null or control characters as they can result in unexpected behaviour
2957 if (evt->charCode() < ' ')
2960 return frame->editor().insertText(evt->keyEvent()->text(), evt);
2964 #if ENABLE(DRAG_SUPPORT)
2967 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2970 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
2971 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2977 case DragControllerActionEntered: {
2978 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
2979 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
2982 case DragControllerActionUpdated: {
2983 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
2984 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
2987 case DragControllerActionExited:
2988 m_page->dragController().dragExited(dragData);
2991 case DragControllerActionPerformDragOperation: {
2992 m_page->dragController().performDragOperation(dragData);
2997 ASSERT_NOT_REACHED();
2999 // DragData does not delete its platformData so we need to do that here.
3000 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3005 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)
3008 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3012 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3014 case DragControllerActionEntered: {
3015 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3016 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3020 case DragControllerActionUpdated: {
3021 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3022 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3025 case DragControllerActionExited:
3026 m_page->dragController().dragExited(dragData);
3029 case DragControllerActionPerformDragOperation: {
3030 ASSERT(!m_pendingDropSandboxExtension);
3032 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
3033 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3034 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
3035 m_pendingDropExtensionsForFileUpload.append(extension);
3038 m_page->dragController().performDragOperation(dragData);
3040 // If we started loading a local file, the sandbox extension tracker would have adopted this
3041 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3042 m_pendingDropSandboxExtension = nullptr;
3044 m_pendingDropExtensionsForFileUpload.clear();
3049 ASSERT_NOT_REACHED();
3054 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3056 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3057 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3059 m_page->dragController().dragEnded();
3060 FrameView* view = m_page->mainFrame().view();
3063 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3064 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
3065 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3068 void WebPage::willPerformLoadDragDestinationAction()
3070 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
3073 void WebPage::mayPerformUploadDragDestinationAction()
3075 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3076 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3077 m_pendingDropExtensionsForFileUpload.clear();
3080 #endif // ENABLE(DRAG_SUPPORT)
3082 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3084 return m_undoStepMap.get(stepID);
3087 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3089 m_undoStepMap.set(stepID, entry);
3092 void WebPage::removeWebEditCommand(uint64_t stepID)
3094 m_undoStepMap.remove(stepID);
3097 void WebPage::unapplyEditCommand(uint64_t stepID)
3099 WebUndoStep* step = webUndoStep(stepID);
3103 step->step()->unapply();
3106 void WebPage::reapplyEditCommand(uint64_t stepID)
3108 WebUndoStep* step = webUndoStep(stepID);
3113 step->step()->reapply();
3117 void WebPage::didRemoveEditCommand(uint64_t commandID)
3119 removeWebEditCommand(commandID);
3122 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3124 m_activePopupMenu = menu;
3127 #if ENABLE(INPUT_TYPE_COLOR)
3128 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3130 m_activeColorChooser = colorChooser;
3133 void WebPage::didEndColorPicker()
3135 m_activeColorChooser->didEndChooser();
3138 void WebPage::didChooseColor(const WebCore::Color& color)
3140 m_activeColorChooser->didChooseColor(color);
3144 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
3146 m_activeOpenPanelResultListener = openPanelResultListener;
3149 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3151 return m_page->findString(target, options);
3154 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3156 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
3159 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3161 m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3164 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3166 m_findController.getImageForFindMatch(matchIndex);
3169 void WebPage::selectFindMatch(uint32_t matchIndex)
3171 m_findController.selectFindMatch(matchIndex);
3174 void WebPage::hideFindUI()
3176 m_findController.hideFindUI();
3179 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3181 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3184 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3186 changeSelectedIndex(newIndex);
3187 m_activePopupMenu = 0;
3190 void WebPage::changeSelectedIndex(int32_t index)
3192 if (!m_activePopupMenu)
3195 m_activePopupMenu->didChangeSelectedIndex(index);
3199 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3201 if (!m_activeOpenPanelResultListener)
3205 if (!iconData.isEmpty()) {
3206 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3207 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3208 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3209 icon = Icon::createIconForImage(imageRef.get());
3212 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3213 m_activeOpenPanelResultListener = nullptr;
3217 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3219 if (!m_activeOpenPanelResultListener)
3222 m_activeOpenPanelResultListener->didChooseFiles(files);
3223 m_activeOpenPanelResultListener = 0;
3226 void WebPage::didCancelForOpenPanel()
3228 m_activeOpenPanelResultListener = 0;
3231 #if ENABLE(SANDBOX_EXTENSIONS)
3232 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3234 SandboxExtension::create(handle)->consumePermanently();
3238 #if ENABLE(GEOLOCATION)
3239 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3241 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3245 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3247 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3251 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3253 Frame& frame = m_page->focusController().focusedOrMainFrame();
3254 frame.editor().advanceToNextMisspelling(startBeforeSelection);
3258 void WebPage::changeSpellingToWord(const String& word)
3260 replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3263 void WebPage::unmarkAllMisspellings()
3265 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3266 if (Document* document = frame->document())
3267 document->markers().removeMarkers(DocumentMarker::Spelling);
3271 void WebPage::unmarkAllBadGrammar()
3273 for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3274 if (Document* document = frame->document())
3275 document->markers().removeMarkers(DocumentMarker::Grammar);
3280 void WebPage::uppercaseWord()
3282 m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3285 void WebPage::lowercaseWord()
3287 m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3290 void WebPage::capitalizeWord()
3292 m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3296 void WebPage::setTextForActivePopupMenu(int32_t index)
3298 if (!m_activePopupMenu)
3301 m_activePopupMenu->setTextForIndex(index);
3305 void WebPage::failedToShowPopupMenu()
3307 if (!m_activePopupMenu)
3310 m_activePopupMenu->client()->popupDidHide();
3314 #if ENABLE(CONTEXT_MENUS)
3315 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3320 m_contextMenu->itemSelected(item);
3325 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3327 bool selectReplacement = true;
3328 bool smartReplace = false;
3329 return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3333 void WebPage::clearSelection()
3335 m_page->focusController().focusedOrMainFrame().selection().clear();
3339 bool WebPage::mainFrameHasCustomContentProvider() const
3341 if (Frame* frame = mainFrame()) {
3342 WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3343 ASSERT(webFrameLoaderClient);
3344 return webFrameLoaderClient->frameHasCustomContentProvider();
3350 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3352 m_mimeTypesWithCustomContentProviders.add(mimeType);
3355 void WebPage::updateMainFrameScrollOffsetPinning()
3357 Frame& frame = m_page->mainFrame();
3358 IntPoint scrollPosition = frame.view()->scrollPosition();
3359 IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3360 IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3362 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3363 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3364 bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3365 bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3367 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3368 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3370 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3371 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3372 m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3373 m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3377 void WebPage::mainFrameDidLayout()
3379 unsigned pageCount = m_page->pageCount();
3380 if (pageCount != m_cachedPageCount) {
3381 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3382 m_cachedPageCount = pageCount;
3385 #if USE(TILED_BACKING_STORE)
3386 if (m_drawingArea && m_drawingArea->layerTreeHost()) {
3387 double red, green, blue, alpha;
3388 m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha);
3389 RGBA32 rgba = makeRGBA32FromFloats(red, green, blue, alpha);
3390 if (m_backgroundColor.rgb() != rgba) {
3391 m_backgroundColor.setRGB(rgba);
3392 m_drawingArea->layerTreeHost()->setBackgroundColor(m_backgroundColor);
3398 m_viewGestureGeometryCollector.mainFrameDidLayout();
3401 if (FrameView* frameView = mainFrameView()) {
3402 IntSize newContentSize = frameView->contentsSize();
3403 if (m_viewportConfiguration.contentsSize() != newContentSize) {
3404 m_viewportConfiguration.setContentsSize(newContentSize);
3405 viewportConfigurationChanged();
3411 void WebPage::addPluginView(PluginView* pluginView)
3413 ASSERT(!m_pluginViews.contains(pluginView));
3415 m_pluginViews.add(pluginView);
3416 m_hasSeenPlugin = true;
3417 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3418 LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3419 m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3423 void WebPage::removePluginView(PluginView* pluginView)
3425 ASSERT(m_pluginViews.contains(pluginView));
3427 m_pluginViews.remove(pluginView);
3428 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3429 LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3433 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3436 m_hasCachedWindowFrame = false;
3438 send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3442 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3444 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3445 m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3446 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3447 m_accessibilityPosition = accessibilityViewCoordinates;
3449 // Tell all our plug-in views that the window and view frames have changed.
3450 for (auto* pluginView : m_pluginViews)
3451 pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3453 m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3457 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3459 m_mainFrameIsScrollable = isScrollable;
3460 m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3462 if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3463 frameView->setCanHaveScrollbars(isScrollable);
3464 frameView->setProhibitsScrolling(!isScrollable);
3468 bool WebPage::windowIsFocused() const
3470 return m_page->focusController().isActive();
3473 bool WebPage::windowAndWebPageAreFocused() const
3478 return m_page->focusController().isFocused() && m_page->focusController().isActive();
3481 void WebPage::didReceiveMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder)
3483 if (decoder.messageReceiverName() == Messages::DrawingArea::messageReceiverName()) {
3485 m_drawingArea->didReceiveDrawingAreaMessage(connection, decoder);
3489 #if USE(TILED_BACKING_STORE)
3490 if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
3492 m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
3497 #if ENABLE(INSPECTOR)
3498 if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
3499 if (WebInspector* inspector = this->inspector())
3500 inspector->didReceiveWebInspectorMessage(connection, decoder);
3505 #if ENABLE(FULLSCREEN_API)
3506 if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
3507 fullScreenManager()->didReceiveMessage(connection, decoder);
3512 didReceiveWebPageMessage(connection, decoder);
3515 void WebPage::didReceiveSyncMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder)
3517 didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
3520 InjectedBundleBackForwardList* WebPage::backForwardList()
3522 if (!m_backForwardList)
3523 m_backForwardList = InjectedBundleBackForwardList::create(this);
3524 return m_backForwardList.get();
3527 #if ENABLE(ASYNC_SCROLLING)
3528 ScrollingCoordinator* WebPage::scrollingCoordinator() const
3530 return m_page->scrollingCoordinator();
3534 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3539 void WebPage::SandboxExtensionTracker::invalidate()