2 * Copyright (C) 2010, 2011, 2012, 2013-2015 Apple Inc. All rights reserved.
3 * Copyright (C) 2012 Intel Corporation. All rights reserved.
4 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
19 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
25 * THE POSSIBILITY OF SUCH DAMAGE.
32 #include "APIGeometry.h"
33 #include "Arguments.h"
34 #include "DataReference.h"
35 #include "DragControllerAction.h"
36 #include "DrawingArea.h"
37 #include "DrawingAreaMessages.h"
38 #include "EditorState.h"
39 #include "EventDispatcher.h"
40 #include "InjectedBundle.h"
41 #include "InjectedBundleBackForwardList.h"
42 #include "InjectedBundleScriptWorld.h"
44 #include "NetscapePlugin.h"
45 #include "NotificationPermissionRequestManager.h"
46 #include "PageBanner.h"
47 #include "PluginProcessAttributes.h"
48 #include "PluginProxy.h"
49 #include "PluginView.h"
50 #include "PrintInfo.h"
51 #include "SessionState.h"
52 #include "SessionStateConversion.h"
53 #include "SessionTracker.h"
54 #include "ShareableBitmap.h"
55 #include "VisitedLinkTableController.h"
56 #include "WKBundleAPICast.h"
57 #include "WKRetainPtr.h"
58 #include "WKSharedAPICast.h"
59 #include "WebAlternativeTextClient.h"
60 #include "WebBackForwardListItem.h"
61 #include "WebBackForwardListProxy.h"
62 #include "WebChromeClient.h"
63 #include "WebColorChooser.h"
64 #include "WebContextMenu.h"
65 #include "WebContextMenuClient.h"
66 #include "WebCoreArgumentCoders.h"
67 #include "WebDatabaseProvider.h"
68 #include "WebDiagnosticLoggingClient.h"
69 #include "WebDocumentLoader.h"
70 #include "WebDragClient.h"
71 #include "WebEditorClient.h"
73 #include "WebEventConversion.h"
74 #include "WebEventFactory.h"
76 #include "WebFrameLoaderClient.h"
77 #include "WebFullScreenManager.h"
78 #include "WebFullScreenManagerMessages.h"
79 #include "WebGeolocationClient.h"
81 #include "WebInspector.h"
82 #include "WebInspectorClient.h"
83 #include "WebInspectorMessages.h"
84 #include "WebInspectorUI.h"
85 #include "WebInspectorUIMessages.h"
86 #include "WebMediaKeyStorageManager.h"
87 #include "WebNotificationClient.h"
88 #include "WebOpenPanelResultListener.h"
89 #include "WebPageCreationParameters.h"
90 #include "WebPageGroupProxy.h"
91 #include "WebPageMessages.h"
92 #include "WebPageOverlay.h"
93 #include "WebPageProxyMessages.h"
94 #include "WebPlugInClient.h"
95 #include "WebPopupMenu.h"
96 #include "WebPreferencesDefinitions.h"
97 #include "WebPreferencesKeys.h"
98 #include "WebPreferencesStore.h"
99 #include "WebProcess.h"
100 #include "WebProcessPoolMessages.h"
101 #include "WebProcessProxyMessages.h"
102 #include "WebProgressTrackerClient.h"
103 #include "WebStorageNamespaceProvider.h"
104 #include "WebUndoStep.h"
105 #include "WebUserContentController.h"
106 #include "WebUserMediaClient.h"
107 #include <JavaScriptCore/APICast.h>
108 #include <WebCore/ArchiveResource.h>
109 #include <WebCore/Chrome.h>
110 #include <WebCore/ContextMenuController.h>
111 #include <WebCore/DataTransfer.h>
112 #include <WebCore/DatabaseManager.h>
113 #include <WebCore/DocumentFragment.h>
114 #include <WebCore/DocumentLoader.h>
115 #include <WebCore/DocumentMarkerController.h>
116 #include <WebCore/DragController.h>
117 #include <WebCore/DragData.h>
118 #include <WebCore/ElementIterator.h>
119 #include <WebCore/EventHandler.h>
120 #include <WebCore/FocusController.h>
121 #include <WebCore/FormState.h>
122 #include <WebCore/FrameLoadRequest.h>
123 #include <WebCore/FrameLoaderTypes.h>
124 #include <WebCore/FrameView.h>
125 #include <WebCore/HTMLFormElement.h>
126 #include <WebCore/HTMLInputElement.h>
127 #include <WebCore/HTMLPlugInElement.h>
128 #include <WebCore/HTMLPlugInImageElement.h>
129 #include <WebCore/HistoryController.h>
130 #include <WebCore/HistoryItem.h>
131 #include <WebCore/HitTestResult.h>
132 #include <WebCore/JSDOMWindow.h>
133 #include <WebCore/KeyboardEvent.h>
134 #include <WebCore/MIMETypeRegistry.h>
135 #include <WebCore/MainFrame.h>
136 #include <WebCore/MouseEvent.h>
137 #include <WebCore/Page.h>
138 #include <WebCore/PageConfiguration.h>
139 #include <WebCore/PageThrottler.h>
140 #include <WebCore/PlatformKeyboardEvent.h>
141 #include <WebCore/PluginDocument.h>
142 #include <WebCore/PrintContext.h>
143 #include <WebCore/Range.h>
144 #include <WebCore/RenderLayer.h>
145 #include <WebCore/RenderTreeAsText.h>
146 #include <WebCore/RenderView.h>
147 #include <WebCore/ResourceRequest.h>
148 #include <WebCore/ResourceResponse.h>
149 #include <WebCore/RuntimeEnabledFeatures.h>
150 #include <WebCore/SchemeRegistry.h>
151 #include <WebCore/ScriptController.h>
152 #include <WebCore/SerializedScriptValue.h>
153 #include <WebCore/SessionID.h>
154 #include <WebCore/Settings.h>
155 #include <WebCore/ShadowRoot.h>
156 #include <WebCore/SharedBuffer.h>
157 #include <WebCore/StyleProperties.h>
158 #include <WebCore/SubframeLoader.h>
159 #include <WebCore/SubstituteData.h>
160 #include <WebCore/TextIterator.h>
161 #include <WebCore/UserInputBridge.h>
162 #include <WebCore/UserScript.h>
163 #include <WebCore/UserStyleSheet.h>
164 #include <WebCore/VisiblePosition.h>
165 #include <WebCore/VisibleUnits.h>
166 #include <WebCore/markup.h>
167 #include <bindings/ScriptValue.h>
168 #include <profiler/ProfilerDatabase.h>
169 #include <runtime/JSCInlines.h>
170 #include <runtime/JSCJSValue.h>
171 #include <runtime/JSLock.h>
172 #include <wtf/RunLoop.h>
173 #include <wtf/TemporaryChange.h>
175 #if ENABLE(DATA_DETECTION)
176 #include "DataDetectionResult.h"
180 #include <WebCore/MHTMLArchive.h>
183 #if ENABLE(BATTERY_STATUS)
184 #include "WebBatteryClient.h"
187 #if ENABLE(VIBRATION)
188 #include "WebVibrationClient.h"
191 #if ENABLE(PROXIMITY_EVENTS)
192 #include "WebDeviceProximityClient.h"
196 #include "PDFPlugin.h"
197 #include "RemoteLayerTreeTransaction.h"
198 #include "WKStringCF.h"
199 #include "WebVideoFullscreenManager.h"
200 #include <WebCore/LegacyWebArchive.h>
205 #include "DataObjectGtk.h"
206 #include "WebPrintOperationGtk.h"
210 #include "RemoteLayerTreeDrawingArea.h"
211 #include <CoreGraphics/CoreGraphics.h>
212 #include <WebCore/CoreTextSPI.h>
213 #include <WebCore/Icon.h>
217 #include <wtf/RefCountedLeakCounter.h>
220 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
221 #include "LayerTreeHost.h"
224 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
225 #include "CoordinatedLayerTreeHostMessages.h"
228 #if ENABLE(DATA_DETECTION)
229 #include <WebCore/DataDetection.h>
232 #if ENABLE(VIDEO) && USE(GSTREAMER)
233 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
236 #if USE(APPLE_INTERNAL_SDK)
237 #include <WebKitAdditions/WebPageIncludes.h>
241 using namespace WebCore;
245 static const double pageScrollHysteresisSeconds = 0.3;
247 class SendStopResponsivenessTimer {
249 SendStopResponsivenessTimer(WebPage* page)
254 ~SendStopResponsivenessTimer()
256 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
263 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
265 Ref<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
267 Ref<WebPage> page = adoptRef(*new WebPage(pageID, parameters));
269 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
270 WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
275 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
277 , m_viewSize(parameters.viewSize)
278 , m_hasSeenPlugin(false)
279 , m_useFixedLayout(false)
280 , m_drawsBackground(true)
283 , m_tabToLinks(false)
284 , m_asynchronousPluginInitializationEnabled(false)
285 , m_asynchronousPluginInitializationEnabledForAllPlugins(false)
286 , m_artificialPluginInitializationDelayEnabled(false)
287 , m_scrollingPerformanceLoggingEnabled(false)
288 , m_mainFrameIsScrollable(true)
289 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
290 , m_readyToFindPrimarySnapshottedPlugin(false)
291 , m_didFindPrimarySnapshottedPlugin(false)
292 , m_numberOfPrimarySnapshotDetectionAttempts(0)
293 , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
295 , m_layerHostingMode(parameters.layerHostingMode)
297 , m_pdfPluginEnabled(false)
298 , m_hasCachedWindowFrame(false)
299 , m_viewGestureGeometryCollector(*this)
300 #elif HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL))
301 , m_accessibilityObject(nullptr)
303 , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
304 #if ENABLE(CONTEXT_MENUS)
305 , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
307 , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
308 , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
309 , m_findController(this)
310 #if ENABLE(INPUT_TYPE_COLOR)
311 , m_activeColorChooser(0)
313 , m_userContentController(WebUserContentController::getOrCreate(parameters.userContentControllerID))
314 #if ENABLE(GEOLOCATION)
315 , m_geolocationPermissionRequestManager(this)
317 #if ENABLE(MEDIA_STREAM)
318 , m_userMediaPermissionRequestManager(*this)
320 , m_pageScrolledHysteresis([this](HysteresisState state) { if (state == HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisSeconds)
321 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
322 , m_canRunModal(parameters.canRunModal)
323 , m_isRunningModal(false)
324 #if ENABLE(DRAG_SUPPORT)
325 , m_isStartingDrag(false)
327 , m_cachedMainFrameIsPinnedToLeftSide(true)
328 , m_cachedMainFrameIsPinnedToRightSide(true)
329 , m_cachedMainFrameIsPinnedToTopSide(true)
330 , m_cachedMainFrameIsPinnedToBottomSide(true)
331 , m_canShortCircuitHorizontalWheelEvents(false)
332 , m_hasWheelEventHandlers(false)
333 , m_cachedPageCount(0)
334 , m_autoSizingShouldExpandToViewHeight(false)
335 #if ENABLE(CONTEXT_MENUS)
336 , m_isShowingContextMenu(false)
339 , m_selectionAnchor(Start)
340 , m_hasReceivedVisibleContentRectsAfterDidCommitLoad(false)
341 , m_scaleWasSetByUIProcess(false)
342 , m_userHasChangedPageScaleFactor(false)
343 , m_hasStablePageScaleFactor(true)
344 , m_userIsInteracting(false)
345 , m_hasPendingBlurNotification(false)
346 , m_useTestingViewportConfiguration(false)
347 , m_isInStableState(true)
348 , m_oldestNonStableUpdateVisibleContentRectsTimestamp(std::chrono::milliseconds::zero())
349 , m_estimatedLatency(std::chrono::milliseconds::zero())
350 , m_screenSize(parameters.screenSize)
351 , m_availableScreenSize(parameters.availableScreenSize)
352 , m_deviceOrientation(0)
353 , m_inDynamicSizeUpdate(false)
354 , m_volatilityTimer(*this, &WebPage::volatilityTimerFired)
356 , m_backgroundColor(Color::white)
357 , m_maximumRenderingSuppressionToken(0)
358 , m_scrollPinningBehavior(DoNotPin)
359 , m_useAsyncScrolling(false)
360 , m_viewState(parameters.viewState)
361 , m_processSuppressionEnabled(true)
362 , m_userActivity("Process suppression disabled for page.")
363 , m_pendingNavigationID(0)
365 , m_systemWebGLPolicy(WebGLAllowCreation)
367 , m_mainFrameProgressCompleted(false)
368 , m_shouldDispatchFakeMouseMoveEvents(true)
369 , m_mediaShouldUsePersistentCache(parameters.mediaShouldUsePersistentCache)
373 m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
376 Settings::setShouldManageAudioSessionCategory(true);
379 PageConfiguration pageConfiguration;
380 pageConfiguration.chromeClient = new WebChromeClient(this);
381 #if ENABLE(CONTEXT_MENUS)
382 pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
384 pageConfiguration.editorClient = new WebEditorClient(this);
385 #if ENABLE(DRAG_SUPPORT)
386 pageConfiguration.dragClient = new WebDragClient(this);
388 pageConfiguration.backForwardClient = WebBackForwardListProxy::create(this);
389 pageConfiguration.inspectorClient = new WebInspectorClient(this);
390 #if USE(AUTOCORRECTION_PANEL)
391 pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
394 pageConfiguration.plugInClient = new WebPlugInClient(*this);
395 pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
396 pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
397 pageConfiguration.diagnosticLoggingClient = new WebDiagnosticLoggingClient(*this);
399 pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
400 pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
401 pageConfiguration.userContentProvider = m_userContentController.ptr();
402 pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
404 #if USE(APPLE_INTERNAL_SDK)
405 #include <WebKitAdditions/WebPageInitialization.h>
408 m_page = std::make_unique<Page>(pageConfiguration);
409 updatePreferences(parameters.store);
411 m_drawingArea = DrawingArea::create(*this, parameters);
412 m_drawingArea->setPaintingEnabled(false);
413 m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
415 #if ENABLE(ASYNC_SCROLLING)
416 m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
417 if (!m_drawingArea->supportsAsyncScrolling())
418 m_useAsyncScrolling = false;
419 m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
422 m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
423 m_drawingArea->updatePreferences(parameters.store);
425 #if ENABLE(BATTERY_STATUS)
426 WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
428 #if ENABLE(GEOLOCATION)
429 WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
431 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
432 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
434 #if ENABLE(VIBRATION)
435 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
437 #if ENABLE(PROXIMITY_EVENTS)
438 WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this));
440 #if ENABLE(MEDIA_STREAM)
441 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
444 m_page->setControlledByAutomation(parameters.controlledByAutomation);
446 #if ENABLE(REMOTE_INSPECTOR)
447 m_page->setRemoteInspectionAllowed(parameters.allowsRemoteInspection);
448 m_page->setRemoteInspectionNameOverride(parameters.remoteInspectionNameOverride);
451 m_page->setCanStartMedia(false);
452 m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
454 m_page->setGroupName(m_pageGroup->identifier());
455 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
457 m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
460 platformInitialize();
462 setUseFixedLayout(parameters.useFixedLayout);
464 setDrawsBackground(parameters.drawsBackground);
466 setUnderlayColor(parameters.underlayColor);
468 setPaginationMode(parameters.paginationMode);
469 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
470 setPageLength(parameters.pageLength);
471 setGapBetweenPages(parameters.gapBetweenPages);
472 setPaginationLineGridEnabled(parameters.paginationLineGridEnabled);
474 // If the page is created off-screen, its visibilityState should be prerender.
475 m_page->setViewState(m_viewState);
477 m_page->setIsPrerender();
478 updateUserActivity();
480 updateIsInWindow(true);
482 setMinimumLayoutSize(parameters.minimumLayoutSize);
483 setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
485 setScrollPinningBehavior(parameters.scrollPinningBehavior);
486 if (parameters.scrollbarOverlayStyle)
487 m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
489 m_scrollbarOverlayStyle = WTF::Optional<ScrollbarOverlayStyle>();
491 setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
493 setTopContentInset(parameters.topContentInset);
495 m_userAgent = parameters.userAgent;
497 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
499 if (!parameters.itemStates.isEmpty())
500 restoreSessionInternal(parameters.itemStates, WasRestoredByAPIRequest::No);
502 if (parameters.sessionID.isValid())
503 setSessionID(parameters.sessionID);
505 m_drawingArea->setPaintingEnabled(true);
507 setMediaVolume(parameters.mediaVolume);
509 setMuted(parameters.muted);
511 // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
512 m_page->addLayoutMilestones(DidFirstLayout | DidFirstVisuallyNonEmptyLayout);
514 auto& webProcess = WebProcess::singleton();
515 webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
517 // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
518 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
519 webProcess.addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this);
521 webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
522 webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
523 #if ENABLE(FULLSCREEN_API)
524 webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
528 webPageCounter.increment();
531 #if ENABLE(ASYNC_SCROLLING)
532 if (m_useAsyncScrolling)
533 webProcess.eventDispatcher().addScrollingTreeForPage(this);
536 for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
537 m_mimeTypesWithCustomContentProviders.add(mimeType);
540 #if ENABLE(ENCRYPTED_MEDIA_V2)
541 if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
542 m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
544 m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
546 if (parameters.viewScaleFactor != 1)
547 scaleView(parameters.viewScaleFactor);
550 m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
554 void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters)
556 if (m_viewState != parameters.viewState)
557 setViewState(parameters.viewState, false, Vector<uint64_t>());
558 if (m_layerHostingMode != parameters.layerHostingMode)
559 setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode));
562 void WebPage::setPageActivityState(PageActivityState::Flags activityState)
564 PageActivityState::Flags changed = m_activityState ^ activityState;
565 m_activityState = activityState;
568 updateUserActivity();
571 void WebPage::updateUserActivity()
573 // Start the activity to prevent AppNap if the page activity is in progress,
574 // the page is visible and non-idle, or process suppression is disabled.
575 if (m_activityState || !(m_viewState & ViewState::IsVisuallyIdle) || !m_processSuppressionEnabled)
576 m_userActivity.start();
578 m_userActivity.stop();
583 if (m_backForwardList)
584 m_backForwardList->detach();
588 auto& webProcess = WebProcess::singleton();
589 #if ENABLE(ASYNC_SCROLLING)
590 if (m_useAsyncScrolling)
591 webProcess.eventDispatcher().removeScrollingTreeForPage(this);
596 m_sandboxExtensionTracker.invalidate();
598 for (auto* pluginView : m_pluginViews)
599 pluginView->webPageDestroyed();
603 m_headerBanner->detachFromPage();
605 m_footerBanner->detachFromPage();
606 #endif // !PLATFORM(IOS)
608 webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
610 // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
611 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
612 webProcess.removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID);
614 webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
615 webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
616 #if ENABLE(FULLSCREEN_API)
617 webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
621 webPageCounter.decrement();
625 void WebPage::dummy(bool&)
629 IPC::Connection* WebPage::messageSenderConnection()
631 return WebProcess::singleton().parentProcessConnection();
634 uint64_t WebPage::messageSenderDestinationID()
639 #if ENABLE(CONTEXT_MENUS)
640 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient> contextMenuClient)
642 if (!contextMenuClient) {
643 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
647 m_contextMenuClient = WTFMove(contextMenuClient);
651 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* client)
653 m_editorClient.initialize(client);
656 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient> formClient)
659 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
663 m_formClient = WTFMove(formClient);
666 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client)
668 m_loaderClient.initialize(client);
670 // It would be nice to get rid of this code and transition all clients to using didLayout instead of
671 // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
672 // for backwards compatibility.
673 LayoutMilestones milestones = 0;
675 if (m_loaderClient.client().didFirstLayoutForFrame)
676 milestones |= WebCore::DidFirstLayout;
677 if (m_loaderClient.client().didFirstVisuallyNonEmptyLayoutForFrame)
678 milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
682 listenForLayoutMilestones(milestones);
685 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
687 m_policyClient.initialize(client);
690 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase* client)
692 m_resourceLoadClient.initialize(client);
695 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient> uiClient)
698 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
702 m_uiClient = WTFMove(uiClient);
705 #if ENABLE(FULLSCREEN_API)
706 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
708 m_fullScreenClient.initialize(client);
712 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase* client)
714 m_logDiagnosticMessageClient.initialize(client);
717 #if ENABLE(NETSCAPE_PLUGIN_API)
718 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
720 String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
721 String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
723 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
724 HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
725 unsigned pluginArea = 0;
726 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
728 PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
731 bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
733 uint64_t pluginProcessToken;
734 uint32_t pluginLoadPolicy;
735 String unavailabilityDescription;
736 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)))
739 PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
740 bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
742 if (isBlockedPlugin || !pluginProcessToken) {
743 #if ENABLE(PDFKIT_PLUGIN)
744 String path = parameters.url.path();
745 if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
746 RefPtr<PDFPlugin> pdfPlugin = PDFPlugin::create(frame);
747 return pdfPlugin.release();
754 if (isBlockedPlugin) {
755 bool replacementObscured = false;
756 if (is<RenderEmbeddedObject>(*pluginElement->renderer())) {
757 auto& renderObject = downcast<RenderEmbeddedObject>(*pluginElement->renderer());
758 renderObject.setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
759 replacementObscured = renderObject.isReplacementObscured();
760 renderObject.setUnavailablePluginIndicatorIsHidden(replacementObscured);
763 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
767 if (!pluginProcessToken)
770 bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
771 return PluginProxy::create(pluginProcessToken, isRestartedProcess);
774 #endif // ENABLE(NETSCAPE_PLUGIN_API)
776 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
777 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
779 return WebGLAllowCreation;
782 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
784 return WebGLAllowCreation;
788 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
790 Frame& frame = m_page->focusController().focusedOrMainFrame();
794 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
795 if (!pluginView->getSelectionString().isNull()) {
796 result.selectionIsNone = false;
797 result.selectionIsRange = true;
798 result.isInPlugin = true;
803 const VisibleSelection& selection = frame.selection().selection();
805 result.selectionIsNone = selection.isNone();
806 result.selectionIsRange = selection.isRange();
807 result.isContentEditable = selection.isContentEditable();
808 result.isContentRichlyEditable = selection.isContentRichlyEditable();
809 result.isInPasswordField = selection.isInPasswordField();
810 result.hasComposition = frame.editor().hasComposition();
811 result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange();
814 if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && result.isContentEditable) {
815 auto& postLayoutData = result.postLayoutData();
816 if (!selection.isNone()) {
818 if (RenderStyle* style = Editor::styleForSelectionStart(&frame, nodeToRemove)) {
819 if (style->fontCascade().weight() >= FontWeightBold)
820 postLayoutData.typingAttributes |= AttributeBold;
821 if (style->fontCascade().italic() == FontItalicOn)
822 postLayoutData.typingAttributes |= AttributeItalics;
824 RefPtr<EditingStyle> typingStyle = frame.selection().typingStyle();
825 if (typingStyle && typingStyle->style()) {
826 String value = typingStyle->style()->getPropertyValue(CSSPropertyWebkitTextDecorationsInEffect);
827 if (value.contains("underline"))
828 postLayoutData.typingAttributes |= AttributeUnderline;
830 if (style->textDecorationsInEffect() & TextDecorationUnderline)
831 postLayoutData.typingAttributes |= AttributeUnderline;
834 if (style->visitedDependentColor(CSSPropertyColor).isValid())
835 postLayoutData.textColor = style->visitedDependentColor(CSSPropertyColor);
837 switch (style->textAlign()) {
840 postLayoutData.textAlignment = RightAlignment;
844 postLayoutData.textAlignment = LeftAlignment;
848 postLayoutData.textAlignment = CenterAlignment;
851 postLayoutData.textAlignment = JustifiedAlignment;
854 postLayoutData.textAlignment = style->isLeftToRightDirection() ? LeftAlignment : RightAlignment;
857 postLayoutData.textAlignment = style->isLeftToRightDirection() ? RightAlignment : LeftAlignment;
862 nodeToRemove->remove(ASSERT_NO_EXCEPTION);
868 platformEditorState(frame, result, shouldIncludePostLayoutData);
873 String WebPage::renderTreeExternalRepresentation() const
875 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
878 String WebPage::renderTreeExternalRepresentationForPrinting() const
880 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
883 uint64_t WebPage::renderTreeSize() const
887 return m_page->renderTreeSize();
890 void WebPage::setTracksRepaints(bool trackRepaints)
892 if (FrameView* view = mainFrameView())
893 view->setTracksRepaints(trackRepaints);
896 bool WebPage::isTrackingRepaints() const
898 if (FrameView* view = mainFrameView())
899 return view->isTrackingRepaints();
904 void WebPage::resetTrackedRepaints()
906 if (FrameView* view = mainFrameView())
907 view->resetTrackedRepaints();
910 Ref<API::Array> WebPage::trackedRepaintRects()
912 FrameView* view = mainFrameView();
914 return API::Array::create();
916 Vector<RefPtr<API::Object>> repaintRects;
917 repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
919 for (const auto& repaintRect : view->trackedRepaintRects())
920 repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
922 return API::Array::create(WTFMove(repaintRects));
925 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
927 if (!frame.document()->isPluginDocument())
930 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
932 if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
935 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
939 PluginView* WebPage::pluginViewForFrame(Frame* frame)
941 if (!frame->document()->isPluginDocument())
944 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
945 PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
949 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
951 Frame& frame = m_page->focusController().focusedOrMainFrame();
953 if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
954 pluginView->handleEditingCommand(commandName, argument);
958 frame.editor().command(commandName).execute(argument);
961 void WebPage::setEditable(bool editable)
963 m_page->setEditable(editable);
964 m_page->setTabKeyCyclesThroughElements(!editable);
965 Frame& frame = m_page->focusController().focusedOrMainFrame();
967 frame.editor().applyEditingStyleToBodyElement();
968 // If the page is made editable and the selection is empty, set it to something.
969 if (frame.selection().isNone())
970 frame.selection().setSelectionFromNone();
974 bool WebPage::isEditingCommandEnabled(const String& commandName)
976 Frame& frame = m_page->focusController().focusedOrMainFrame();
978 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
979 return pluginView->isEditingCommandEnabled(commandName);
981 Editor::Command command = frame.editor().command(commandName);
982 return command.isSupported() && command.isEnabled();
985 void WebPage::clearMainFrameName()
987 if (Frame* frame = mainFrame())
988 frame->tree().clearName();
991 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
993 m_drawingArea->setRootCompositingLayer(layer);
996 void WebPage::exitAcceleratedCompositingMode()
998 m_drawingArea->setRootCompositingLayer(0);
1001 void WebPage::close()
1008 // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1009 if (!mainWebFrame()->url().isEmpty())
1010 reportUsedFeatures();
1012 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle())
1013 WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1016 m_inspector->disconnectFromPage();
1017 m_inspector = nullptr;
1020 #if ENABLE(FULLSCREEN_API)
1021 m_fullScreenManager = nullptr;
1024 if (m_activePopupMenu) {
1025 m_activePopupMenu->disconnectFromPage();
1026 m_activePopupMenu = nullptr;
1029 if (m_activeOpenPanelResultListener) {
1030 m_activeOpenPanelResultListener->disconnectFromPage();
1031 m_activeOpenPanelResultListener = nullptr;
1034 #if ENABLE(INPUT_TYPE_COLOR)
1035 if (m_activeColorChooser) {
1036 m_activeColorChooser->disconnectFromPage();
1037 m_activeColorChooser = nullptr;
1042 if (m_printOperation) {
1043 m_printOperation->disconnectFromPage();
1044 m_printOperation = nullptr;
1048 #if ENABLE(VIDEO) && USE(GSTREAMER)
1049 if (m_installMediaPluginsCallback) {
1050 m_installMediaPluginsCallback->invalidate();
1051 m_installMediaPluginsCallback = nullptr;
1055 m_sandboxExtensionTracker.invalidate();
1057 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1058 m_determinePrimarySnapshottedPlugInTimer.stop();
1061 #if ENABLE(CONTEXT_MENUS)
1062 m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1064 m_editorClient.initialize(0);
1065 m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1066 m_loaderClient.initialize(0);
1067 m_policyClient.initialize(0);
1068 m_resourceLoadClient.initialize(0);
1069 m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1070 #if ENABLE(FULLSCREEN_API)
1071 m_fullScreenClient.initialize(0);
1073 m_logDiagnosticMessageClient.initialize(0);
1075 m_printContext = nullptr;
1076 m_mainFrame->coreFrame()->loader().detachFromParent();
1078 m_drawingArea = nullptr;
1080 bool isRunningModal = m_isRunningModal;
1081 m_isRunningModal = false;
1083 // The WebPage can be destroyed by this call.
1084 WebProcess::singleton().removeWebPage(m_pageID);
1086 WebProcess::singleton().updateActivePages();
1089 RunLoop::main().stop();
1092 void WebPage::tryClose()
1094 SendStopResponsivenessTimer stopper(this);
1096 if (!corePage()->userInputBridge().tryClosePage()) {
1097 send(Messages::WebPageProxy::StopResponsivenessTimer());
1101 send(Messages::WebPageProxy::ClosePage(true));
1104 void WebPage::sendClose()
1106 send(Messages::WebPageProxy::ClosePage(false));
1109 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
1111 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1115 frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url)), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1118 void WebPage::loadRequest(uint64_t navigationID, const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, uint64_t shouldOpenExternalURLsPolicy, const UserData& userData)
1120 SendStopResponsivenessTimer stopper(this);
1122 m_pendingNavigationID = navigationID;
1124 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1126 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1127 // to all the client to set up any needed state.
1128 m_loaderClient.willLoadURLRequest(this, request, WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1130 // Initate the load in WebCore.
1131 FrameLoadRequest frameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1132 ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(shouldOpenExternalURLsPolicy);
1133 frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1135 corePage()->userInputBridge().loadRequest(frameLoadRequest);
1137 ASSERT(!m_pendingNavigationID);
1140 void WebPage::loadDataImpl(uint64_t navigationID, PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1142 SendStopResponsivenessTimer stopper(this);
1144 m_pendingNavigationID = navigationID;
1146 ResourceRequest request(baseURL);
1147 ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1148 SubstituteData substituteData(sharedBuffer, unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1150 // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1151 // to all the client to set up any needed state.
1152 m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1154 // Initate the load in WebCore.
1155 m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData));
1158 void WebPage::loadString(uint64_t navigationID, const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1160 if (!htmlString.isNull() && htmlString.is8Bit()) {
1161 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
1162 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, userData);
1164 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
1165 loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, userData);
1169 void WebPage::loadData(uint64_t navigationID, const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, const UserData& userData)
1171 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
1172 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1173 loadDataImpl(navigationID, sharedBuffer, MIMEType, encodingName, baseURL, URL(), userData);
1176 void WebPage::loadHTMLString(uint64_t navigationID, const String& htmlString, const String& baseURLString, const UserData& userData)
1178 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1179 loadString(navigationID, htmlString, ASCIILiteral("text/html"), baseURL, URL(), userData);
1182 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, const String& provisionalLoadErrorURLString, const UserData& userData)
1184 URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
1185 URL unreachableURL = unreachableURLString.isEmpty() ? URL() : URL(URL(), unreachableURLString);
1186 URL provisionalLoadErrorURL = provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), provisionalLoadErrorURLString);
1187 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);
1188 loadString(0, htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, userData);
1189 m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1192 void WebPage::loadPlainTextString(const String& string, const UserData& userData)
1194 loadString(0, string, ASCIILiteral("text/plain"), blankURL(), URL(), userData);
1197 void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, const UserData& userData)
1199 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
1200 loadDataImpl(0, sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), userData);
1203 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1205 Frame* mainFrame = m_mainFrame->coreFrame();
1206 Document* mainFrameDocument = mainFrame->document();
1207 if (!mainFrameDocument)
1210 const int singleClick = 1;
1211 RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, true, true, currentTime(), nullptr, singleClick, screenPoint.x(), screenPoint.y(), documentPoint.x(), documentPoint.y(),
1212 #if ENABLE(POINTER_LOCK)
1215 false, false, false, false, 0, nullptr, 0, nullptr);
1217 mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1220 void WebPage::stopLoadingFrame(uint64_t frameID)
1222 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1226 corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1229 void WebPage::stopLoading()
1231 SendStopResponsivenessTimer stopper(this);
1233 corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1236 bool WebPage::defersLoading() const
1238 return m_page->defersLoading();
1241 void WebPage::setDefersLoading(bool defersLoading)
1243 m_page->setDefersLoading(defersLoading);
1246 void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, bool contentBlockersEnabled, const SandboxExtension::Handle& sandboxExtensionHandle)
1248 SendStopResponsivenessTimer stopper(this);
1250 ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1251 m_pendingNavigationID = navigationID;
1253 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1254 corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin, contentBlockersEnabled);
1257 void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID)
1259 SendStopResponsivenessTimer stopper(this);
1261 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1266 ASSERT(!m_pendingNavigationID);
1267 m_pendingNavigationID = navigationID;
1269 m_page->goToItem(*item, FrameLoadType::Forward);
1272 void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID)
1274 SendStopResponsivenessTimer stopper(this);
1276 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1281 ASSERT(!m_pendingNavigationID);
1282 m_pendingNavigationID = navigationID;
1284 m_page->goToItem(*item, FrameLoadType::Back);
1287 void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID)
1289 SendStopResponsivenessTimer stopper(this);
1291 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1296 ASSERT(!m_pendingNavigationID);
1297 m_pendingNavigationID = navigationID;
1299 m_page->goToItem(*item, FrameLoadType::IndexedBackForward);
1302 void WebPage::tryRestoreScrollPosition()
1304 m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1307 void WebPage::layoutIfNeeded()
1309 if (m_mainFrame->coreFrame()->view())
1310 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1313 WebPage* WebPage::fromCorePage(Page* page)
1315 return static_cast<WebChromeClient&>(page->chrome().client()).page();
1318 void WebPage::setSize(const WebCore::IntSize& viewSize)
1320 if (m_viewSize == viewSize)
1323 FrameView* view = m_page->mainFrame().view();
1324 view->resize(viewSize);
1325 m_drawingArea->setNeedsDisplay();
1327 m_viewSize = viewSize;
1329 #if USE(COORDINATED_GRAPHICS)
1330 if (view->useFixedLayout())
1331 sendViewportAttributesChanged();
1335 #if USE(COORDINATED_GRAPHICS)
1336 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1338 ASSERT(m_useFixedLayout);
1340 m_page->mainFrame().view()->setFixedVisibleContentRect(rect);
1343 void WebPage::sendViewportAttributesChanged()
1345 ASSERT(m_useFixedLayout);
1347 // Viewport properties have no impact on zero sized fixed viewports.
1348 if (m_viewSize.isEmpty())
1351 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1352 Settings& settings = m_page->settings();
1354 int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1356 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1357 int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1358 int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1360 ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1362 FrameView* view = m_page->mainFrame().view();
1364 // If no layout was done yet set contentFixedOrigin to (0,0).
1365 IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1367 // Put the width and height to the viewport width and height. In css units however.
1368 // Use FloatSize to avoid truncated values during scale.
1369 FloatSize contentFixedSize = m_viewSize;
1371 #if ENABLE(CSS_DEVICE_ADAPTATION)
1372 // CSS viewport descriptors might be applied to already affected viewport size
1373 // if the page enables/disables stylesheets, so need to keep initial viewport size.
1374 view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1377 contentFixedSize.scale(1 / attr.initialScale);
1378 setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1380 attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1382 // This also takes care of the relayout.
1383 setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1385 #if USE(COORDINATED_GRAPHICS_THREADED)
1386 if (m_drawingArea->layerTreeHost())
1387 m_drawingArea->layerTreeHost()->didChangeViewportProperties(attr);
1389 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1394 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1396 FrameView* frameView = m_page->mainFrame().view();
1398 ScrollPosition scrollPosition = frameView->scrollPosition();
1399 ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1401 // If the current scroll position in a direction is the max scroll position
1402 // we don't want to scroll at all.
1403 IntSize newScrollOffset;
1404 if (scrollPosition.x() < maximumScrollPosition.x())
1405 newScrollOffset.setWidth(scrollOffset.width());
1406 if (scrollPosition.y() < maximumScrollPosition.y())
1407 newScrollOffset.setHeight(scrollOffset.height());
1409 if (newScrollOffset.isZero())
1412 frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1415 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1417 GraphicsContextStateSaver stateSaver(graphicsContext);
1418 graphicsContext.clip(rect);
1420 m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1423 double WebPage::textZoomFactor() const
1425 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1426 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1427 if (pluginView->handlesPageScaleFactor())
1428 return pluginView->pageScaleFactor();
1429 return pageScaleFactor();
1432 Frame* frame = m_mainFrame->coreFrame();
1435 return frame->textZoomFactor();
1438 void WebPage::setTextZoomFactor(double zoomFactor)
1440 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1441 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1442 if (pluginView->handlesPageScaleFactor())
1443 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1445 scalePage(zoomFactor, IntPoint());
1449 Frame* frame = m_mainFrame->coreFrame();
1452 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1455 double WebPage::pageZoomFactor() const
1457 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1458 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1459 if (pluginView->handlesPageScaleFactor())
1460 return pluginView->pageScaleFactor();
1461 return pageScaleFactor();
1464 Frame* frame = m_mainFrame->coreFrame();
1467 return frame->pageZoomFactor();
1470 void WebPage::setPageZoomFactor(double zoomFactor)
1472 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1473 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1474 if (pluginView->handlesPageScaleFactor())
1475 pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1477 scalePage(zoomFactor, IntPoint());
1481 Frame* frame = m_mainFrame->coreFrame();
1484 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1487 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1489 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1490 if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1491 if (pluginView->handlesPageScaleFactor())
1492 pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1494 scalePage(pageZoomFactor, IntPoint());
1498 Frame* frame = m_mainFrame->coreFrame();
1501 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1504 void WebPage::windowScreenDidChange(uint32_t displayID)
1506 m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1509 void WebPage::scalePage(double scale, const IntPoint& origin)
1511 double totalScale = scale * viewScaleFactor();
1512 bool willChangeScaleFactor = totalScale != totalScaleFactor();
1515 if (willChangeScaleFactor) {
1516 if (!m_inDynamicSizeUpdate)
1517 m_dynamicSizeUpdateHistory.clear();
1518 m_scaleWasSetByUIProcess = false;
1521 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1522 if (pluginView && pluginView->handlesPageScaleFactor()) {
1523 // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1524 // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1525 if (m_page->pageScaleFactor() != 1) {
1526 m_page->setPageScaleFactor(1, origin);
1527 for (auto* pluginView : m_pluginViews)
1528 pluginView->pageScaleFactorDidChange();
1531 pluginView->setPageScaleFactor(totalScale, origin);
1535 m_page->setPageScaleFactor(totalScale, origin);
1537 // We can't early return before setPageScaleFactor because the origin might be different.
1538 if (!willChangeScaleFactor)
1541 for (auto* pluginView : m_pluginViews)
1542 pluginView->pageScaleFactorDidChange();
1544 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1545 if (m_drawingArea->layerTreeHost())
1546 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1549 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1552 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1554 double totalScale = scale * viewScaleFactor();
1555 if (totalScale == totalScaleFactor())
1558 IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1559 double scaleRatio = scale / pageScaleFactor();
1560 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1561 scalePage(scale, scrollPositionAtNewScale);
1564 double WebPage::totalScaleFactor() const
1566 PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1567 if (pluginView && pluginView->handlesPageScaleFactor())
1568 return pluginView->pageScaleFactor();
1570 return m_page->pageScaleFactor();
1573 double WebPage::pageScaleFactor() const
1575 return totalScaleFactor() / viewScaleFactor();
1578 double WebPage::viewScaleFactor() const
1580 return m_page->viewScaleFactor();
1583 void WebPage::scaleView(double scale)
1585 if (viewScaleFactor() == scale)
1588 float pageScale = pageScaleFactor();
1590 IntPoint scrollPositionAtNewScale;
1591 if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1592 double scaleRatio = scale / viewScaleFactor();
1593 scrollPositionAtNewScale = mainFrameView->scrollPosition();
1594 scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1597 m_page->setViewScaleFactor(scale);
1598 scalePage(pageScale, scrollPositionAtNewScale);
1601 void WebPage::setDeviceScaleFactor(float scaleFactor)
1603 if (scaleFactor == m_page->deviceScaleFactor())
1606 m_page->setDeviceScaleFactor(scaleFactor);
1608 // Tell all our plug-in views that the device scale factor changed.
1610 for (auto* pluginView : m_pluginViews)
1611 pluginView->setDeviceScaleFactor(scaleFactor);
1613 updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1616 if (m_findController.isShowingOverlay()) {
1617 // We must have updated layout to get the selection rects right.
1619 m_findController.deviceScaleFactorDidChange();
1622 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1623 if (m_drawingArea->layerTreeHost())
1624 m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1628 float WebPage::deviceScaleFactor() const
1630 return m_page->deviceScaleFactor();
1633 void WebPage::setUseFixedLayout(bool fixed)
1635 // Do not overwrite current settings if initially setting it to false.
1636 if (m_useFixedLayout == fixed)
1638 m_useFixedLayout = fixed;
1641 m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1643 #if USE(COORDINATED_GRAPHICS)
1644 m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1645 m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1646 m_page->settings().setDelegatesPageScaling(fixed);
1647 m_page->settings().setScrollingCoordinatorEnabled(fixed);
1650 #if USE(COORDINATED_GRAPHICS) && ENABLE(SMOOTH_SCROLLING)
1651 // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1652 // Ensure we don't do animated scrolling in the WebProcess in that case.
1653 m_page->settings().setScrollAnimatorEnabled(!fixed);
1656 FrameView* view = mainFrameView();
1660 #if USE(COORDINATED_GRAPHICS)
1661 view->setDelegatesScrolling(fixed);
1662 view->setPaintsEntireContents(fixed);
1664 view->setUseFixedLayout(fixed);
1666 setFixedLayoutSize(IntSize());
1668 send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1671 void WebPage::setFixedLayoutSize(const IntSize& size)
1673 FrameView* view = mainFrameView();
1674 if (!view || view->fixedLayoutSize() == size)
1677 view->setFixedLayoutSize(size);
1679 send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1682 IntSize WebPage::fixedLayoutSize() const
1684 FrameView* view = mainFrameView();
1687 return view->fixedLayoutSize();
1690 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1694 m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1697 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1699 m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1702 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1704 m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1707 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1709 m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1712 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1714 if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1715 m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1718 void WebPage::setPaginationMode(uint32_t mode)
1720 Pagination pagination = m_page->pagination();
1721 pagination.mode = static_cast<Pagination::Mode>(mode);
1722 m_page->setPagination(pagination);
1725 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1727 Pagination pagination = m_page->pagination();
1728 pagination.behavesLikeColumns = behavesLikeColumns;
1729 m_page->setPagination(pagination);
1732 void WebPage::setPageLength(double pageLength)
1734 Pagination pagination = m_page->pagination();
1735 pagination.pageLength = pageLength;
1736 m_page->setPagination(pagination);
1739 void WebPage::setGapBetweenPages(double gap)
1741 Pagination pagination = m_page->pagination();
1742 pagination.gap = gap;
1743 m_page->setPagination(pagination);
1746 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
1748 m_page->setPaginationLineGridEnabled(lineGridEnabled);
1751 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1753 auto& webProcess = WebProcess::singleton();
1754 InjectedBundle* injectedBundle = webProcess.injectedBundle();
1755 if (!injectedBundle)
1758 injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1762 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1765 m_headerBanner->detachFromPage();
1767 m_headerBanner = pageBanner;
1770 m_headerBanner->addToPage(PageBanner::Header, this);
1773 PageBanner* WebPage::headerPageBanner()
1775 return m_headerBanner.get();
1778 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1781 m_footerBanner->detachFromPage();
1783 m_footerBanner = pageBanner;
1786 m_footerBanner->addToPage(PageBanner::Footer, this);
1789 PageBanner* WebPage::footerPageBanner()
1791 return m_footerBanner.get();
1794 void WebPage::hidePageBanners()
1797 m_headerBanner->hide();
1799 m_footerBanner->hide();
1802 void WebPage::showPageBanners()
1805 m_headerBanner->showIfHidden();
1807 m_footerBanner->showIfHidden();
1809 #endif // !PLATFORM(IOS)
1811 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1813 SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1814 snapshotOptions |= SnapshotOptionsShareable;
1816 RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1818 ShareableBitmap::Handle handle;
1820 image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly);
1822 send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1825 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1827 IntRect snapshotRect = rect;
1828 IntSize bitmapSize = snapshotRect.size();
1829 if (options & SnapshotOptionsPrinting) {
1830 ASSERT(additionalScaleFactor == 1);
1831 Frame* coreFrame = m_mainFrame->coreFrame();
1834 bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
1836 double scaleFactor = additionalScaleFactor;
1837 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1838 scaleFactor *= corePage()->deviceScaleFactor();
1839 bitmapSize.scale(scaleFactor);
1842 return snapshotAtSize(rect, bitmapSize, options);
1845 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1847 Frame* coreFrame = m_mainFrame->coreFrame();
1851 FrameView* frameView = coreFrame->view();
1855 IntRect snapshotRect = rect;
1856 float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1857 float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1858 float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1860 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1861 if (!snapshot->bitmap())
1864 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1866 if (options & SnapshotOptionsPrinting) {
1867 PrintContext::spoolAllPagesWithBoundaries(*coreFrame, *graphicsContext, snapshotRect.size());
1868 return snapshot.release();
1871 Color documentBackgroundColor = frameView->documentBackgroundColor();
1872 Color backgroundColor = (coreFrame->settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView->baseBackgroundColor();
1873 graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
1875 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1876 double deviceScaleFactor = corePage()->deviceScaleFactor();
1877 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1878 scaleFactor /= deviceScaleFactor;
1881 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1882 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1884 FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1885 if (options & SnapshotOptionsExcludeSelectionHighlighting)
1886 shouldPaintSelection = FrameView::ExcludeSelection;
1888 FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1889 if (options & SnapshotOptionsInViewCoordinates)
1890 coordinateSpace = FrameView::ViewCoordinates;
1892 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
1894 if (options & SnapshotOptionsPaintSelectionRectangle) {
1895 FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1896 graphicsContext->setStrokeColor(Color(0xFF, 0, 0));
1897 graphicsContext->strokeRect(selectionRectangle, 1);
1900 return snapshot.release();
1903 PassRefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
1905 Frame* coreFrame = m_mainFrame->coreFrame();
1909 FrameView* frameView = coreFrame->view();
1913 if (!node.renderer())
1916 LayoutRect topLevelRect;
1917 IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
1918 if (snapshotRect.isEmpty())
1921 double scaleFactor = 1;
1922 IntSize snapshotSize = snapshotRect.size();
1923 unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
1924 if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
1925 scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
1926 snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
1929 RefPtr<WebImage> snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options));
1930 if (!snapshot->bitmap())
1933 auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1935 if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1936 double deviceScaleFactor = corePage()->deviceScaleFactor();
1937 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1938 scaleFactor /= deviceScaleFactor;
1941 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1942 graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1944 Color savedBackgroundColor = frameView->baseBackgroundColor();
1945 frameView->setBaseBackgroundColor(Color::transparent);
1946 frameView->setNodeToDraw(&node);
1948 frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
1950 frameView->setBaseBackgroundColor(savedBackgroundColor);
1951 frameView->setNodeToDraw(nullptr);
1953 return snapshot.release();
1956 void WebPage::pageDidScroll()
1959 if (!m_inDynamicSizeUpdate)
1960 m_dynamicSizeUpdateHistory.clear();
1962 m_uiClient->pageDidScroll(this);
1964 m_pageScrolledHysteresis.impulse();
1966 send(Messages::WebPageProxy::PageDidScroll());
1969 void WebPage::pageStoppedScrolling()
1971 // Maintain the current history item's scroll position up-to-date.
1972 if (Frame* frame = m_mainFrame->coreFrame())
1973 frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
1976 #if USE(COORDINATED_GRAPHICS)
1977 void WebPage::pageDidRequestScroll(const IntPoint& point)
1979 #if USE(COORDINATED_GRAPHICS_THREADED)
1980 drawingArea()->scroll(IntRect(point, IntSize()), IntSize());
1981 #elif USE(COORDINATED_GRAPHICS_MULTIPROCESS)
1982 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1987 #if ENABLE(CONTEXT_MENUS)
1988 WebContextMenu* WebPage::contextMenu()
1991 m_contextMenu = WebContextMenu::create(this);
1992 return m_contextMenu.get();
1995 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1997 corePage()->contextMenuController().clearContextMenu();
1999 // Simulate a mouse click to generate the correct menu.
2000 PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick);
2001 bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
2005 return contextMenu();
2011 static const WebEvent* g_currentEvent = 0;
2013 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2014 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2015 // platform events passed to the event handler code.
2016 const WebEvent* WebPage::currentEvent()
2018 return g_currentEvent;
2021 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
2023 auto* drawingArea = this->drawingArea();
2027 drawingArea->setLayerTreeStateIsFrozen(frozen);
2030 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2032 auto* drawingArea = this->drawingArea();
2036 return drawingArea->markLayersVolatileImmediatelyIfPossible();
2039 class CurrentEvent {
2041 explicit CurrentEvent(const WebEvent& event)
2042 : m_previousCurrentEvent(g_currentEvent)
2044 g_currentEvent = &event;
2049 g_currentEvent = m_previousCurrentEvent;
2053 const WebEvent* m_previousCurrentEvent;
2056 #if ENABLE(CONTEXT_MENUS)
2057 static bool isContextClick(const PlatformMouseEvent& event)
2060 return WebEventFactory::shouldBeHandledAsContextClick(event);
2062 return event.button() == WebCore::RightButton;
2066 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2068 IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2069 HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2071 Frame* frame = &page->corePage()->mainFrame();
2072 if (result.innerNonSharedNode())
2073 frame = result.innerNonSharedNode()->document().frame();
2075 bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
2077 page->contextMenu()->show();
2083 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
2085 Frame& frame = page->corePage()->mainFrame();
2089 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2091 switch (platformMouseEvent.type()) {
2092 case PlatformEvent::MousePressed: {
2093 #if ENABLE(CONTEXT_MENUS)
2094 if (isContextClick(platformMouseEvent))
2095 page->corePage()->contextMenuController().clearContextMenu();
2098 bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2099 #if ENABLE(CONTEXT_MENUS)
2100 if (isContextClick(platformMouseEvent))
2101 handled = handleContextMenuEvent(platformMouseEvent, page);
2105 case PlatformEvent::MouseReleased:
2106 return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2108 case PlatformEvent::MouseMoved:
2109 if (onlyUpdateScrollbars)
2110 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2111 return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2113 case PlatformEvent::MouseForceChanged:
2114 case PlatformEvent::MouseForceDown:
2115 case PlatformEvent::MouseForceUp:
2116 return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2119 ASSERT_NOT_REACHED();
2124 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2126 m_page->pageThrottler().didReceiveUserInput();
2128 bool shouldHandleEvent = true;
2130 #if ENABLE(CONTEXT_MENUS)
2131 // Don't try to handle any pending mouse events if a context menu is showing.
2132 if (m_isShowingContextMenu)
2133 shouldHandleEvent = false;
2135 #if ENABLE(DRAG_SUPPORT)
2136 if (m_isStartingDrag)
2137 shouldHandleEvent = false;
2140 if (!shouldHandleEvent) {
2141 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2145 bool handled = false;
2148 if (!handled && m_headerBanner)
2149 handled = m_headerBanner->mouseEvent(mouseEvent);
2150 if (!handled && m_footerBanner)
2151 handled = m_footerBanner->mouseEvent(mouseEvent);
2152 #endif // !PLATFORM(IOS)
2154 if (!handled && canHandleUserEvents()) {
2155 CurrentEvent currentEvent(mouseEvent);
2157 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2158 // button is currently pressed. It is possible that neither of those things will be true since on
2159 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2160 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2161 // efficient scrollbars-only version of the event.
2162 bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
2163 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
2166 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2169 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2171 Frame& frame = page->mainFrame();
2175 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2176 return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2179 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2181 m_page->pageThrottler().didReceiveUserInput();
2183 bool handled = false;
2185 if (canHandleUserEvents()) {
2186 CurrentEvent currentEvent(wheelEvent);
2188 handled = handleWheelEvent(wheelEvent, m_page.get());
2190 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2193 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2195 if (!page->mainFrame().view())
2198 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2199 return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2200 return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2203 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2205 m_page->pageThrottler().didReceiveUserInput();
2207 bool handled = false;
2209 if (canHandleUserEvents()) {
2210 CurrentEvent currentEvent(keyboardEvent);
2212 handled = handleKeyEvent(keyboardEvent, m_page.get());
2213 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2215 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2217 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2220 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
2222 bool isEnabled = false;
2224 Frame& frame = m_page->focusController().focusedOrMainFrame();
2225 if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2226 isEnabled = pluginView->isEditingCommandEnabled(commandName);
2228 Editor::Command command = frame.editor().command(commandName);
2229 state = command.state();
2230 isEnabled = command.isSupported() && command.isEnabled();
2233 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2236 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2238 executeEditingCommand(commandName, argument);
2241 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest)
2243 for (const auto& itemState : itemStates) {
2244 auto historyItem = toHistoryItem(itemState.pageState);
2245 historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2246 WebBackForwardListProxy::addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID);
2250 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2252 restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes);
2255 #if ENABLE(TOUCH_EVENTS)
2256 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2258 if (!page->mainFrame().view())
2261 return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2265 #if ENABLE(IOS_TOUCH_EVENTS)
2266 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2268 m_userIsInteracting = true;
2270 m_lastInteractionLocation = touchEvent.position();
2271 CurrentEvent currentEvent(touchEvent);
2272 handled = handleTouchEvent(touchEvent, m_page.get());
2274 m_userIsInteracting = false;
2277 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2279 EventDispatcher::TouchEventQueue queuedEvents;
2280 WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2281 dispatchAsynchronousTouchEvents(queuedEvents);
2283 dispatchTouchEvent(touchEvent, handled);
2285 #elif ENABLE(TOUCH_EVENTS)
2286 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2289 bool handled = false;
2290 if (canHandleUserEvents()) {
2291 CurrentEvent currentEvent(touchEvent);
2293 handled = handleTouchEvent(touchEvent, m_page.get());
2295 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2299 #if ENABLE(MAC_GESTURE_EVENTS)
2300 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2302 if (!page->mainFrame().view())
2305 return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2308 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2310 bool handled = false;
2311 if (canHandleUserEvents()) {
2312 CurrentEvent currentEvent(gestureEvent);
2313 handled = handleGestureEvent(gestureEvent, m_page.get());
2315 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2320 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2322 return page->userInputBridge().scrollRecursively(direction, granularity);
2325 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2327 return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2330 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2332 return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2335 void WebPage::centerSelectionInVisibleArea()
2337 Frame& frame = m_page->focusController().focusedOrMainFrame();
2338 frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
2339 m_findController.showFindIndicatorInSelection();
2342 bool WebPage::isControlledByAutomation() const
2344 return m_page->isControlledByAutomation();
2347 void WebPage::setControlledByAutomation(bool controlled)
2349 m_page->setControlledByAutomation(controlled);
2352 void WebPage::insertNewlineInQuotedContent()
2354 Frame& frame = m_page->focusController().focusedOrMainFrame();
2355 if (frame.selection().isNone())
2357 frame.editor().insertParagraphSeparatorInQuotedContent();
2360 #if ENABLE(REMOTE_INSPECTOR)
2361 void WebPage::setAllowsRemoteInspection(bool allow)
2363 m_page->setRemoteInspectionAllowed(allow);
2366 void WebPage::setRemoteInspectionNameOverride(const String& name)
2368 m_page->setRemoteInspectionNameOverride(name);
2372 void WebPage::setDrawsBackground(bool drawsBackground)
2374 if (m_drawsBackground == drawsBackground)
2377 m_drawsBackground = drawsBackground;
2379 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2380 if (FrameView* view = coreFrame->view())
2381 view->setTransparent(!drawsBackground);
2384 m_drawingArea->pageBackgroundTransparencyChanged();
2385 m_drawingArea->setNeedsDisplay();
2388 void WebPage::setTopContentInset(float contentInset)
2390 if (contentInset == m_page->topContentInset())
2393 m_page->setTopContentInset(contentInset);
2395 for (auto* pluginView : m_pluginViews)
2396 pluginView->topContentInsetDidChange();
2399 void WebPage::viewWillStartLiveResize()
2404 // FIXME: This should propagate to all ScrollableAreas.
2405 Frame& frame = m_page->focusController().focusedOrMainFrame();
2406 if (FrameView* view = frame.view())
2407 view->willStartLiveResize();
2410 void WebPage::viewWillEndLiveResize()
2415 // FIXME: This should propagate to all ScrollableAreas.
2416 Frame& frame = m_page->focusController().focusedOrMainFrame();
2417 if (FrameView* view = frame.view())
2418 view->willEndLiveResize();
2421 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, uint64_t callbackID)
2427 TemporaryChange<bool> userIsInteractingChange { m_userIsInteracting, true };
2430 Frame& frame = m_page->focusController().focusedOrMainFrame();
2431 frame.document()->setFocusedElement(0);
2433 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2434 PlatformKeyboardEvent platformEvent(platform(event));
2435 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2436 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2438 send(Messages::WebPageProxy::VoidCallback(callbackID));
2442 m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2443 send(Messages::WebPageProxy::VoidCallback(callbackID));
2446 void WebPage::setCanStartMediaTimerFired()
2449 m_page->setCanStartMedia(true);
2452 inline bool WebPage::canHandleUserEvents() const
2454 #if USE(COORDINATED_GRAPHICS)
2455 // Should apply only if the area was frozen by didStartPageTransition().
2456 return !m_drawingArea->layerTreeStateIsFrozen();
2461 void WebPage::updateIsInWindow(bool isInitialState)
2463 bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2466 m_setCanStartMediaTimer.stop();
2467 m_page->setCanStartMedia(false);
2469 // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2470 if (!isInitialState)
2471 WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2473 // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2474 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2475 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2476 if (m_mayStartMediaWhenInWindow)
2477 m_setCanStartMediaTimer.startOneShot(0);
2479 WebProcess::singleton().pageDidEnterWindow(m_pageID);
2486 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState, const Vector<uint64_t>& callbackIDs)
2488 ViewState::Flags changed = m_viewState ^ viewState;
2489 m_viewState = viewState;
2492 updateUserActivity();
2494 m_page->setViewState(viewState);
2495 for (auto* pluginView : m_pluginViews)
2496 pluginView->viewStateDidChange(changed);
2498 m_drawingArea->viewStateDidChange(changed, wantsDidUpdateViewState, callbackIDs);
2500 if (changed & ViewState::IsInWindow)
2504 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2506 m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2508 m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2510 for (auto* pluginView : m_pluginViews)
2511 pluginView->setLayerHostingMode(m_layerHostingMode);
2514 void WebPage::setSessionID(SessionID sessionID)
2516 if (sessionID.isEphemeral())
2517 WebProcess::singleton().ensurePrivateBrowsingSession(sessionID);
2518 m_page->setSessionID(sessionID);
2521 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, DownloadID downloadID)
2523 WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2526 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID);
2529 void WebPage::didStartPageTransition()
2531 m_drawingArea->setLayerTreeStateIsFrozen(true);
2533 m_hasFocusedDueToUserInteraction = false;
2537 void WebPage::didCompletePageTransition()
2539 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
2540 // m_mainFrame can be null since r170163.
2541 if (m_mainFrame && m_mainFrame->coreFrame()->view()->delegatesScrolling()) {
2542 // Wait until the UI process sent us the visible rect it wants rendered.
2543 send(Messages::WebPageProxy::PageTransitionViewportReady());
2547 m_drawingArea->setLayerTreeStateIsFrozen(false);
2550 void WebPage::show()
2552 send(Messages::WebPageProxy::ShowPage());
2555 String WebPage::userAgent(const URL& webCoreURL) const
2557 return userAgent(nullptr, webCoreURL);
2560 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2562 if (frame && m_loaderClient.client().userAgentForURL) {
2563 API::String* apiString = m_loaderClient.userAgentForURL(frame, API::URL::create(webcoreURL).ptr());
2565 return apiString->string();
2568 String userAgent = platformUserAgent(webcoreURL);
2569 if (!userAgent.isEmpty())
2574 void WebPage::setUserAgent(const String& userAgent)
2576 m_userAgent = userAgent;
2579 void WebPage::suspendActiveDOMObjectsAndAnimations()
2581 m_page->suspendActiveDOMObjectsAndAnimations();
2584 void WebPage::resumeActiveDOMObjectsAndAnimations()
2586 m_page->resumeActiveDOMObjectsAndAnimations();
2589 IntPoint WebPage::screenToRootView(const IntPoint& point)
2591 IntPoint windowPoint;
2592 sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2596 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2599 sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2604 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2606 IntPoint windowPoint;
2607 sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2611 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2614 sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2619 KeyboardUIMode WebPage::keyboardUIMode()
2621 bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
2622 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2625 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2627 // NOTE: We need to be careful when running scripts that the objects we depend on don't
2628 // disappear during script execution.
2630 RefPtr<SerializedScriptValue> serializedResultValue;
2631 JSLockHolder lock(JSDOMWindow::commonVM());
2632 bool hadException = true;
2633 ExceptionDetails details;
2634 if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true, &details).jsValue()) {
2635 hadException = false;
2636 serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
2637 toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr);
2640 IPC::DataReference dataReference;
2641 if (serializedResultValue)
2642 dataReference = serializedResultValue->data();
2643 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
2646 void WebPage::getContentsAsString(uint64_t callbackID)
2648 String resultString = m_mainFrame->contentsAsString();
2649 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2653 void WebPage::getContentsAsMHTMLData(uint64_t callbackID)
2655 RefPtr<SharedBuffer> buffer = MHTMLArchive::generateMHTMLData(m_page.get());
2657 // FIXME: Use SharedBufferDataReference.
2658 IPC::DataReference dataReference;
2660 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2661 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2665 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2667 String resultString = renderTreeExternalRepresentation();
2668 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2671 static Frame* frameWithSelection(Page* page)
2673 for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2674 if (frame->selection().isRange())
2681 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2684 RetainPtr<CFDataRef> data;
2685 if (Frame* frame = frameWithSelection(m_page.get()))
2686 data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
2689 IPC::DataReference dataReference;
2692 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2694 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2697 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2699 String resultString = m_mainFrame->selectionAsString();
2700 if (resultString.isEmpty())
2701 resultString = m_mainFrame->contentsAsString();
2702 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2705 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2707 String resultString;
2708 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2709 resultString = frame->source();
2711 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2714 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2716 RefPtr<SharedBuffer> buffer;
2717 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2718 if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
2719 buffer = pluginView->liveResourceData();
2721 if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
2722 buffer = loader->mainResourceData();
2726 // FIXME: Use SharedBufferDataReference.
2727 IPC::DataReference dataReference;
2729 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2730 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2733 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2735 DocumentLoader* loader = frame->loader().documentLoader();
2739 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2743 return &subresource->data();
2746 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2748 RefPtr<SharedBuffer> buffer;
2749 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2750 URL resourceURL(URL(), resourceURLString);
2751 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2753 // Try to get the resource data from the cache.
2754 buffer = cachedResponseDataForURL(resourceURL);
2758 // FIXME: Use SharedBufferDataReference.
2759 IPC::DataReference dataReference;
2761 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2762 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2765 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2768 RetainPtr<CFDataRef> data;
2769 if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2770 data = frame->webArchiveData(nullptr, nullptr);
2772 UNUSED_PARAM(frameID);
2775 IPC::DataReference dataReference;
2778 dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2780 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2783 void WebPage::forceRepaintWithoutCallback()
2785 m_drawingArea->forceRepaint();
2788 void WebPage::forceRepaint(uint64_t callbackID)
2790 if (m_drawingArea->forceRepaintAsync(callbackID))
2793 forceRepaintWithoutCallback();
2794 send(Messages::WebPageProxy::VoidCallback(callbackID));
2797 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2799 WebPreferencesStore::removeTestRunnerOverrides();
2800 updatePreferences(store);
2803 void WebPage::updatePreferences(const WebPreferencesStore& store)
2805 Settings& settings = m_page->settings();
2807 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2808 m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2809 m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2810 m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2812 m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2815 m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2818 // FIXME: This should be generated from macro expansion for all preferences,
2819 // but we currently don't match the naming of WebCore exactly so we are
2820 // handrolling the boolean and integer preferences until that is fixed.
2822 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2824 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2826 #undef INITIALIZE_SETTINGS
2828 settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2829 settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2830 settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2831 settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2832 settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2833 settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2834 settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));
2835 settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2836 settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2837 settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2838 settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2839 if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
2840 setSessionID(SessionID::legacyPrivateSessionID());
2841 else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
2842 setSessionID(SessionID::defaultSessionID());
2843 settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2844 settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
2845 settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2846 settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2847 settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2848 settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2849 settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2850 settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey()));
2851 #if ENABLE(WEB_ARCHIVE)
2852 settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2854 settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2855 settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2856 settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2857 settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2858 settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2859 settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2860 settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2861 settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2862 settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2863 settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2864 settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2866 settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2867 settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2868 settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2869 settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2870 settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2871 settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2872 settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2873 settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2874 settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2876 settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2877 settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
2878 settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
2879 settings.setDisplayListDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::displayListDrawingEnabledKey()));
2880 settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
2881 settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2882 settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2883 settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2884 settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey()));
2885 settings.setUseGiantTiles(store.getBoolValueForKey(WebPreferencesKey::useGiantTilesKey()));
2887 settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2888 settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
2889 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
2890 RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey()));
2892 #if ENABLE(WEB_ANIMATIONS)
2893 RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled(store.getBoolValueForKey(WebPreferencesKey::webAnimationsEnabledKey()));
2895 RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2896 RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2897 settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2898 settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2899 settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2900 bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
2901 settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
2902 settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
2903 settings.setMainContentUserGestureOverrideEnabled(store.getBoolValueForKey(WebPreferencesKey::mainContentUserGestureOverrideEnabledKey()));
2904 settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey()));
2905 settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute(store.getBoolValueForKey(WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey()));
2906 settings.setInvisibleAutoplayNotPermitted(store.getBoolValueForKey(WebPreferencesKey::invisibleAutoplayNotPermittedKey()));
2907 settings.setMediaDataLoadsAutomatically(store.getBoolValueForKey(WebPreferencesKey::mediaDataLoadsAutomaticallyKey()));
2908 #if ENABLE(ATTACHMENT_ELEMENT)
2909 settings.setAttachmentElementEnabled(store.getBoolValueForKey(WebPreferencesKey::attachmentElementEnabledKey()));
2911 settings.setAllowsPictureInPictureMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey()));
2912 settings.setMediaControlsScaleWithPageZoom(store.getBoolValueForKey(WebPreferencesKey::mediaControlsScaleWithPageZoomKey()));
2913 settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2914 settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2915 settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2916 #if ENABLE(SMOOTH_SCROLLING)
2917 settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2919 settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
2920 settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2921 settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2923 settings.setHttpEquivEnabled(store.getBoolValueForKey(WebPreferencesKey::httpEquivEnabledKey()));
2925 DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2927 #if ENABLE(FULLSCREEN_API)
2928 settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2931 #if USE(AVFOUNDATION)
2932 settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2933 settings.setAVFoundationNSURLSessionEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationNSURLSessionEnabledKey()));
2937 settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2940 #if PLATFORM(IOS) && HAVE(AVKIT)
2941 settings.setAVKitEnabled(true);
2944 #if ENABLE(IOS_TEXT_AUTOSIZING)
2945 settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2948 #if ENABLE(WEB_AUDIO)
2949 settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2952 #if ENABLE(MEDIA_STREAM)
2953 settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2956 #if ENABLE(SERVICE_CONTROLS)
2957 settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2960 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2961 settings.setAllowsAirPlayForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsAirPlayForMediaPlaybackKey()));
2964 #if ENABLE(RESOURCE_USAGE)
2965 settings.setResourceUsageOverlayVisible(store.getBoolValueForKey(WebPreferencesKey::resourceUsageOverlayVisibleKey()));
2968 settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2969 settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2970 settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2971 settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2972 settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2974 #if ENABLE(VIDEO_TRACK)
2975 settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2976 settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2977 settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2980 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2981 settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2984 settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2985 settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2986 settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2988 settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2990 settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2992 settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2993 settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2994 settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2995 settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2996 settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2998 #if ENABLE(TEXT_AUTOSIZING)
2999 settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
3002 settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
3003 settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
3005 settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
3006 settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
3007 settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
3009 settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
3010 settings.setHiddenPageDOMTimerThrottlingAutoIncreases(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingAutoIncreasesKey()));
3012 settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
3013 settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
3014 settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
3015 settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
3017 settings.setNewBlockInsideInlineModelEnabled(store.getBoolValueForKey(WebPreferencesKey::newBlockInsideInlineModelEnabledKey()));
3019 settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
3021 settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
3023 #if ENABLE(MEDIA_SOURCE)
3024 settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
3027 #if ENABLE(MEDIA_STREAM)
3028 settings.setMockCaptureDevicesEnabled(store.getBoolValueForKey(WebPreferencesKey::mockCaptureDevicesEnabledKey()));
3031 settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
3033 settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
3034 settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
3035 settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
3036 settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
3038 settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
3039 settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
3041 settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
3042 settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
3044 settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
3046 settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
3048 #if USE(APPLE_INTERNAL_SDK)
3049 #include <WebKitAdditions/WebPagePreferences.cpp>
3053 settings.setUseImageDocumentForSubframePDF(true);
3056 #if ENABLE(DATA_DETECTION)
3057 settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3060 RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
3063 #if ENABLE(SERVICE_CONTROLS)
3064 settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
3067 #if ENABLE(SHADOW_DOM)
3068 RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled(store.getBoolValueForKey(WebPreferencesKey::shadowDOMEnabledKey()));
3071 #if ENABLE(CUSTOM_ELEMENTS)
3072 RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled(store.getBoolValueForKey(WebPreferencesKey::customElementsEnabledKey()));
3075 bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3076 if (m_processSuppressionEnabled != processSuppressionEnabled) {
3077 m_processSuppressionEnabled = processSuppressionEnabled;
3078 updateUserActivity();
3081 platformPreferencesDidChange(store);
3084 m_drawingArea->updatePreferences(store);
3087 m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3088 m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3089 m_forceAlwaysUserScalable = store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey());
3090 updateForceAlwaysUserScalable();
3094 #if ENABLE(DATA_DETECTION)
3095 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3097 DataDetectionResult dataDetectionResult;
3098 dataDetectionResult.results = detectionResults;
3099 send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3104 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3106 layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
3107 layerTransaction.setScrollOrigin(corePage()->mainFrame().view()->scrollOrigin());
3108 layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3109 layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3110 layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3112 layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3113 layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3114 layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3115 layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3116 layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3117 layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3118 layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3119 layerTransaction.setAllowsUserScaling(allowsUserScaling());
3122 layerTransaction.setScrollPosition(corePage()->mainFrame().view()->scrollPosition());
3126 void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp)
3129 if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) {
3130 std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3131 m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero();
3133 m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20));
3136 UNUSED_PARAM(timestamp);
3141 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3145 if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3146 m_inspector = WebInspector::create(this);
3147 return m_inspector.get();
3150 WebInspectorUI* WebPage::inspectorUI()
3155 m_inspectorUI = WebInspectorUI::create(*this);
3156 return m_inspectorUI.get();
3159 #if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3160 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
3162 if (!m_videoFullscreenManager)
3163 m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
3164 return m_videoFullscreenManager.get();
3169 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3171 m_page->setAllowsMediaDocumentInlinePlayback(allows);
3175 #if ENABLE(FULLSCREEN_API)
3176 WebFullScreenManager* WebPage::fullScreenManager()
3178 if (!m_fullScreenManager)
3179 m_fullScreenManager = WebFullScreenManager::create(this);
3180 return m_fullScreenManager.get();
3184 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3186 if (m_notificationPermissionRequestManager)
3187 return m_notificationPermissionRequestManager.get();
3189 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3190 return m_notificationPermissionRequestManager.get();
3193 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
3194 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
3196 Node* node = evt->target()->toNode();
3198 Frame* frame = node->document().frame();
3201 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
3205 Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
3207 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
3208 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
3209 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
3210 // (e.g. Tab that inserts a Tab character, or Enter).
3211 return !command.isTextInsertion() && command.execute(evt);
3214 if (command.execute(evt))
3217 // Don't allow text insertion for nodes that cannot edit.
3218 if (!frame->editor().canEdit())
3221 // Don't insert null or control characters as they can result in unexpected behaviour
3222 if (evt->charCode() < ' ')
3225 return frame->editor().insertText(evt->keyEvent()->text(), evt);
3229 #if ENABLE(DRAG_SUPPORT)
3232 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
3235 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3236 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3242 case DragControllerActionEntered: {
3243 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3244 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3247 case DragControllerActionUpdated: {
3248 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3249 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3252 case DragControllerActionExited:
3253 m_page->dragController().dragExited(dragData);
3256 case DragControllerActionPerformDragOperation: {
3257 m_page->dragController().performDragOperation(dragData);
3262 ASSERT_NOT_REACHED();
3264 // DragData does not delete its platformData so we need to do that here.
3265 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3270 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)
3273 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3277 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3279 case DragControllerActionEntered: {
3280 DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3281 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3285 case DragControllerActionUpdated: {
3286 DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3287 send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3290 case DragControllerActionExited:
3291 m_page->dragController().dragExited(dragData);
3294 case DragControllerActionPerformDragOperation: {
3295 ASSERT(!m_pendingDropSandboxExtension);
3297 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
3298 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3299 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
3300 m_pendingDropExtensionsForFileUpload.append(extension);
3303 m_page->dragController().performDragOperation(dragData);
3305 // If we started loading a local file, the sandbox extension tracker would have adopted this
3306 // pending drop sandbox extension. If not, we'll play it safe and clear it.
3307 m_pendingDropSandboxExtension = nullptr;
3309 m_pendingDropExtensionsForFileUpload.clear();
3314 ASSERT_NOT_REACHED();
3319 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3321 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3322 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3324 m_page->dragController().dragEnded();
3325 FrameView* view = m_page->mainFrame().view();
3328 // FIXME: These are fake modifier keys here, but they should be real ones instead.
3329 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime(), 0);
3330 m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3333 void WebPage::willPerformLoadDragDestinationAction()
3335 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
3338 void WebPage::mayPerformUploadDragDestinationAction()
3340 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3341 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3342 m_pendingDropExtensionsForFileUpload.clear();
3345 #endif // ENABLE(DRAG_SUPPORT)
3347 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3349 return m_undoStepMap.get(stepID);
3352 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3354 m_undoStepMap.set(stepID, entry);
3357 void WebPage::removeWebEditCommand(uint64_t stepID)
3359 m_undoStepMap.remove(stepID);
3362 void WebPage::unapplyEditCommand(uint64_t stepID)
3364 WebUndoStep* step = webUndoStep(stepID);
3368 step->step()->unapply();
3371 void WebPage::reapplyEditCommand(uint64_t stepID)
3373 WebUndoStep* step = webUndoStep(stepID);
3378 step->step()->reapply();
3382 void WebPage::didRemoveEditCommand(uint64_t commandID)
3384 removeWebEditCommand(commandID);
3387 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3389 m_activePopupMenu = menu;
3392 #if ENABLE(INPUT_TYPE_COLOR)
3393 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3395 m_activeColorChooser = colorChooser;
3398 void WebPage::didEndColorPicker()
3400 m_activeColorChooser->didEndChooser();
3403 void WebPage::didChooseColor(const WebCore::Color& color)
3405 m_activeColorChooser->didChooseColor(color);
3409 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
3411 m_activeOpenPanelResultListener = openPanelResultListener;
3414 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3416 return m_page->findString(target, options);
3419 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3421 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
3424 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3426 m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3429 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3431 m_findController.getImageForFindMatch(matchIndex);
3434 void WebPage::selectFindMatch(uint32_t matchIndex)
3436 m_findController.selectFindMatch(matchIndex);
3439 void WebPage::hideFindUI()
3441 m_findController.hideFindUI();
3444 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3446 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3449 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3451 changeSelectedIndex(newIndex);
3452 m_activePopupMenu = nullptr;
3455 void WebPage::changeSelectedIndex(int32_t index)
3457 if (!m_activePopupMenu)
3460 m_activePopupMenu->didChangeSelectedIndex(index);
3464 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3466 if (!m_activeOpenPanelResultListener)
3470 if (!iconData.isEmpty()) {
3471 RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3472 RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3473 RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3474 icon = Icon::createIconForImage(imageRef.get());
3477 m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3478 m_activeOpenPanelResultListener = nullptr;
3482 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3484 if (!m_activeOpenPanelResultListener)
3487 m_activeOpenPanelResultListener->didChooseFiles(files);
3488 m_activeOpenPanelResultListener = nullptr;
3491 void WebPage::didCancelForOpenPanel()
3493 m_activeOpenPanelResultListener = nullptr;
3496 #if ENABLE(SANDBOX_EXTENSIONS)
3497 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3499 bool result = SandboxExtension::consumePermanently(handle);
3501 // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3502 WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3507 #if ENABLE(GEOLOCATION)
3508 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3510 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3514 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3516 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3519 #if ENABLE(MEDIA_STREAM)
3520 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed, const String& audioDeviceUID, const String& videoDeviceUID)
3522 m_userMediaPermissionRequestManager.didReceiveUserMediaPermissionDecision(userMediaID, allowed, audioDeviceUID, videoDeviceUID);
3525 void WebPage::didCompleteUserMediaPermissionCheck(uint64_t userMediaID, const String& mediaDeviceIdentifierHashSalt, bool allowed)
3527 m_userMediaPermissionRequestManager.didCompleteUserMediaPermissionCheck(userMediaID, mediaDeviceIdentifierHashSalt, allowed);