a42b87456872bcae44ea1796e007578684cdccba
[WebKit-https.git] / Source / WebKit / WebProcess / WebPage / WebPage.cpp
1 /*
2  * Copyright (C) 2010-2018 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)
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
14  *
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.
26  */
27
28 #include "config.h"
29 #include "WebPage.h"
30
31 #include "APIArray.h"
32 #include "APIGeometry.h"
33 #include "AssistedNodeInformation.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 "FindController.h"
41 #include "FormDataReference.h"
42 #include "GeolocationPermissionRequestManager.h"
43 #include "InjectUserScriptImmediately.h"
44 #include "InjectedBundle.h"
45 #include "InjectedBundleScriptWorld.h"
46 #include "LibWebRTCProvider.h"
47 #include "LoadParameters.h"
48 #include "Logging.h"
49 #include "NetscapePlugin.h"
50 #include "NetworkConnectionToWebProcessMessages.h"
51 #include "NetworkProcessConnection.h"
52 #include "NotificationPermissionRequestManager.h"
53 #include "PageBanner.h"
54 #include "PluginProcessAttributes.h"
55 #include "PluginProxy.h"
56 #include "PluginView.h"
57 #include "PrintInfo.h"
58 #include "RemoteWebInspectorUI.h"
59 #include "RemoteWebInspectorUIMessages.h"
60 #include "SessionState.h"
61 #include "SessionStateConversion.h"
62 #include "SessionTracker.h"
63 #include "ShareSheetCallbackID.h"
64 #include "ShareableBitmap.h"
65 #include "SharedBufferDataReference.h"
66 #include "UserMediaPermissionRequestManager.h"
67 #include "ViewGestureGeometryCollector.h"
68 #include "VisitedLinkTableController.h"
69 #include "WKBundleAPICast.h"
70 #include "WKRetainPtr.h"
71 #include "WKSharedAPICast.h"
72 #include "WebAlternativeTextClient.h"
73 #include "WebBackForwardListItem.h"
74 #include "WebBackForwardListProxy.h"
75 #include "WebCacheStorageProvider.h"
76 #include "WebChromeClient.h"
77 #include "WebColorChooser.h"
78 #include "WebContextMenu.h"
79 #include "WebContextMenuClient.h"
80 #include "WebCoreArgumentCoders.h"
81 #include "WebDataListSuggestionPicker.h"
82 #include "WebDatabaseProvider.h"
83 #include "WebDiagnosticLoggingClient.h"
84 #include "WebDocumentLoader.h"
85 #include "WebDragClient.h"
86 #include "WebEditorClient.h"
87 #include "WebEvent.h"
88 #include "WebEventConversion.h"
89 #include "WebEventFactory.h"
90 #include "WebFrame.h"
91 #include "WebFrameLoaderClient.h"
92 #include "WebFullScreenManager.h"
93 #include "WebFullScreenManagerMessages.h"
94 #include "WebGamepadProvider.h"
95 #include "WebGeolocationClient.h"
96 #include "WebImage.h"
97 #include "WebInspector.h"
98 #include "WebInspectorClient.h"
99 #include "WebInspectorMessages.h"
100 #include "WebInspectorUI.h"
101 #include "WebInspectorUIMessages.h"
102 #include "WebMediaKeyStorageManager.h"
103 #include "WebNotificationClient.h"
104 #include "WebOpenPanelResultListener.h"
105 #include "WebPageCreationParameters.h"
106 #include "WebPageGroupProxy.h"
107 #include "WebPageMessages.h"
108 #include "WebPageOverlay.h"
109 #include "WebPageProxyMessages.h"
110 #include "WebPaymentCoordinator.h"
111 #include "WebPerformanceLoggingClient.h"
112 #include "WebPlugInClient.h"
113 #include "WebPluginInfoProvider.h"
114 #include "WebPopupMenu.h"
115 #include "WebPreferencesDefinitions.h"
116 #include "WebPreferencesKeys.h"
117 #include "WebPreferencesStore.h"
118 #include "WebProcess.h"
119 #include "WebProcessPoolMessages.h"
120 #include "WebProcessProxyMessages.h"
121 #include "WebProgressTrackerClient.h"
122 #include "WebSocketProvider.h"
123 #include "WebStorageNamespaceProvider.h"
124 #include "WebURLSchemeHandlerProxy.h"
125 #include "WebUndoStep.h"
126 #include "WebUserContentController.h"
127 #include "WebUserMediaClient.h"
128 #include "WebValidationMessageClient.h"
129 #include "WebsiteDataStoreParameters.h"
130 #include <JavaScriptCore/APICast.h>
131 #include <JavaScriptCore/JSCInlines.h>
132 #include <JavaScriptCore/JSCJSValue.h>
133 #include <JavaScriptCore/JSLock.h>
134 #include <JavaScriptCore/ProfilerDatabase.h>
135 #include <JavaScriptCore/SamplingProfiler.h>
136 #include <WebCore/ApplicationCacheStorage.h>
137 #include <WebCore/ArchiveResource.h>
138 #include <WebCore/BackForwardController.h>
139 #include <WebCore/Chrome.h>
140 #include <WebCore/CommonVM.h>
141 #include <WebCore/ContextMenuController.h>
142 #include <WebCore/DataTransfer.h>
143 #include <WebCore/DatabaseManager.h>
144 #include <WebCore/DeprecatedGlobalSettings.h>
145 #include <WebCore/DocumentFragment.h>
146 #include <WebCore/DocumentLoader.h>
147 #include <WebCore/DocumentMarkerController.h>
148 #include <WebCore/DragController.h>
149 #include <WebCore/DragData.h>
150 #include <WebCore/Editing.h>
151 #include <WebCore/Editor.h>
152 #include <WebCore/ElementIterator.h>
153 #include <WebCore/EventHandler.h>
154 #include <WebCore/EventNames.h>
155 #include <WebCore/File.h>
156 #include <WebCore/FocusController.h>
157 #include <WebCore/FontAttributeChanges.h>
158 #include <WebCore/FontAttributes.h>
159 #include <WebCore/FormState.h>
160 #include <WebCore/Frame.h>
161 #include <WebCore/FrameLoadRequest.h>
162 #include <WebCore/FrameLoaderTypes.h>
163 #include <WebCore/FrameView.h>
164 #include <WebCore/GraphicsContext3D.h>
165 #include <WebCore/HTMLAttachmentElement.h>
166 #include <WebCore/HTMLFormElement.h>
167 #include <WebCore/HTMLImageElement.h>
168 #include <WebCore/HTMLInputElement.h>
169 #include <WebCore/HTMLMenuElement.h>
170 #include <WebCore/HTMLMenuItemElement.h>
171 #include <WebCore/HTMLOListElement.h>
172 #include <WebCore/HTMLPlugInElement.h>
173 #include <WebCore/HTMLPlugInImageElement.h>
174 #include <WebCore/HTMLUListElement.h>
175 #include <WebCore/HistoryController.h>
176 #include <WebCore/HistoryItem.h>
177 #include <WebCore/HitTestResult.h>
178 #include <WebCore/InspectorController.h>
179 #include <WebCore/JSDOMExceptionHandling.h>
180 #include <WebCore/JSDOMWindow.h>
181 #include <WebCore/KeyboardEvent.h>
182 #include <WebCore/MIMETypeRegistry.h>
183 #include <WebCore/MouseEvent.h>
184 #include <WebCore/NotImplemented.h>
185 #include <WebCore/Page.h>
186 #include <WebCore/PageConfiguration.h>
187 #include <WebCore/PingLoader.h>
188 #include <WebCore/PlatformKeyboardEvent.h>
189 #include <WebCore/PluginDocument.h>
190 #include <WebCore/PrintContext.h>
191 #include <WebCore/PromisedAttachmentInfo.h>
192 #include <WebCore/Range.h>
193 #include <WebCore/RemoteDOMWindow.h>
194 #include <WebCore/RemoteFrame.h>
195 #include <WebCore/RenderLayer.h>
196 #include <WebCore/RenderTheme.h>
197 #include <WebCore/RenderTreeAsText.h>
198 #include <WebCore/RenderView.h>
199 #include <WebCore/ResourceRequest.h>
200 #include <WebCore/ResourceResponse.h>
201 #include <WebCore/RuntimeEnabledFeatures.h>
202 #include <WebCore/SchemeRegistry.h>
203 #include <WebCore/ScriptController.h>
204 #include <WebCore/SerializedScriptValue.h>
205 #include <WebCore/ServiceWorkerProvider.h>
206 #include <WebCore/Settings.h>
207 #include <WebCore/ShadowRoot.h>
208 #include <WebCore/SharedBuffer.h>
209 #include <WebCore/StyleProperties.h>
210 #include <WebCore/SubframeLoader.h>
211 #include <WebCore/SubstituteData.h>
212 #include <WebCore/TextIterator.h>
213 #include <WebCore/UserGestureIndicator.h>
214 #include <WebCore/UserInputBridge.h>
215 #include <WebCore/UserScript.h>
216 #include <WebCore/UserStyleSheet.h>
217 #include <WebCore/UserTypingGestureIndicator.h>
218 #include <WebCore/VisiblePosition.h>
219 #include <WebCore/VisibleUnits.h>
220 #include <WebCore/WebGLStateTracker.h>
221 #include <WebCore/markup.h>
222 #include <pal/SessionID.h>
223 #include <wtf/ProcessID.h>
224 #include <wtf/RunLoop.h>
225 #include <wtf/SetForScope.h>
226 #include <wtf/text/TextStream.h>
227
228 #if ENABLE(DATA_DETECTION)
229 #include "DataDetectionResult.h"
230 #endif
231
232 #if ENABLE(MHTML)
233 #include <WebCore/MHTMLArchive.h>
234 #endif
235
236 #if ENABLE(POINTER_LOCK)
237 #include <WebCore/PointerLockController.h>
238 #endif
239
240 #if PLATFORM(COCOA)
241 #include "PDFPlugin.h"
242 #include "PlaybackSessionManager.h"
243 #include "RemoteLayerTreeTransaction.h"
244 #include "TouchBarMenuData.h"
245 #include "TouchBarMenuItemData.h"
246 #include "VideoFullscreenManager.h"
247 #include "WKStringCF.h"
248 #include <WebCore/LegacyWebArchive.h>
249 #include <wtf/MachSendRight.h>
250 #endif
251
252 #if PLATFORM(GTK)
253 #include "WebPrintOperationGtk.h"
254 #include "WebSelectionData.h"
255 #include <gtk/gtk.h>
256 #endif
257
258 #if PLATFORM(IOS_FAMILY)
259 #include "RemoteLayerTreeDrawingArea.h"
260 #include <CoreGraphics/CoreGraphics.h>
261 #include <WebCore/Icon.h>
262 #include <pal/spi/cocoa/CoreTextSPI.h>
263 #endif
264
265 #if PLATFORM(MAC)
266 #include <WebCore/LocalDefaultSystemAppearance.h>
267 #include <pal/spi/cf/CFUtilitiesSPI.h>
268 #endif
269
270 #ifndef NDEBUG
271 #include <wtf/RefCountedLeakCounter.h>
272 #endif
273
274 #if ENABLE(DATA_DETECTION)
275 #include <WebCore/DataDetection.h>
276 #endif
277
278 #if ENABLE(VIDEO) && USE(GSTREAMER)
279 #include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h>
280 #endif
281
282 #if ENABLE(WEB_AUTHN)
283 #include "WebAuthenticatorCoordinator.h"
284 #include <WebCore/AuthenticatorCoordinator.h>
285 #endif
286
287 namespace WebKit {
288 using namespace JSC;
289 using namespace WebCore;
290
291 static const Seconds pageScrollHysteresisDuration { 300_ms };
292 static const Seconds initialLayerVolatilityTimerInterval { 20_ms };
293 static const Seconds maximumLayerVolatilityTimerInterval { 2_s };
294
295 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
296 #define RELEASE_LOG_ERROR_IF_ALLOWED(...) RELEASE_LOG_ERROR_IF(isAlwaysOnLoggingAllowed(), Layers, __VA_ARGS__)
297
298 class SendStopResponsivenessTimer {
299 public:
300     ~SendStopResponsivenessTimer()
301     {
302         WebProcess::singleton().parentProcessConnection()->send(Messages::WebProcessProxy::StopResponsivenessTimer(), 0);
303     }
304 };
305
306 class DeferredPageDestructor {
307 public:
308     static void createDeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
309     {
310         new DeferredPageDestructor(WTFMove(page), webPage);
311     }
312
313 private:
314     DeferredPageDestructor(std::unique_ptr<Page> page, WebPage* webPage)
315         : m_page(WTFMove(page))
316         , m_webPage(webPage)
317     {
318         tryDestruction();
319     }
320
321     void tryDestruction()
322     {
323         if (m_page->insideNestedRunLoop()) {
324             m_page->whenUnnested([this] { tryDestruction(); });
325             return;
326         }
327
328         m_page = nullptr;
329         m_webPage = nullptr;
330         delete this;
331     }
332
333     std::unique_ptr<Page> m_page;
334     RefPtr<WebPage> m_webPage;
335 };
336
337 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
338
339 Ref<WebPage> WebPage::create(uint64_t pageID, WebPageCreationParameters&& parameters)
340 {
341     Ref<WebPage> page = adoptRef(*new WebPage(pageID, WTFMove(parameters)));
342
343     if (WebProcess::singleton().injectedBundle())
344         WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr());
345
346     return page;
347 }
348
349 WebPage::WebPage(uint64_t pageID, WebPageCreationParameters&& parameters)
350     : m_pageID(pageID)
351     , m_viewSize(parameters.viewSize)
352     , m_alwaysShowsHorizontalScroller { parameters.alwaysShowsHorizontalScroller }
353     , m_alwaysShowsVerticalScroller { parameters.alwaysShowsVerticalScroller }
354 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
355     , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
356 #endif
357     , m_layerHostingMode(parameters.layerHostingMode)
358 #if PLATFORM(COCOA)
359     , m_viewGestureGeometryCollector(makeUniqueRef<ViewGestureGeometryCollector>(*this))
360 #elif HAVE(ACCESSIBILITY) && PLATFORM(GTK)
361     , m_accessibilityObject(nullptr)
362 #endif
363     , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
364 #if ENABLE(CONTEXT_MENUS)
365     , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>())
366 #endif
367     , m_editorClient { std::make_unique<API::InjectedBundle::EditorClient>() }
368     , m_formClient(std::make_unique<API::InjectedBundle::FormClient>())
369     , m_loaderClient(std::make_unique<API::InjectedBundle::PageLoaderClient>())
370     , m_resourceLoadClient(std::make_unique<API::InjectedBundle::ResourceLoadClient>())
371     , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>())
372     , m_findController(makeUniqueRef<FindController>(this))
373     , m_userContentController(WebUserContentController::getOrCreate(parameters.userContentControllerID))
374 #if ENABLE(GEOLOCATION)
375     , m_geolocationPermissionRequestManager(makeUniqueRef<GeolocationPermissionRequestManager>(*this))
376 #endif
377 #if ENABLE(MEDIA_STREAM)
378     , m_userMediaPermissionRequestManager { std::make_unique<UserMediaPermissionRequestManager>(*this) }
379 #endif
380     , m_pageScrolledHysteresis([this](PAL::HysteresisState state) { if (state == PAL::HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisDuration)
381     , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
382     , m_canRunModal(parameters.canRunModal)
383 #if PLATFORM(IOS_FAMILY)
384     , m_forceAlwaysUserScalable(parameters.ignoresViewportScaleLimits)
385     , m_screenSize(parameters.screenSize)
386     , m_availableScreenSize(parameters.availableScreenSize)
387     , m_overrideScreenSize(parameters.overrideScreenSize)
388 #endif
389     , m_layerVolatilityTimer(*this, &WebPage::layerVolatilityTimerFired)
390     , m_activityState(parameters.activityState)
391     , m_processSuppressionEnabled(true)
392     , m_userActivity("Process suppression disabled for page.")
393     , m_userActivityHysteresis([this](PAL::HysteresisState) { updateUserActivity(); })
394     , m_userInterfaceLayoutDirection(parameters.userInterfaceLayoutDirection)
395     , m_overrideContentSecurityPolicy { parameters.overrideContentSecurityPolicy }
396     , m_cpuLimit(parameters.cpuLimit)
397 #if PLATFORM(MAC)
398     , m_shouldAttachDrawingAreaOnPageTransition(parameters.shouldDelayAttachingDrawingArea)
399 #endif
400 {
401     ASSERT(m_pageID);
402
403     m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData);
404
405 #if PLATFORM(IOS_FAMILY)
406     DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(true);
407 #endif
408
409     PageConfiguration pageConfiguration(
410         makeUniqueRef<WebEditorClient>(this),
411         WebSocketProvider::create(),
412         makeUniqueRef<WebKit::LibWebRTCProvider>(),
413         WebProcess::singleton().cacheStorageProvider(),
414         WebBackForwardListProxy::create(*this)
415     );
416     pageConfiguration.chromeClient = new WebChromeClient(*this);
417 #if ENABLE(CONTEXT_MENUS)
418     pageConfiguration.contextMenuClient = new WebContextMenuClient(this);
419 #endif
420 #if ENABLE(DRAG_SUPPORT)
421     pageConfiguration.dragClient = new WebDragClient(this);
422 #endif
423     pageConfiguration.inspectorClient = new WebInspectorClient(this);
424 #if USE(AUTOCORRECTION_PANEL)
425     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this);
426 #endif
427
428     pageConfiguration.plugInClient = new WebPlugInClient(*this);
429     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
430     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this);
431     pageConfiguration.diagnosticLoggingClient = std::make_unique<WebDiagnosticLoggingClient>(*this);
432     pageConfiguration.performanceLoggingClient = std::make_unique<WebPerformanceLoggingClient>(*this);
433
434     pageConfiguration.webGLStateTracker = std::make_unique<WebGLStateTracker>([this](bool isUsingHighPerformanceWebGL) {
435         send(Messages::WebPageProxy::SetIsUsingHighPerformanceWebGL(isUsingHighPerformanceWebGL));
436     });
437
438 #if PLATFORM(COCOA)
439     pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(*this);
440 #endif
441
442     pageConfiguration.applicationCacheStorage = &WebProcess::singleton().applicationCacheStorage();
443     pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID());
444     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
445     pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID());
446     pageConfiguration.userContentProvider = m_userContentController.ptr();
447     pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
448
449 #if ENABLE(APPLE_PAY)
450     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinator(*this);
451 #endif
452
453 #if ENABLE(WEB_AUTHN)
454     pageConfiguration.authenticatorCoordinatorClient = std::make_unique<WebAuthenticatorCoordinator>(*this);
455 #endif
456
457 #if ENABLE(APPLICATION_MANIFEST)
458     pageConfiguration.applicationManifest = parameters.applicationManifest;
459 #endif
460
461     m_page = std::make_unique<Page>(WTFMove(pageConfiguration));
462     updatePreferences(parameters.store);
463
464     m_drawingArea = DrawingArea::create(*this, parameters);
465     m_drawingArea->setPaintingEnabled(false);
466     m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
467
468 #if ENABLE(ASYNC_SCROLLING)
469     m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
470     if (!m_drawingArea->supportsAsyncScrolling())
471         m_useAsyncScrolling = false;
472     m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
473 #endif
474
475     m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
476     m_drawingArea->updatePreferences(parameters.store);
477
478     setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
479
480 #if ENABLE(GEOLOCATION)
481     WebCore::provideGeolocationTo(m_page.get(), *new WebGeolocationClient(*this));
482 #endif
483 #if ENABLE(NOTIFICATIONS)
484     WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
485 #endif
486 #if ENABLE(MEDIA_STREAM)
487     WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this));
488 #endif
489
490     m_page->setControlledByAutomation(parameters.controlledByAutomation);
491
492 #if ENABLE(REMOTE_INSPECTOR)
493     m_page->setRemoteInspectionAllowed(parameters.allowsRemoteInspection);
494     m_page->setRemoteInspectionNameOverride(parameters.remoteInspectionNameOverride);
495 #endif
496
497     m_page->setCanStartMedia(false);
498     m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
499
500     m_page->setGroupName(m_pageGroup->identifier());
501     m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
502     m_page->setUserInterfaceLayoutDirection(m_userInterfaceLayoutDirection);
503 #if PLATFORM(IOS_FAMILY)
504     m_page->setTextAutosizingWidth(parameters.textAutosizingWidth);
505 #endif
506
507     platformInitialize();
508
509     setUseFixedLayout(parameters.useFixedLayout);
510
511     setDrawsBackground(parameters.drawsBackground);
512
513     setUnderlayColor(parameters.underlayColor);
514
515     setPaginationMode(parameters.paginationMode);
516     setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
517     setPageLength(parameters.pageLength);
518     setGapBetweenPages(parameters.gapBetweenPages);
519     setPaginationLineGridEnabled(parameters.paginationLineGridEnabled);
520 #if PLATFORM(MAC)
521     setUseSystemAppearance(parameters.useSystemAppearance);
522     setUseDarkAppearance(parameters.useDarkAppearance);
523 #endif
524     // If the page is created off-screen, its visibilityState should be prerender.
525     m_page->setActivityState(m_activityState);
526     if (!isVisible())
527         m_page->setIsPrerender();
528
529     updateIsInWindow(true);
530
531     setViewLayoutSize(parameters.viewLayoutSize);
532     setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
533     setViewportSizeForCSSViewportUnits(parameters.viewportSizeForCSSViewportUnits);
534     
535     setScrollPinningBehavior(parameters.scrollPinningBehavior);
536     if (parameters.scrollbarOverlayStyle)
537         m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
538     else
539         m_scrollbarOverlayStyle = std::optional<ScrollbarOverlayStyle>();
540
541     setTopContentInset(parameters.topContentInset);
542
543     m_userAgent = parameters.userAgent;
544     
545     if (!parameters.itemStates.isEmpty())
546         restoreSessionInternal(parameters.itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
547
548     if (parameters.sessionID.isValid())
549         setSessionID(parameters.sessionID);
550
551     m_drawingArea->setPaintingEnabled(true);
552     
553     setMediaVolume(parameters.mediaVolume);
554
555     setMuted(parameters.muted);
556
557     // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
558     m_page->addLayoutMilestones(DidFirstLayout | DidFirstVisuallyNonEmptyLayout);
559
560     auto& webProcess = WebProcess::singleton();
561     webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
562
563     // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
564     webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
565     webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
566     webProcess.addMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID, *this);
567 #if ENABLE(FULLSCREEN_API)
568     webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
569 #endif
570
571 #ifndef NDEBUG
572     webPageCounter.increment();
573 #endif
574
575 #if ENABLE(ASYNC_SCROLLING)
576     if (m_useAsyncScrolling)
577         webProcess.eventDispatcher().addScrollingTreeForPage(this);
578 #endif
579
580     for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
581         m_mimeTypesWithCustomContentProviders.add(mimeType);
582
583
584 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
585     if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
586         m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
587 #endif
588     m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
589     
590     if (parameters.viewScaleFactor != 1)
591         scaleView(parameters.viewScaleFactor);
592
593     m_page->addLayoutMilestones(parameters.observedLayoutMilestones);
594
595 #if PLATFORM(COCOA)
596     m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
597     setSmartInsertDeleteEnabled(parameters.smartInsertDeleteEnabled);
598 #endif
599
600 #if ENABLE(SERVICE_WORKER)
601     if (parameters.hasRegisteredServiceWorkers)
602         ServiceWorkerProvider::singleton().setMayHaveRegisteredServiceWorkers();
603 #endif
604
605     m_needsFontAttributes = parameters.needsFontAttributes;
606
607 #if ENABLE(WEB_RTC)
608     if (!parameters.iceCandidateFilteringEnabled)
609         disableICECandidateFiltering();
610 #if USE(LIBWEBRTC)
611     if (parameters.enumeratingAllNetworkInterfacesEnabled)
612         enableEnumeratingAllNetworkInterfaces();
613 #endif
614 #endif
615
616     for (auto iterator : parameters.urlSchemeHandlers)
617         registerURLSchemeHandler(iterator.value, iterator.key);
618
619     m_userContentController->addUserContentWorlds(parameters.userContentWorlds);
620     m_userContentController->addUserScripts(WTFMove(parameters.userScripts), InjectUserScriptImmediately::No);
621     m_userContentController->addUserStyleSheets(parameters.userStyleSheets);
622     m_userContentController->addUserScriptMessageHandlers(parameters.messageHandlers);
623 #if ENABLE(CONTENT_EXTENSIONS)
624     m_userContentController->addContentRuleLists(parameters.contentRuleLists);
625 #endif
626
627 #if PLATFORM(IOS_FAMILY)
628     setViewportConfigurationViewLayoutSize(parameters.viewportConfigurationViewLayoutSize, parameters.viewportConfigurationLayoutSizeScaleFactor);
629     setMaximumUnobscuredSize(parameters.maximumUnobscuredSize);
630 #endif
631 }
632
633 #if ENABLE(WEB_RTC)
634 void WebPage::disableICECandidateFiltering()
635 {
636     m_page->disableICECandidateFiltering();
637 }
638
639 void WebPage::enableICECandidateFiltering()
640 {
641     m_page->enableICECandidateFiltering();
642 }
643
644 #if USE(LIBWEBRTC)
645 void WebPage::disableEnumeratingAllNetworkInterfaces()
646 {
647     m_page->libWebRTCProvider().disableEnumeratingAllNetworkInterfaces();
648 }
649
650 void WebPage::enableEnumeratingAllNetworkInterfaces()
651 {
652     m_page->libWebRTCProvider().enableEnumeratingAllNetworkInterfaces();
653 }
654 #endif
655 #endif
656
657 void WebPage::reinitializeWebPage(WebPageCreationParameters&& parameters)
658 {
659     ASSERT(m_drawingArea);
660
661     setSize(parameters.viewSize);
662
663     if (m_shouldResetDrawingArea) {
664         // Make sure we destroy the previous drawing area before constructing the new one as DrawingArea registers / unregisters
665         // itself as an IPC::MesssageReceiver in its constructor / destructor.
666         m_drawingArea = nullptr;
667         m_shouldResetDrawingArea = false;
668
669         m_drawingArea = DrawingArea::create(*this, parameters);
670         m_drawingArea->setPaintingEnabled(false);
671         m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument);
672         m_drawingArea->updatePreferences(parameters.store);
673         m_drawingArea->setPaintingEnabled(true);
674 #if PLATFORM(MAC)
675         m_shouldAttachDrawingAreaOnPageTransition = parameters.shouldDelayAttachingDrawingArea;
676 #endif
677     }
678
679     setViewLayoutSize(parameters.viewLayoutSize);
680
681     if (m_activityState != parameters.activityState)
682         setActivityState(parameters.activityState, ActivityStateChangeAsynchronous, Vector<CallbackID>());
683     if (m_layerHostingMode != parameters.layerHostingMode)
684         setLayerHostingMode(parameters.layerHostingMode);
685 }
686
687 void WebPage::updateThrottleState()
688 {
689     bool isActive = m_activityState.containsAny({ ActivityState::IsLoading, ActivityState::IsAudible, ActivityState::IsCapturingMedia, ActivityState::WindowIsActive });
690     bool isVisuallyIdle = m_activityState.contains(ActivityState::IsVisuallyIdle);
691     bool pageSuppressed = m_processSuppressionEnabled && !isActive && isVisuallyIdle;
692
693 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
694     if (!pageSuppressed) {
695         // App nap must be manually enabled when not running the NSApplication run loop.
696         static std::once_flag onceKey;
697         std::call_once(onceKey, [] {
698             __CFRunLoopSetOptionsReason(__CFRunLoopOptionsEnableAppNap, CFSTR("Finished checkin as application - enable app nap"));
699         });
700     }
701 #endif
702     // The UserActivity keeps the processes runnable. So if the page should be suppressed, stop the activity.
703     // If the page should not be supressed, start it.
704     if (pageSuppressed)
705         m_userActivityHysteresis.stop();
706     else
707         m_userActivityHysteresis.start();
708 }
709
710 void WebPage::updateUserActivity()
711 {
712     if (m_userActivityHysteresis.state() == PAL::HysteresisState::Started)
713         m_userActivity.start();
714     else
715         m_userActivity.stop();
716 }
717
718 WebPage::~WebPage()
719 {
720     ASSERT(!m_page);
721
722     auto& webProcess = WebProcess::singleton();
723 #if ENABLE(ASYNC_SCROLLING)
724     if (m_useAsyncScrolling)
725         webProcess.eventDispatcher().removeScrollingTreeForPage(this);
726 #endif
727
728     platformDetach();
729     
730     m_sandboxExtensionTracker.invalidate();
731
732     for (auto* pluginView : m_pluginViews)
733         pluginView->webPageDestroyed();
734
735 #if !PLATFORM(IOS_FAMILY)
736     if (m_headerBanner)
737         m_headerBanner->detachFromPage();
738     if (m_footerBanner)
739         m_footerBanner->detachFromPage();
740 #endif // !PLATFORM(IOS_FAMILY)
741
742     webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
743
744     // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
745     webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
746     webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
747     webProcess.removeMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID);
748 #if ENABLE(FULLSCREEN_API)
749     webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
750 #endif
751
752 #ifndef NDEBUG
753     webPageCounter.decrement();
754 #endif
755     
756 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
757     if (m_playbackSessionManager)
758         m_playbackSessionManager->invalidate();
759
760     if (m_videoFullscreenManager)
761         m_videoFullscreenManager->invalidate();
762 #endif
763 }
764
765 IPC::Connection* WebPage::messageSenderConnection()
766 {
767     return WebProcess::singleton().parentProcessConnection();
768 }
769
770 uint64_t WebPage::messageSenderDestinationID()
771 {
772     return pageID();
773 }
774
775 #if ENABLE(CONTEXT_MENUS)
776 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>&& contextMenuClient)
777 {
778     if (!contextMenuClient) {
779         m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
780         return;
781     }
782
783     m_contextMenuClient = WTFMove(contextMenuClient);
784 }
785 #endif
786
787 void WebPage::setInjectedBundleEditorClient(std::unique_ptr<API::InjectedBundle::EditorClient>&& editorClient)
788 {
789     if (!editorClient) {
790         m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
791         return;
792     }
793
794     m_editorClient = WTFMove(editorClient);
795 }
796
797 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>&& formClient)
798 {
799     if (!formClient) {
800         m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
801         return;
802     }
803
804     m_formClient = WTFMove(formClient);
805 }
806
807 void WebPage::setInjectedBundlePageLoaderClient(std::unique_ptr<API::InjectedBundle::PageLoaderClient>&& loaderClient)
808 {
809     if (!loaderClient) {
810         m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
811         return;
812     }
813
814     m_loaderClient = WTFMove(loaderClient);
815
816     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
817     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
818     // for backwards compatibility.
819     if (auto milestones = m_loaderClient->layoutMilestones())
820         listenForLayoutMilestones(milestones);
821 }
822
823 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
824 {
825     m_policyClient.initialize(client);
826 }
827
828 void WebPage::setInjectedBundleResourceLoadClient(std::unique_ptr<API::InjectedBundle::ResourceLoadClient>&& client)
829 {
830     if (!m_resourceLoadClient)
831         m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
832     else
833         m_resourceLoadClient = WTFMove(client);
834 }
835
836 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>&& uiClient)
837 {
838     if (!uiClient) {
839         m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
840         return;
841     }
842
843     m_uiClient = WTFMove(uiClient);
844 }
845
846 #if ENABLE(FULLSCREEN_API)
847 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
848 {
849     m_fullScreenClient.initialize(client);
850 }
851 #endif
852
853 #if ENABLE(NETSCAPE_PLUGIN_API)
854 RefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
855 {
856     String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
857     String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
858
859 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
860     HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
861     unsigned pluginArea = 0;
862     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
863 #else
864     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
865 #endif
866
867     bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
868
869     uint64_t pluginProcessToken;
870     uint32_t pluginLoadPolicy;
871     String unavailabilityDescription;
872     bool isUnsupported;
873     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, isUnsupported)))
874         return nullptr;
875
876     PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
877     bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
878
879     if (isUnsupported || isBlockedPlugin || !pluginProcessToken) {
880 #if ENABLE(PDFKIT_PLUGIN)
881         String path = parameters.url.path();
882         if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWithIgnoringASCIICase(".pdf") || path.endsWithIgnoringASCIICase(".ps")))))
883             return PDFPlugin::create(*frame);
884 #endif
885     }
886
887     if (isUnsupported) {
888         pluginElement->setReplacement(RenderEmbeddedObject::UnsupportedPlugin, unavailabilityDescription);
889         return nullptr;
890     }
891
892     if (isBlockedPlugin) {
893         bool isReplacementObscured = pluginElement->setReplacement(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
894         send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, isReplacementObscured));
895         return nullptr;
896     }
897
898     if (!pluginProcessToken)
899         return nullptr;
900
901     bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
902     return PluginProxy::create(pluginProcessToken, isRestartedProcess);
903 }
904 #endif // ENABLE(NETSCAPE_PLUGIN_API)
905
906 #if ENABLE(WEBGL) && !PLATFORM(MAC)
907 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const URL&)
908 {
909     return WebGLAllowCreation;
910 }
911
912 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const URL&)
913 {
914     return WebGLAllowCreation;
915 }
916 #endif
917
918 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
919 {
920     Frame& frame = m_page->focusController().focusedOrMainFrame();
921
922     EditorState result;
923
924     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
925         if (!pluginView->getSelectionString().isNull()) {
926             result.selectionIsNone = false;
927             result.selectionIsRange = true;
928             result.isInPlugin = true;
929             return result;
930         }
931     }
932
933     const VisibleSelection& selection = frame.selection().selection();
934     const Editor& editor = frame.editor();
935
936     result.selectionIsNone = selection.isNone();
937     result.selectionIsRange = selection.isRange();
938     result.isContentEditable = selection.isContentEditable();
939     result.isContentRichlyEditable = selection.isContentRichlyEditable();
940     result.isInPasswordField = selection.isInPasswordField();
941     result.hasComposition = editor.hasComposition();
942     result.shouldIgnoreSelectionChanges = editor.ignoreSelectionChanges();
943
944     if (auto* document = frame.document())
945         result.originIdentifierForPasteboard = document->originIdentifierForPasteboard();
946
947     bool canIncludePostLayoutData = frame.view() && !frame.view()->needsLayout();
948     if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && canIncludePostLayoutData) {
949         auto& postLayoutData = result.postLayoutData();
950         postLayoutData.canCut = editor.canCut();
951         postLayoutData.canCopy = editor.canCopy();
952         postLayoutData.canPaste = editor.canPaste();
953
954         if (m_needsFontAttributes)
955             postLayoutData.fontAttributes = editor.fontAttributesAtSelectionStart();
956
957 #if PLATFORM(COCOA)
958         if (result.isContentEditable && !selection.isNone()) {
959             if (auto editingStyle = EditingStyle::styleAtSelectionStart(selection)) {
960                 if (editingStyle->hasStyle(CSSPropertyFontWeight, "bold"))
961                     postLayoutData.typingAttributes |= AttributeBold;
962
963                 if (editingStyle->hasStyle(CSSPropertyFontStyle, "italic") || editingStyle->hasStyle(CSSPropertyFontStyle, "oblique"))
964                     postLayoutData.typingAttributes |= AttributeItalics;
965
966                 if (editingStyle->hasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline"))
967                     postLayoutData.typingAttributes |= AttributeUnderline;
968
969                 if (auto* styleProperties = editingStyle->style()) {
970                     bool isLeftToRight = styleProperties->propertyAsValueID(CSSPropertyDirection) == CSSValueLtr;
971                     switch (styleProperties->propertyAsValueID(CSSPropertyTextAlign)) {
972                     case CSSValueRight:
973                     case CSSValueWebkitRight:
974                         postLayoutData.textAlignment = RightAlignment;
975                         break;
976                     case CSSValueLeft:
977                     case CSSValueWebkitLeft:
978                         postLayoutData.textAlignment = LeftAlignment;
979                         break;
980                     case CSSValueCenter:
981                     case CSSValueWebkitCenter:
982                         postLayoutData.textAlignment = CenterAlignment;
983                         break;
984                     case CSSValueJustify:
985                         postLayoutData.textAlignment = JustifiedAlignment;
986                         break;
987                     case CSSValueStart:
988                         postLayoutData.textAlignment = isLeftToRight ? LeftAlignment : RightAlignment;
989                         break;
990                     case CSSValueEnd:
991                         postLayoutData.textAlignment = isLeftToRight ? RightAlignment : LeftAlignment;
992                         break;
993                     default:
994                         break;
995                     }
996                     if (auto textColor = styleProperties->propertyAsColor(CSSPropertyColor))
997                         postLayoutData.textColor = *textColor;
998                 }
999             }
1000
1001             if (auto* enclosingListElement = enclosingList(selection.start().containerNode())) {
1002                 if (is<HTMLUListElement>(*enclosingListElement))
1003                     postLayoutData.enclosingListType = UnorderedList;
1004                 else if (is<HTMLOListElement>(*enclosingListElement))
1005                     postLayoutData.enclosingListType = OrderedList;
1006                 else
1007                     ASSERT_NOT_REACHED();
1008             }
1009         }
1010 #endif
1011     }
1012
1013     platformEditorState(frame, result, shouldIncludePostLayoutData);
1014
1015     m_lastEditorStateWasContentEditable = result.isContentEditable ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1016
1017     return result;
1018 }
1019
1020 void WebPage::changeFontAttributes(WebCore::FontAttributeChanges&& changes)
1021 {
1022     auto& frame = m_page->focusController().focusedOrMainFrame();
1023     if (frame.selection().selection().isContentEditable())
1024         frame.editor().applyStyleToSelection(changes.createEditingStyle(), changes.editAction(), Editor::ColorFilterMode::InvertColor);
1025 }
1026
1027 void WebPage::changeFont(WebCore::FontChanges&& changes)
1028 {
1029     auto& frame = m_page->focusController().focusedOrMainFrame();
1030     if (frame.selection().selection().isContentEditable())
1031         frame.editor().applyStyleToSelection(changes.createEditingStyle(), EditAction::SetFont, Editor::ColorFilterMode::InvertColor);
1032 }
1033
1034 void WebPage::executeEditCommandWithCallback(const String& commandName, const String& argument, CallbackID callbackID)
1035 {
1036     executeEditCommand(commandName, argument);
1037     send(Messages::WebPageProxy::VoidCallback(callbackID));
1038 }
1039
1040 void WebPage::updateEditorStateAfterLayoutIfEditabilityChanged()
1041 {
1042     // FIXME: We should update EditorStateIsContentEditable to track whether the state is richly
1043     // editable or plainttext-only.
1044     if (m_lastEditorStateWasContentEditable == EditorStateIsContentEditable::Unset)
1045         return;
1046
1047     Frame& frame = m_page->focusController().focusedOrMainFrame();
1048     EditorStateIsContentEditable editorStateIsContentEditable = frame.selection().selection().isContentEditable() ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1049     if (m_lastEditorStateWasContentEditable != editorStateIsContentEditable)
1050         sendPartialEditorStateAndSchedulePostLayoutUpdate();
1051 }
1052
1053 String WebPage::renderTreeExternalRepresentation() const
1054 {
1055     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
1056 }
1057
1058 String WebPage::renderTreeExternalRepresentationForPrinting() const
1059 {
1060     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
1061 }
1062
1063 uint64_t WebPage::renderTreeSize() const
1064 {
1065     if (!m_page)
1066         return 0;
1067     return m_page->renderTreeSize();
1068 }
1069
1070 void WebPage::setTracksRepaints(bool trackRepaints)
1071 {
1072     if (FrameView* view = mainFrameView())
1073         view->setTracksRepaints(trackRepaints);
1074 }
1075
1076 bool WebPage::isTrackingRepaints() const
1077 {
1078     if (FrameView* view = mainFrameView())
1079         return view->isTrackingRepaints();
1080
1081     return false;
1082 }
1083
1084 void WebPage::resetTrackedRepaints()
1085 {
1086     if (FrameView* view = mainFrameView())
1087         view->resetTrackedRepaints();
1088 }
1089
1090 Ref<API::Array> WebPage::trackedRepaintRects()
1091 {
1092     FrameView* view = mainFrameView();
1093     if (!view)
1094         return API::Array::create();
1095
1096     Vector<RefPtr<API::Object>> repaintRects;
1097     repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
1098
1099     for (const auto& repaintRect : view->trackedRepaintRects())
1100         repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
1101
1102     return API::Array::create(WTFMove(repaintRects));
1103 }
1104
1105 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
1106 {
1107     if (!is<PluginDocument>(frame.document()))
1108         return nullptr;
1109
1110     auto& pluginDocument = downcast<PluginDocument>(*frame.document());
1111     if (pluginDocument.focusedElement() != pluginDocument.pluginElement())
1112         return nullptr;
1113
1114     return pluginViewForFrame(&frame);
1115 }
1116
1117 PluginView* WebPage::pluginViewForFrame(Frame* frame)
1118 {
1119     if (!frame || !is<PluginDocument>(frame->document()))
1120         return nullptr;
1121
1122     auto& document = downcast<PluginDocument>(*frame->document());
1123     return static_cast<PluginView*>(document.pluginWidget());
1124 }
1125
1126 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
1127 {
1128     Frame& frame = m_page->focusController().focusedOrMainFrame();
1129
1130     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
1131         pluginView->handleEditingCommand(commandName, argument);
1132         return;
1133     }
1134     
1135     frame.editor().command(commandName).execute(argument);
1136 }
1137
1138 void WebPage::setEditable(bool editable)
1139 {
1140     m_page->setEditable(editable);
1141     m_page->setTabKeyCyclesThroughElements(!editable);
1142     Frame& frame = m_page->focusController().focusedOrMainFrame();
1143     if (editable) {
1144         frame.editor().applyEditingStyleToBodyElement();
1145         // If the page is made editable and the selection is empty, set it to something.
1146         if (frame.selection().isNone())
1147             frame.selection().setSelectionFromNone();
1148     }
1149 }
1150
1151 bool WebPage::isEditingCommandEnabled(const String& commandName)
1152 {
1153     Frame& frame = m_page->focusController().focusedOrMainFrame();
1154
1155     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1156         return pluginView->isEditingCommandEnabled(commandName);
1157     
1158     Editor::Command command = frame.editor().command(commandName);
1159     return command.isSupported() && command.isEnabled();
1160 }
1161     
1162 void WebPage::clearMainFrameName()
1163 {
1164     if (Frame* frame = mainFrame())
1165         frame->tree().clearName();
1166 }
1167
1168 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
1169 {
1170     m_drawingArea->setRootCompositingLayer(layer);
1171 }
1172
1173 void WebPage::exitAcceleratedCompositingMode()
1174 {
1175     m_drawingArea->setRootCompositingLayer(0);
1176 }
1177
1178 void WebPage::close()
1179 {
1180     if (m_isClosed)
1181         return;
1182
1183     WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::RemoveStorageAccessForAllFramesOnPage(sessionID(), m_pageID), 0);
1184     
1185     m_isClosed = true;
1186
1187     // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1188     if (!mainWebFrame()->url().isEmpty())
1189         reportUsedFeatures();
1190
1191     if (WebProcess::singleton().injectedBundle())
1192         WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1193
1194     if (m_inspector) {
1195         m_inspector->disconnectFromPage();
1196         m_inspector = nullptr;
1197     }
1198
1199     m_page->inspectorController().disconnectAllFrontends();
1200
1201 #if ENABLE(MEDIA_STREAM)
1202     m_userMediaPermissionRequestManager = nullptr;
1203 #endif
1204
1205 #if ENABLE(FULLSCREEN_API)
1206     m_fullScreenManager = nullptr;
1207 #endif
1208
1209     if (m_activePopupMenu) {
1210         m_activePopupMenu->disconnectFromPage();
1211         m_activePopupMenu = nullptr;
1212     }
1213
1214     if (m_activeOpenPanelResultListener) {
1215         m_activeOpenPanelResultListener->disconnectFromPage();
1216         m_activeOpenPanelResultListener = nullptr;
1217     }
1218
1219 #if ENABLE(INPUT_TYPE_COLOR)
1220     if (m_activeColorChooser) {
1221         m_activeColorChooser->disconnectFromPage();
1222         m_activeColorChooser = nullptr;
1223     }
1224 #endif
1225
1226 #if PLATFORM(GTK)
1227     if (m_printOperation) {
1228         m_printOperation->disconnectFromPage();
1229         m_printOperation = nullptr;
1230     }
1231 #endif
1232
1233 #if ENABLE(VIDEO) && USE(GSTREAMER)
1234     if (m_installMediaPluginsCallback) {
1235         m_installMediaPluginsCallback->invalidate();
1236         m_installMediaPluginsCallback = nullptr;
1237     }
1238 #endif
1239
1240     m_sandboxExtensionTracker.invalidate();
1241
1242 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1243     m_determinePrimarySnapshottedPlugInTimer.stop();
1244 #endif
1245
1246 #if ENABLE(CONTEXT_MENUS)
1247     m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1248 #endif
1249     m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
1250     m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1251     m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
1252     m_policyClient.initialize(0);
1253     m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
1254     m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1255 #if ENABLE(FULLSCREEN_API)
1256     m_fullScreenClient.initialize(0);
1257 #endif
1258
1259     m_printContext = nullptr;
1260     m_mainFrame->coreFrame()->loader().detachFromParent();
1261     m_drawingArea = nullptr;
1262
1263     DeferredPageDestructor::createDeferredPageDestructor(WTFMove(m_page), this);
1264
1265     bool isRunningModal = m_isRunningModal;
1266     m_isRunningModal = false;
1267
1268     // The WebPage can be destroyed by this call.
1269     WebProcess::singleton().removeWebPage(m_pageID);
1270
1271     WebProcess::singleton().updateActivePages();
1272
1273     if (isRunningModal)
1274         RunLoop::main().stop();
1275 }
1276
1277 void WebPage::tryClose()
1278 {
1279     SendStopResponsivenessTimer stopper;
1280
1281     if (!corePage()->userInputBridge().tryClosePage())
1282         return;
1283
1284     send(Messages::WebPageProxy::ClosePage(true));
1285 }
1286
1287 void WebPage::sendClose()
1288 {
1289     send(Messages::WebPageProxy::ClosePage(false));
1290 }
1291
1292 void WebPage::loadURLInFrame(WebCore::URL&& url, uint64_t frameID)
1293 {
1294     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1295     if (!frame)
1296         return;
1297
1298     frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(url), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1299 }
1300
1301 #if !PLATFORM(COCOA)
1302 void WebPage::platformDidReceiveLoadParameters(const LoadParameters& loadParameters)
1303 {
1304 }
1305 #endif
1306
1307 void WebPage::loadRequest(LoadParameters&& loadParameters)
1308 {
1309     SendStopResponsivenessTimer stopper;
1310
1311     m_pendingNavigationID = loadParameters.navigationID;
1312
1313     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), WTFMove(loadParameters.sandboxExtensionHandle));
1314
1315     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1316     // to all the client to set up any needed state.
1317     m_loaderClient->willLoadURLRequest(*this, loadParameters.request, WebProcess::singleton().transformHandlesToObjects(loadParameters.userData.object()).get());
1318
1319     platformDidReceiveLoadParameters(loadParameters);
1320
1321     // Initate the load in WebCore.
1322     FrameLoadRequest frameLoadRequest { *m_mainFrame->coreFrame(), loadParameters.request, ShouldOpenExternalURLsPolicy::ShouldNotAllow };
1323     ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(loadParameters.shouldOpenExternalURLsPolicy);
1324     frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1325     frameLoadRequest.setShouldTreatAsContinuingLoad(loadParameters.shouldTreatAsContinuingLoad);
1326     frameLoadRequest.setLockHistory(loadParameters.lockHistory);
1327     frameLoadRequest.setlockBackForwardList(loadParameters.lockBackForwardList);
1328     frameLoadRequest.setClientRedirectSourceForHistory(loadParameters.clientRedirectSourceForHistory);
1329
1330     corePage()->userInputBridge().loadRequest(WTFMove(frameLoadRequest));
1331
1332     ASSERT(!m_pendingNavigationID);
1333 }
1334
1335 void WebPage::loadDataImpl(uint64_t navigationID, Ref<SharedBuffer>&& sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData)
1336 {
1337     SendStopResponsivenessTimer stopper;
1338
1339     m_pendingNavigationID = navigationID;
1340
1341     ResourceRequest request(baseURL);
1342     ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1343     SubstituteData substituteData(WTFMove(sharedBuffer), unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1344
1345     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1346     // to all the client to set up any needed state.
1347     m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1348
1349     // Initate the load in WebCore.
1350     m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(*m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData));
1351 }
1352
1353 void WebPage::loadData(LoadParameters&& loadParameters)
1354 {
1355     platformDidReceiveLoadParameters(loadParameters);
1356
1357     auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1358     URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1359     loadDataImpl(loadParameters.navigationID, WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, URL(), loadParameters.userData);
1360 }
1361
1362 void WebPage::loadAlternateHTML(const LoadParameters& loadParameters)
1363 {
1364     platformDidReceiveLoadParameters(loadParameters);
1365
1366     URL baseURL = loadParameters.baseURLString.isEmpty() ? blankURL() : URL(URL(), loadParameters.baseURLString);
1367     URL unreachableURL = loadParameters.unreachableURLString.isEmpty() ? URL() : URL(URL(), loadParameters.unreachableURLString);
1368     URL provisionalLoadErrorURL = loadParameters.provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), loadParameters.provisionalLoadErrorURLString);
1369     auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1370     m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);    
1371     loadDataImpl(loadParameters.navigationID, WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, unreachableURL, loadParameters.userData);
1372     m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1373 }
1374
1375 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1376 {
1377     Frame* mainFrame = m_mainFrame->coreFrame();
1378     Document* mainFrameDocument = mainFrame->document();
1379     if (!mainFrameDocument)
1380         return;
1381
1382     const int singleClick = 1;
1383     // FIXME: Set modifier keys.
1384     // FIXME: This should probably set IsSimulated::Yes.
1385     RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes, Event::IsComposed::Yes,
1386         MonotonicTime::now(), nullptr, singleClick, screenPoint, documentPoint, { }, { }, 0, 0, nullptr, 0, WebCore::NoTap, nullptr);
1387
1388     mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1389 }
1390
1391 void WebPage::stopLoadingFrame(uint64_t frameID)
1392 {
1393     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1394     if (!frame)
1395         return;
1396
1397     corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1398 }
1399
1400 void WebPage::stopLoading()
1401 {
1402     SendStopResponsivenessTimer stopper;
1403
1404     corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1405 }
1406
1407 bool WebPage::defersLoading() const
1408 {
1409     return m_page->defersLoading();
1410 }
1411
1412 void WebPage::setDefersLoading(bool defersLoading)
1413 {
1414     m_page->setDefersLoading(defersLoading);
1415 }
1416
1417 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, SandboxExtension::Handle&& sandboxExtensionHandle)
1418 {
1419     SendStopResponsivenessTimer stopper;
1420
1421     ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1422     m_pendingNavigationID = navigationID;
1423
1424     m_sandboxExtensionTracker.beginReload(m_mainFrame.get(), WTFMove(sandboxExtensionHandle));
1425     corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1426
1427     if (m_pendingNavigationID) {
1428         // This can happen if FrameLoader::reload() returns early because the document URL is empty.
1429         // The reload does nothing so we need to reset the pending navigation. See webkit.org/b/153210.
1430         m_pendingNavigationID = 0;
1431     }
1432 }
1433
1434 void WebPage::goToBackForwardItem(uint64_t navigationID, const BackForwardItemIdentifier& backForwardItemID, FrameLoadType backForwardType, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad)
1435 {
1436     SendStopResponsivenessTimer stopper;
1437
1438     ASSERT(isBackForwardLoadType(backForwardType));
1439
1440     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1441     ASSERT(item);
1442     if (!item)
1443         return;
1444
1445     LOG(Loading, "In WebProcess pid %i, WebPage %" PRIu64 " is navigating to back/forward URL %s", getCurrentProcessID(), m_pageID, item->url().string().utf8().data());
1446
1447     ASSERT(!m_pendingNavigationID);
1448     m_pendingNavigationID = navigationID;
1449
1450     m_page->goToItem(*item, backForwardType, shouldTreatAsContinuingLoad);
1451 }
1452
1453 void WebPage::tryRestoreScrollPosition()
1454 {
1455     m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1456 }
1457
1458 void WebPage::layoutIfNeeded()
1459 {
1460     if (m_mainFrame->coreFrame()->view())
1461         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1462 }
1463
1464 WebPage* WebPage::fromCorePage(Page* page)
1465 {
1466     return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1467 }
1468
1469 void WebPage::setSize(const WebCore::IntSize& viewSize)
1470 {
1471     if (m_viewSize == viewSize)
1472         return;
1473
1474     m_viewSize = viewSize;
1475     FrameView* view = m_page->mainFrame().view();
1476     view->resize(viewSize);
1477     m_drawingArea->setNeedsDisplay();
1478
1479 #if USE(COORDINATED_GRAPHICS)
1480     if (view->useFixedLayout())
1481         sendViewportAttributesChanged(m_page->viewportArguments());
1482 #endif
1483 }
1484
1485 #if USE(COORDINATED_GRAPHICS)
1486 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1487 {
1488     FrameView* view = m_page->mainFrame().view();
1489     ASSERT(view && view->useFixedLayout());
1490
1491     // Viewport properties have no impact on zero sized fixed viewports.
1492     if (m_viewSize.isEmpty())
1493         return;
1494
1495     // Recalculate the recommended layout size, when the available size (device pixel) changes.
1496     Settings& settings = m_page->settings();
1497
1498     int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1499
1500     // If unset  we use the viewport dimensions. This fits with the behavior of desktop browsers.
1501     int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1502     int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1503
1504     ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1505
1506     // If no layout was done yet set contentFixedOrigin to (0,0).
1507     IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1508
1509     // Put the width and height to the viewport width and height. In css units however.
1510     // Use FloatSize to avoid truncated values during scale.
1511     FloatSize contentFixedSize = m_viewSize;
1512
1513 #if ENABLE(CSS_DEVICE_ADAPTATION)
1514     // CSS viewport descriptors might be applied to already affected viewport size
1515     // if the page enables/disables stylesheets, so need to keep initial viewport size.
1516     view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1517 #endif
1518
1519     contentFixedSize.scale(1 / attr.initialScale);
1520     view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1521
1522     attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1523
1524     // This also takes care of the relayout.
1525     setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1526
1527 #if USE(COORDINATED_GRAPHICS_THREADED)
1528     m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1529 #else
1530     send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1531 #endif
1532 }
1533 #endif
1534
1535 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1536 {
1537     FrameView* frameView = m_page->mainFrame().view();
1538
1539     ScrollPosition scrollPosition = frameView->scrollPosition();
1540     ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1541
1542     // If the current scroll position in a direction is the max scroll position 
1543     // we don't want to scroll at all.
1544     IntSize newScrollOffset;
1545     if (scrollPosition.x() < maximumScrollPosition.x())
1546         newScrollOffset.setWidth(scrollOffset.width());
1547     if (scrollPosition.y() < maximumScrollPosition.y())
1548         newScrollOffset.setHeight(scrollOffset.height());
1549
1550     if (newScrollOffset.isZero())
1551         return;
1552
1553     frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1554 }
1555
1556 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1557 {
1558 #if PLATFORM(MAC)
1559     auto* document = m_mainFrame->coreFrame()->document();
1560     LocalDefaultSystemAppearance localAppearance(document ? document->useDarkAppearance() : false);
1561 #endif
1562
1563     GraphicsContextStateSaver stateSaver(graphicsContext);
1564     graphicsContext.clip(rect);
1565
1566     m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1567 }
1568
1569 double WebPage::textZoomFactor() const
1570 {
1571     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1572     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1573         if (pluginView->handlesPageScaleFactor())
1574             return pluginView->pageScaleFactor();
1575         return pageScaleFactor();
1576     }
1577
1578     Frame* frame = m_mainFrame->coreFrame();
1579     if (!frame)
1580         return 1;
1581     return frame->textZoomFactor();
1582 }
1583
1584 void WebPage::setTextZoomFactor(double zoomFactor)
1585 {
1586     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1587     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1588         if (pluginView->handlesPageScaleFactor())
1589             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1590         else
1591             scalePage(zoomFactor, IntPoint());
1592         return;
1593     }
1594
1595     Frame* frame = m_mainFrame->coreFrame();
1596     if (!frame)
1597         return;
1598     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1599 }
1600
1601 double WebPage::pageZoomFactor() const
1602 {
1603     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1604     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1605         if (pluginView->handlesPageScaleFactor())
1606             return pluginView->pageScaleFactor();
1607         return pageScaleFactor();
1608     }
1609
1610     Frame* frame = m_mainFrame->coreFrame();
1611     if (!frame)
1612         return 1;
1613     return frame->pageZoomFactor();
1614 }
1615
1616 void WebPage::setPageZoomFactor(double zoomFactor)
1617 {
1618     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1619     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1620         if (pluginView->handlesPageScaleFactor())
1621             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1622         else
1623             scalePage(zoomFactor, IntPoint());
1624         return;
1625     }
1626
1627     Frame* frame = m_mainFrame->coreFrame();
1628     if (!frame)
1629         return;
1630     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1631 }
1632
1633 static void dumpHistoryItem(HistoryItem& item, size_t indent, bool isCurrentItem, StringBuilder& stringBuilder, const String& directoryName)
1634 {
1635     if (isCurrentItem)
1636         stringBuilder.appendLiteral("curr->  ");
1637     else {
1638         for (size_t i = 0; i < indent; ++i)
1639             stringBuilder.append(' ');
1640     }
1641
1642     auto url = item.url();
1643     if (url.protocolIs("file")) {
1644         size_t start = url.string().find(directoryName);
1645         if (start == WTF::notFound)
1646             start = 0;
1647         else
1648             start += directoryName.length();
1649         stringBuilder.appendLiteral("(file test):");
1650         stringBuilder.append(url.string().substring(start));
1651     } else
1652         stringBuilder.append(url);
1653     
1654     auto& target = item.target();
1655     if (target.length()) {
1656         stringBuilder.appendLiteral(" (in frame \"");
1657         stringBuilder.append(target);
1658         stringBuilder.appendLiteral("\")");
1659     }
1660     
1661     if (item.isTargetItem())
1662         stringBuilder.appendLiteral("  **nav target**");
1663     
1664     stringBuilder.append('\n');
1665     
1666     Vector<Ref<HistoryItem>> children;
1667     children.reserveInitialCapacity(item.children().size());
1668     for (auto& child : item.children())
1669         children.uncheckedAppend(child.copyRef());
1670     std::stable_sort(children.begin(), children.end(), [] (auto& a, auto& b) {
1671         return codePointCompare(a->target(), b->target()) < 0;
1672     });
1673     for (auto& child : children)
1674         dumpHistoryItem(child, indent + 4, false, stringBuilder, directoryName);
1675 }
1676
1677 String WebPage::dumpHistoryForTesting(const String& directory)
1678 {
1679     if (!m_page)
1680         return { };
1681
1682     auto& list = m_page->backForward();
1683     
1684     StringBuilder builder;
1685     int begin = -list.backCount();
1686     if (list.itemAtIndex(begin)->url() == blankURL())
1687         ++begin;
1688     for (int i = begin; i <= static_cast<int>(list.forwardCount()); ++i)
1689         dumpHistoryItem(*list.itemAtIndex(i), 8, !i, builder, directory);
1690     return builder.toString();
1691 }
1692
1693 void WebPage::clearHistory()
1694 {
1695     if (!m_page)
1696         return;
1697
1698     static_cast<WebBackForwardListProxy&>(m_page->backForward().client()).clear();
1699 }
1700
1701 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1702 {
1703     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1704     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1705         if (pluginView->handlesPageScaleFactor())
1706             pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1707         else
1708             scalePage(pageZoomFactor, IntPoint());
1709         return;
1710     }
1711
1712     Frame* frame = m_mainFrame->coreFrame();
1713     if (!frame)
1714         return;
1715     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1716 }
1717
1718 void WebPage::windowScreenDidChange(uint32_t displayID)
1719 {
1720     m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1721 }
1722
1723 void WebPage::scalePage(double scale, const IntPoint& origin)
1724 {
1725     double totalScale = scale * viewScaleFactor();
1726     bool willChangeScaleFactor = totalScale != totalScaleFactor();
1727
1728 #if PLATFORM(IOS_FAMILY)
1729     if (willChangeScaleFactor) {
1730         if (!m_inDynamicSizeUpdate)
1731             m_dynamicSizeUpdateHistory.clear();
1732         m_scaleWasSetByUIProcess = false;
1733     }
1734 #endif
1735     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1736     if (pluginView && pluginView->handlesPageScaleFactor()) {
1737         // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1738         // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1739         if (m_page->pageScaleFactor() != 1) {
1740             m_page->setPageScaleFactor(1, origin);
1741             for (auto* pluginView : m_pluginViews)
1742                 pluginView->pageScaleFactorDidChange();
1743         }
1744
1745         pluginView->setPageScaleFactor(totalScale, origin);
1746         return;
1747     }
1748
1749     m_page->setPageScaleFactor(totalScale, origin);
1750
1751     // We can't early return before setPageScaleFactor because the origin might be different.
1752     if (!willChangeScaleFactor)
1753         return;
1754
1755     for (auto* pluginView : m_pluginViews)
1756         pluginView->pageScaleFactorDidChange();
1757
1758 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1759     m_drawingArea->deviceOrPageScaleFactorChanged();
1760 #endif
1761
1762     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1763 }
1764
1765 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1766 {
1767     double totalScale = scale * viewScaleFactor();
1768     if (totalScale == totalScaleFactor())
1769         return;
1770
1771     IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1772     double scaleRatio = scale / pageScaleFactor();
1773     scrollPositionAtNewScale.scale(scaleRatio);
1774     scalePage(scale, scrollPositionAtNewScale);
1775 }
1776
1777 double WebPage::totalScaleFactor() const
1778 {
1779     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1780     if (pluginView && pluginView->handlesPageScaleFactor())
1781         return pluginView->pageScaleFactor();
1782
1783     return m_page->pageScaleFactor();
1784 }
1785
1786 double WebPage::pageScaleFactor() const
1787 {
1788     return totalScaleFactor() / viewScaleFactor();
1789 }
1790
1791 double WebPage::viewScaleFactor() const
1792 {
1793     return m_page->viewScaleFactor();
1794 }
1795
1796 void WebPage::scaleView(double scale)
1797 {
1798     if (viewScaleFactor() == scale)
1799         return;
1800
1801     float pageScale = pageScaleFactor();
1802
1803     IntPoint scrollPositionAtNewScale;
1804     if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1805         double scaleRatio = scale / viewScaleFactor();
1806         scrollPositionAtNewScale = mainFrameView->scrollPosition();
1807         scrollPositionAtNewScale.scale(scaleRatio);
1808     }
1809
1810     m_page->setViewScaleFactor(scale);
1811     scalePage(pageScale, scrollPositionAtNewScale);
1812 }
1813
1814 void WebPage::setDeviceScaleFactor(float scaleFactor)
1815 {
1816     if (scaleFactor == m_page->deviceScaleFactor())
1817         return;
1818
1819     m_page->setDeviceScaleFactor(scaleFactor);
1820
1821     // Tell all our plug-in views that the device scale factor changed.
1822 #if PLATFORM(MAC)
1823     for (auto* pluginView : m_pluginViews)
1824         pluginView->setDeviceScaleFactor(scaleFactor);
1825
1826     updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1827 #endif
1828
1829     if (findController().isShowingOverlay()) {
1830         // We must have updated layout to get the selection rects right.
1831         layoutIfNeeded();
1832         findController().deviceScaleFactorDidChange();
1833     }
1834
1835 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1836     m_drawingArea->deviceOrPageScaleFactorChanged();
1837 #endif
1838 }
1839
1840 float WebPage::deviceScaleFactor() const
1841 {
1842     return m_page->deviceScaleFactor();
1843 }
1844
1845 void WebPage::accessibilitySettingsDidChange()
1846 {
1847     m_page->accessibilitySettingsDidChange();
1848 }
1849
1850 #if ENABLE(ACCESSIBILITY_EVENTS)
1851 void WebPage::updateAccessibilityEventsEnabled(bool enabled)
1852 {
1853     m_page->settings().setAccessibilityEventsEnabled(enabled);
1854 }
1855 #endif
1856
1857 void WebPage::setUseFixedLayout(bool fixed)
1858 {
1859     // Do not overwrite current settings if initially setting it to false.
1860     if (m_useFixedLayout == fixed)
1861         return;
1862     m_useFixedLayout = fixed;
1863
1864 #if !PLATFORM(IOS_FAMILY)
1865     m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1866 #endif
1867
1868     FrameView* view = mainFrameView();
1869     if (!view)
1870         return;
1871
1872     view->setUseFixedLayout(fixed);
1873     if (!fixed)
1874         setFixedLayoutSize(IntSize());
1875
1876     send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1877 }
1878
1879 bool WebPage::setFixedLayoutSize(const IntSize& size)
1880 {
1881     FrameView* view = mainFrameView();
1882     if (!view || view->fixedLayoutSize() == size)
1883         return false;
1884
1885     LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " setFixedLayoutSize " << size);
1886     view->setFixedLayoutSize(size);
1887
1888     send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1889     return true;
1890 }
1891
1892 IntSize WebPage::fixedLayoutSize() const
1893 {
1894     FrameView* view = mainFrameView();
1895     if (!view)
1896         return IntSize();
1897     return view->fixedLayoutSize();
1898 }
1899
1900 void WebPage::disabledAdaptationsDidChange(const OptionSet<DisabledAdaptations>& disabledAdaptations)
1901 {
1902 #if PLATFORM(IOS_FAMILY)
1903     if (m_viewportConfiguration.setDisabledAdaptations(disabledAdaptations))
1904         viewportConfigurationChanged();
1905 #else
1906     UNUSED_PARAM(disabledAdaptations);
1907 #endif
1908 }
1909
1910 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
1911 {
1912 #if PLATFORM(IOS_FAMILY)
1913     if (!m_page->settings().shouldIgnoreMetaViewport() && m_viewportConfiguration.setViewportArguments(viewportArguments))
1914         viewportConfigurationChanged();
1915 #endif
1916
1917 #if USE(COORDINATED_GRAPHICS)
1918     FrameView* view = m_page->mainFrame().view();
1919     if (view && view->useFixedLayout())
1920         sendViewportAttributesChanged(viewportArguments);
1921 #if USE(COORDINATED_GRAPHICS_THREADED)
1922     else
1923         m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
1924 #endif
1925 #endif
1926
1927 #if !PLATFORM(IOS_FAMILY) && !USE(COORDINATED_GRAPHICS)
1928     UNUSED_PARAM(viewportArguments);
1929 #endif
1930 }
1931
1932 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1933 {
1934     if (!m_page)
1935         return;
1936     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1937 }
1938
1939 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1940 {
1941     m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1942 }
1943     
1944 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1945 {
1946     m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1947 }
1948     
1949 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1950 {
1951     m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1952 }
1953
1954 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1955 {
1956     if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1957         m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1958 }
1959
1960 void WebPage::setPaginationMode(uint32_t mode)
1961 {
1962     Pagination pagination = m_page->pagination();
1963     pagination.mode = static_cast<Pagination::Mode>(mode);
1964     m_page->setPagination(pagination);
1965 }
1966
1967 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1968 {
1969     Pagination pagination = m_page->pagination();
1970     pagination.behavesLikeColumns = behavesLikeColumns;
1971     m_page->setPagination(pagination);
1972 }
1973
1974 void WebPage::setPageLength(double pageLength)
1975 {
1976     Pagination pagination = m_page->pagination();
1977     pagination.pageLength = pageLength;
1978     m_page->setPagination(pagination);
1979 }
1980
1981 void WebPage::setGapBetweenPages(double gap)
1982 {
1983     Pagination pagination = m_page->pagination();
1984     pagination.gap = gap;
1985     m_page->setPagination(pagination);
1986 }
1987
1988 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
1989 {
1990     m_page->setPaginationLineGridEnabled(lineGridEnabled);
1991 }
1992
1993 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1994 {
1995     auto& webProcess = WebProcess::singleton();
1996     InjectedBundle* injectedBundle = webProcess.injectedBundle();
1997     if (!injectedBundle)
1998         return;
1999
2000     injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
2001 }
2002
2003 #if !PLATFORM(IOS_FAMILY)
2004
2005 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
2006 {
2007     if (m_headerBanner)
2008         m_headerBanner->detachFromPage();
2009
2010     m_headerBanner = pageBanner;
2011
2012     if (m_headerBanner)
2013         m_headerBanner->addToPage(PageBanner::Header, this);
2014 }
2015
2016 PageBanner* WebPage::headerPageBanner()
2017 {
2018     return m_headerBanner.get();
2019 }
2020
2021 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
2022 {
2023     if (m_footerBanner)
2024         m_footerBanner->detachFromPage();
2025
2026     m_footerBanner = pageBanner;
2027
2028     if (m_footerBanner)
2029         m_footerBanner->addToPage(PageBanner::Footer, this);
2030 }
2031
2032 PageBanner* WebPage::footerPageBanner()
2033 {
2034     return m_footerBanner.get();
2035 }
2036
2037 void WebPage::hidePageBanners()
2038 {
2039     if (m_headerBanner)
2040         m_headerBanner->hide();
2041     if (m_footerBanner)
2042         m_footerBanner->hide();
2043 }
2044
2045 void WebPage::showPageBanners()
2046 {
2047     if (m_headerBanner)
2048         m_headerBanner->showIfHidden();
2049     if (m_footerBanner)
2050         m_footerBanner->showIfHidden();
2051 }
2052
2053 void WebPage::setHeaderBannerHeightForTesting(int height)
2054 {
2055 #if ENABLE(RUBBER_BANDING)
2056     corePage()->addHeaderWithHeight(height);
2057 #endif
2058 }
2059
2060 void WebPage::setFooterBannerHeightForTesting(int height)
2061 {
2062 #if ENABLE(RUBBER_BANDING)
2063     corePage()->addFooterWithHeight(height);
2064 #endif
2065 }
2066
2067 #endif // !PLATFORM(IOS_FAMILY)
2068
2069 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
2070 {
2071     SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
2072     snapshotOptions |= SnapshotOptionsShareable;
2073
2074     RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
2075
2076     ShareableBitmap::Handle handle;
2077     if (image)
2078         image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
2079
2080     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
2081 }
2082
2083 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
2084 {
2085     IntRect snapshotRect = rect;
2086     IntSize bitmapSize = snapshotRect.size();
2087     if (options & SnapshotOptionsPrinting) {
2088         ASSERT(additionalScaleFactor == 1);
2089         Frame* coreFrame = m_mainFrame->coreFrame();
2090         if (!coreFrame)
2091             return nullptr;
2092         bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
2093     } else {
2094         double scaleFactor = additionalScaleFactor;
2095         if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
2096             scaleFactor *= corePage()->deviceScaleFactor();
2097         bitmapSize.scale(scaleFactor);
2098     }
2099
2100     return snapshotAtSize(rect, bitmapSize, options);
2101 }
2102
2103 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
2104 {
2105     IntRect snapshotRect = rect;
2106     float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
2107     float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
2108     float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
2109
2110     if (options & SnapshotOptionsPrinting) {
2111         PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
2112         return;
2113     }
2114
2115     Color documentBackgroundColor = frameView.documentBackgroundColor();
2116     Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
2117     graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
2118
2119     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2120         double deviceScaleFactor = frame.page()->deviceScaleFactor();
2121         graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
2122         scaleFactor /= deviceScaleFactor;
2123     }
2124
2125     graphicsContext.scale(scaleFactor);
2126     graphicsContext.translate(-snapshotRect.location());
2127
2128     FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
2129     if (options & SnapshotOptionsExcludeSelectionHighlighting)
2130         shouldPaintSelection = FrameView::ExcludeSelection;
2131
2132     FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
2133     if (options & SnapshotOptionsInViewCoordinates)
2134         coordinateSpace = FrameView::ViewCoordinates;
2135
2136     frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
2137
2138     if (options & SnapshotOptionsPaintSelectionRectangle) {
2139         FloatRect selectionRectangle = frame.selection().selectionBounds();
2140         graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
2141         graphicsContext.strokeRect(selectionRectangle, 1);
2142     }
2143 }
2144
2145 static ShareableBitmap::Configuration snapshotOptionsToBitmapConfiguration(SnapshotOptions options, WebPage& page)
2146 {
2147     ShareableBitmap::Configuration configuration;
2148 #if USE(CG)
2149     if (options & SnapshotOptionsUseScreenColorSpace)
2150         configuration.colorSpace.cgColorSpace = screenColorSpace(page.corePage()->mainFrame().view());
2151 #endif
2152     return configuration;
2153 }
2154
2155 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2156 {
2157     Frame* coreFrame = m_mainFrame->coreFrame();
2158     if (!coreFrame)
2159         return nullptr;
2160
2161     FrameView* frameView = coreFrame->view();
2162     if (!frameView)
2163         return nullptr;
2164
2165     auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2166     if (!snapshot)
2167         return nullptr;
2168     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2169
2170     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2171
2172     return snapshot;
2173 }
2174
2175 #if USE(CF)
2176 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2177 {
2178     Frame* coreFrame = m_mainFrame->coreFrame();
2179     if (!coreFrame)
2180         return nullptr;
2181
2182     FrameView* frameView = coreFrame->view();
2183     if (!frameView)
2184         return nullptr;
2185
2186     auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2187
2188 #if USE(CG)
2189     auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2190     auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2191     auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2192
2193     CGPDFContextBeginPage(pdfContext.get(), nullptr);
2194
2195     GraphicsContext graphicsContext { pdfContext.get() };
2196     graphicsContext.scale({ 1, -1 });
2197     graphicsContext.translate(0, -bitmapSize.height());
2198     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2199
2200     CGPDFContextEndPage(pdfContext.get());
2201     CGPDFContextClose(pdfContext.get());
2202 #endif
2203
2204     return WTFMove(data);
2205 }
2206 #endif
2207
2208 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2209 {
2210     Frame* coreFrame = m_mainFrame->coreFrame();
2211     if (!coreFrame)
2212         return nullptr;
2213
2214     FrameView* frameView = coreFrame->view();
2215     if (!frameView)
2216         return nullptr;
2217
2218     if (!node.renderer())
2219         return nullptr;
2220
2221     LayoutRect topLevelRect;
2222     IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2223     if (snapshotRect.isEmpty())
2224         return nullptr;
2225
2226     double scaleFactor = 1;
2227     IntSize snapshotSize = snapshotRect.size();
2228     unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2229     if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2230         scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2231         snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2232     }
2233
2234     auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2235     if (!snapshot)
2236         return nullptr;
2237     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2238
2239     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2240         double deviceScaleFactor = corePage()->deviceScaleFactor();
2241         graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2242         scaleFactor /= deviceScaleFactor;
2243     }
2244
2245     graphicsContext->scale(scaleFactor);
2246     graphicsContext->translate(-snapshotRect.location());
2247
2248     Color savedBackgroundColor = frameView->baseBackgroundColor();
2249     frameView->setBaseBackgroundColor(Color::transparent);
2250     frameView->setNodeToDraw(&node);
2251
2252     frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2253
2254     frameView->setBaseBackgroundColor(savedBackgroundColor);
2255     frameView->setNodeToDraw(nullptr);
2256
2257     return snapshot;
2258 }
2259
2260 void WebPage::pageDidScroll()
2261 {
2262 #if PLATFORM(IOS_FAMILY)
2263     if (!m_inDynamicSizeUpdate)
2264         m_dynamicSizeUpdateHistory.clear();
2265 #endif
2266     m_uiClient->pageDidScroll(this);
2267
2268     m_pageScrolledHysteresis.impulse();
2269
2270     send(Messages::WebPageProxy::PageDidScroll());
2271 }
2272
2273 void WebPage::pageStoppedScrolling()
2274 {
2275     // Maintain the current history item's scroll position up-to-date.
2276     if (Frame* frame = m_mainFrame->coreFrame())
2277         frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2278 }
2279
2280 #if ENABLE(CONTEXT_MENUS)
2281 WebContextMenu* WebPage::contextMenu()
2282 {
2283     if (!m_contextMenu)
2284         m_contextMenu = WebContextMenu::create(this);
2285     return m_contextMenu.get();
2286 }
2287
2288 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2289 {
2290     corePage()->contextMenuController().clearContextMenu();
2291
2292     // Simulate a mouse click to generate the correct menu.
2293     PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2294     corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2295     bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2296     auto* menu = handled ? contextMenu() : nullptr;
2297     PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2298     corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2299
2300     return menu;
2301 }
2302 #endif
2303
2304 // Events 
2305
2306 static const WebEvent* g_currentEvent = 0;
2307
2308 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2309 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2310 // platform events passed to the event handler code.
2311 const WebEvent* WebPage::currentEvent()
2312 {
2313     return g_currentEvent;
2314 }
2315
2316 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
2317 {
2318     auto* drawingArea = this->drawingArea();
2319     if (!drawingArea)
2320         return;
2321
2322     drawingArea->setLayerTreeStateIsFrozen(frozen || m_isSuspended);
2323 }
2324
2325 void WebPage::callVolatilityCompletionHandlers(bool succeeded)
2326 {
2327     auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2328     for (auto& completionHandler : completionHandlers)
2329         completionHandler(succeeded);
2330 }
2331
2332 void WebPage::layerVolatilityTimerFired()
2333 {
2334     Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2335     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2336     if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2337         m_layerVolatilityTimer.stop();
2338         if (didSucceed)
2339             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Succeeded in marking layers as volatile", this);
2340         else
2341             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Failed to mark layers as volatile within %gms", this, maximumLayerVolatilityTimerInterval.milliseconds());
2342         callVolatilityCompletionHandlers(didSucceed);
2343         return;
2344     }
2345
2346     RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.milliseconds());
2347     m_layerVolatilityTimer.startRepeating(newInterval);
2348 }
2349
2350 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2351 {
2352     return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2353 }
2354
2355 void WebPage::markLayersVolatile(WTF::Function<void (bool)>&& completionHandler)
2356 {
2357     RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2358
2359     if (m_layerVolatilityTimer.isActive())
2360         m_layerVolatilityTimer.stop();
2361
2362     if (completionHandler)
2363         m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2364
2365     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2366     if (didSucceed || m_isSuspendedUnderLock) {
2367         if (didSucceed)
2368             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2369         else {
2370             // If we get suspended when locking the screen, it is expected that some IOSurfaces cannot be marked as purgeable so we do not keep retrying.
2371             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2372         }
2373         callVolatilityCompletionHandlers(didSucceed);
2374         return;
2375     }
2376
2377     RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.milliseconds());
2378     m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2379 }
2380
2381 void WebPage::cancelMarkLayersVolatile()
2382 {
2383     RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2384     m_layerVolatilityTimer.stop();
2385     m_markLayersAsVolatileCompletionHandlers.clear();
2386 }
2387
2388 class CurrentEvent {
2389 public:
2390     explicit CurrentEvent(const WebEvent& event)
2391         : m_previousCurrentEvent(g_currentEvent)
2392     {
2393         g_currentEvent = &event;
2394     }
2395
2396     ~CurrentEvent()
2397     {
2398         g_currentEvent = m_previousCurrentEvent;
2399     }
2400
2401 private:
2402     const WebEvent* m_previousCurrentEvent;
2403 };
2404
2405 #if ENABLE(CONTEXT_MENUS)
2406 static bool isContextClick(const PlatformMouseEvent& event)
2407 {
2408 #if PLATFORM(COCOA)
2409     return WebEventFactory::shouldBeHandledAsContextClick(event);
2410 #else
2411     return event.button() == WebCore::RightButton;
2412 #endif
2413 }
2414
2415 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2416 {
2417     IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2418     HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2419
2420     Frame* frame = &page->corePage()->mainFrame();
2421     if (result.innerNonSharedNode())
2422         frame = result.innerNonSharedNode()->document().frame();
2423
2424     bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2425     if (handled)
2426         page->contextMenu()->show();
2427
2428     return handled;
2429 }
2430
2431 void WebPage::contextMenuForKeyEvent()
2432 {
2433     corePage()->contextMenuController().clearContextMenu();
2434
2435     Frame& frame = m_page->focusController().focusedOrMainFrame();
2436     bool handled = frame.eventHandler().sendContextMenuEventForKey();
2437     if (handled)
2438         contextMenu()->show();
2439 }
2440 #endif
2441
2442 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2443 {
2444     Frame& frame = page->corePage()->mainFrame();
2445     if (!frame.view())
2446         return false;
2447
2448     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2449
2450     switch (platformMouseEvent.type()) {
2451         case PlatformEvent::MousePressed: {
2452 #if ENABLE(CONTEXT_MENUS)
2453             if (isContextClick(platformMouseEvent))
2454                 page->corePage()->contextMenuController().clearContextMenu();
2455 #endif
2456
2457             bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2458 #if ENABLE(CONTEXT_MENUS)
2459             if (isContextClick(platformMouseEvent))
2460                 handled = handleContextMenuEvent(platformMouseEvent, page);
2461 #endif
2462             return handled;
2463         }
2464         case PlatformEvent::MouseReleased:
2465             return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2466
2467         case PlatformEvent::MouseMoved:
2468 #if PLATFORM(COCOA)
2469             // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2470             // button is currently pressed. It is possible that neither of those things will be true since on
2471             // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2472             // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2473             // efficient scrollbars-only version of the event.
2474             if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2475                 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2476 #endif
2477             return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2478
2479         case PlatformEvent::MouseForceChanged:
2480         case PlatformEvent::MouseForceDown:
2481         case PlatformEvent::MouseForceUp:
2482             return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2483
2484         default:
2485             ASSERT_NOT_REACHED();
2486             return false;
2487     }
2488 }
2489
2490 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2491 {
2492     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2493
2494     m_userActivityHysteresis.impulse();
2495
2496     bool shouldHandleEvent = true;
2497
2498 #if ENABLE(CONTEXT_MENUS)
2499     // Don't try to handle any pending mouse events if a context menu is showing.
2500     if (m_isShowingContextMenu)
2501         shouldHandleEvent = false;
2502 #endif
2503 #if ENABLE(DRAG_SUPPORT)
2504     if (m_isStartingDrag)
2505         shouldHandleEvent = false;
2506 #endif
2507
2508     if (!shouldHandleEvent) {
2509         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2510         return;
2511     }
2512
2513     bool handled = false;
2514
2515 #if !PLATFORM(IOS_FAMILY)
2516     if (!handled && m_headerBanner)
2517         handled = m_headerBanner->mouseEvent(mouseEvent);
2518     if (!handled && m_footerBanner)
2519         handled = m_footerBanner->mouseEvent(mouseEvent);
2520 #endif // !PLATFORM(IOS_FAMILY)
2521
2522     if (!handled) {
2523         CurrentEvent currentEvent(mouseEvent);
2524         handled = handleMouseEvent(mouseEvent, this);
2525     }
2526
2527     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2528 }
2529
2530 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2531 {
2532     Frame& frame = page->mainFrame();
2533     if (!frame.view())
2534         return false;
2535
2536     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2537     return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2538 }
2539
2540 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2541 {
2542     m_userActivityHysteresis.impulse();
2543
2544     CurrentEvent currentEvent(wheelEvent);
2545
2546     bool handled = handleWheelEvent(wheelEvent, m_page.get());
2547
2548     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2549 }
2550
2551 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2552 {
2553     if (!page->mainFrame().view())
2554         return false;
2555
2556     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2557         return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2558     return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2559 }
2560
2561 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2562 {
2563     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2564
2565     m_userActivityHysteresis.impulse();
2566
2567     CurrentEvent currentEvent(keyboardEvent);
2568
2569     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2570     // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2571     if (!handled)
2572         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2573
2574     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2575 }
2576
2577 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2578 {
2579     bool isEnabled = false;
2580     int32_t state = 0;
2581     Frame& frame = m_page->focusController().focusedOrMainFrame();
2582     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2583         isEnabled = pluginView->isEditingCommandEnabled(commandName);
2584     else {
2585         Editor::Command command = frame.editor().command(commandName);
2586         state = command.state();
2587         isEnabled = command.isSupported() && command.isEnabled();
2588     }
2589
2590     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2591 }
2592
2593 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2594 {
2595     executeEditingCommand(commandName, argument);
2596 }
2597
2598 void WebPage::setNeedsFontAttributes(bool needsFontAttributes)
2599 {
2600     if (m_needsFontAttributes == needsFontAttributes)
2601         return;
2602
2603     m_needsFontAttributes = needsFontAttributes;
2604
2605     if (m_needsFontAttributes)
2606         sendPartialEditorStateAndSchedulePostLayoutUpdate();
2607 }
2608
2609 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest, WebBackForwardListProxy::OverwriteExistingItem overwrite)
2610 {
2611     for (const auto& itemState : itemStates) {
2612         auto historyItem = toHistoryItem(itemState);
2613         historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2614         static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, overwrite);
2615     }
2616 }
2617
2618 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2619 {
2620     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes, WebBackForwardListProxy::OverwriteExistingItem::No);
2621 }
2622
2623 void WebPage::updateBackForwardListForReattach(const Vector<WebKit::BackForwardListItemState>& itemStates)
2624 {
2625     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2626 }
2627
2628 void WebPage::setCurrentHistoryItemForReattach(WebKit::BackForwardListItemState&& itemState)
2629 {
2630     auto historyItem = toHistoryItem(itemState);
2631     auto& historyItemRef = historyItem.get();
2632     static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2633     corePage()->mainFrame().loader().history().setCurrentItem(historyItemRef);
2634 }
2635
2636 void WebPage::requestFontAttributesAtSelectionStart(CallbackID callbackID)
2637 {
2638     auto attributes = m_page->focusController().focusedOrMainFrame().editor().fontAttributesAtSelectionStart();
2639     send(Messages::WebPageProxy::FontAttributesCallback(attributes, callbackID));
2640 }
2641
2642 #if ENABLE(TOUCH_EVENTS)
2643 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2644 {
2645     if (!page->mainFrame().view())
2646         return false;
2647
2648     return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2649 }
2650 #endif
2651
2652 #if ENABLE(IOS_TOUCH_EVENTS)
2653 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2654 {
2655     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2656
2657     m_lastInteractionLocation = touchEvent.position();
2658     CurrentEvent currentEvent(touchEvent);
2659     handled = handleTouchEvent(touchEvent, m_page.get());
2660     updatePotentialTapSecurityOrigin(touchEvent, handled);
2661 }
2662
2663 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2664 {
2665     EventDispatcher::TouchEventQueue queuedEvents;
2666     WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2667     dispatchAsynchronousTouchEvents(queuedEvents);
2668
2669     dispatchTouchEvent(touchEvent, handled);
2670 }
2671
2672 void WebPage::updatePotentialTapSecurityOrigin(const WebTouchEvent& touchEvent, bool wasHandled)
2673 {
2674     if (wasHandled)
2675         return;
2676
2677     if (!touchEvent.isPotentialTap())
2678         return;
2679
2680     if (touchEvent.type() != WebEvent::TouchStart)
2681         return;
2682
2683     auto& mainFrame = m_page->mainFrame();
2684     auto document = mainFrame.document();
2685     if (!document)
2686         return;
2687
2688     if (!document->handlingTouchEvent())
2689         return;
2690
2691     Frame* touchEventTargetFrame = &mainFrame;
2692     while (auto subframe = touchEventTargetFrame->eventHandler().touchEventTargetSubframe())
2693         touchEventTargetFrame = subframe;
2694
2695     auto& touches = touchEventTargetFrame->eventHandler().touches();
2696     if (touches.isEmpty())
2697         return;
2698
2699     ASSERT(touches.size() == 1);
2700
2701     if (auto targetDocument = touchEventTargetFrame->document())
2702         m_potentialTapSecurityOrigin = &targetDocument->securityOrigin();
2703 }
2704 #elif ENABLE(TOUCH_EVENTS)
2705 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2706 {
2707     CurrentEvent currentEvent(touchEvent);
2708
2709     bool handled = handleTouchEvent(touchEvent, m_page.get());
2710
2711     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2712 }
2713 #endif
2714
2715 #if ENABLE(MAC_GESTURE_EVENTS)
2716 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2717 {
2718     if (!page->mainFrame().view())
2719         return false;
2720
2721     return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2722 }
2723
2724 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2725 {
2726     CurrentEvent currentEvent(gestureEvent);
2727     bool handled = handleGestureEvent(gestureEvent, m_page.get());
2728     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2729 }
2730 #endif
2731
2732 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2733 {
2734     return page->userInputBridge().scrollRecursively(direction, granularity);
2735 }
2736
2737 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2738 {
2739     return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2740 }
2741
2742 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2743 {
2744     return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2745 }
2746
2747 void WebPage::centerSelectionInVisibleArea()
2748 {
2749     Frame& frame = m_page->focusController().focusedOrMainFrame();
2750     frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2751     findController().showFindIndicatorInSelection();
2752 }
2753
2754 bool WebPage::isControlledByAutomation() const
2755 {
2756     return m_page->isControlledByAutomation();
2757 }
2758
2759 void WebPage::setControlledByAutomation(bool controlled)
2760 {
2761     m_page->setControlledByAutomation(controlled);
2762 }
2763
2764 void WebPage::insertNewlineInQuotedContent()
2765 {
2766     Frame& frame = m_page->focusController().focusedOrMainFrame();
2767     if (frame.selection().isNone())
2768         return;
2769     frame.editor().insertParagraphSeparatorInQuotedContent();
2770 }
2771
2772 #if ENABLE(REMOTE_INSPECTOR)
2773 void WebPage::setAllowsRemoteInspection(bool allow)
2774 {
2775     m_page->setRemoteInspectionAllowed(allow);
2776 }
2777
2778 void WebPage::setRemoteInspectionNameOverride(const String& name)
2779 {
2780     m_page->setRemoteInspectionNameOverride(name);
2781 }
2782 #endif
2783
2784 void WebPage::setDrawsBackground(bool drawsBackground)
2785 {
2786     if (m_drawsBackground == drawsBackground)
2787         return;
2788
2789     m_drawsBackground = drawsBackground;
2790
2791     if (FrameView* frameView = mainFrameView()) {
2792         Color backgroundColor = drawsBackground ? Color::white : Color::transparent;
2793         bool isTransparent = !drawsBackground;
2794         frameView->updateBackgroundRecursively(backgroundColor, isTransparent);
2795     }
2796
2797     m_drawingArea->pageBackgroundTransparencyChanged();
2798     m_drawingArea->setNeedsDisplay();
2799 }
2800
2801 #if PLATFORM(COCOA)
2802 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
2803 {
2804     if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
2805         LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
2806         return;
2807     }
2808
2809     m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
2810
2811     setTopContentInset(contentInset);
2812
2813     deallocateSendRightSafely(fencePort.port());
2814 }
2815 #endif
2816
2817 void WebPage::setTopContentInset(float contentInset)
2818 {
2819     if (contentInset == m_page->topContentInset())
2820         return;
2821
2822     m_page->setTopContentInset(contentInset);
2823
2824     for (auto* pluginView : m_pluginViews)
2825         pluginView->topContentInsetDidChange();
2826 }
2827
2828 void WebPage::viewWillStartLiveResize()
2829 {
2830     if (!m_page)
2831         return;
2832
2833     // FIXME: This should propagate to all ScrollableAreas.
2834     Frame& frame = m_page->focusController().focusedOrMainFrame();
2835     if (FrameView* view = frame.view())
2836         view->willStartLiveResize();
2837 }
2838
2839 void WebPage::viewWillEndLiveResize()
2840 {
2841     if (!m_page)
2842         return;
2843
2844     // FIXME: This should propagate to all ScrollableAreas.
2845     Frame& frame = m_page->focusController().focusedOrMainFrame();
2846     if (FrameView* view = frame.view())
2847         view->willEndLiveResize();
2848 }
2849
2850 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
2851 {
2852     if (!m_page)
2853         return;
2854
2855     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2856
2857     Frame& frame = m_page->focusController().focusedOrMainFrame();
2858     frame.document()->setFocusedElement(0);
2859
2860     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2861         PlatformKeyboardEvent platformEvent(platform(event));
2862         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2863         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
2864
2865         send(Messages::WebPageProxy::VoidCallback(callbackID));
2866         return;
2867     }
2868
2869     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
2870     send(Messages::WebPageProxy::VoidCallback(callbackID));
2871 }
2872
2873 void WebPage::setCanStartMediaTimerFired()
2874 {
2875     if (m_page)
2876         m_page->setCanStartMedia(true);
2877 }
2878
2879 void WebPage::updateIsInWindow(bool isInitialState)
2880 {
2881     bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
2882
2883     if (!isInWindow) {
2884         m_setCanStartMediaTimer.stop();
2885         m_page->setCanStartMedia(false);
2886         
2887         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2888         if (!isInitialState)
2889             WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2890     } else {
2891         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2892         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2893         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2894         if (m_mayStartMediaWhenInWindow)
2895             m_setCanStartMediaTimer.startOneShot(0_s);
2896
2897         WebProcess::singleton().pageDidEnterWindow(m_pageID);
2898     }
2899
2900     if (isInWindow)
2901         layoutIfNeeded();
2902 }
2903
2904 void WebPage::visibilityDidChange()
2905 {
2906     bool isVisible = m_activityState.contains(ActivityState::IsVisible);
2907     if (!isVisible) {
2908         // We save the document / scroll state when backgrounding a tab so that we are able to restore it
2909         // if it gets terminated while in the background.
2910         if (auto* frame = m_mainFrame->coreFrame())
2911             frame->loader().history().saveDocumentAndScrollState();
2912     }
2913 }
2914
2915 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
2916 {
2917     LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
2918
2919     auto changed = m_activityState ^ activityState;
2920     m_activityState = activityState;
2921
2922     if (changed)
2923         updateThrottleState();
2924
2925     {
2926         SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
2927         m_page->setActivityState(activityState);
2928     }
2929     
2930     for (auto* pluginView : m_pluginViews)
2931         pluginView->activityStateDidChange(changed);
2932
2933     m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
2934     WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
2935
2936     if (changed & ActivityState::IsInWindow)
2937         updateIsInWindow();
2938
2939     if (changed & ActivityState::IsVisible)
2940         visibilityDidChange();
2941 }
2942
2943 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
2944 {
2945     m_layerHostingMode = layerHostingMode;
2946
2947     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2948
2949     for (auto* pluginView : m_pluginViews)
2950         pluginView->setLayerHostingMode(m_layerHostingMode);
2951 }
2952
2953 void WebPage::setSessionID(PAL::SessionID sessionID)
2954 {
2955     if (sessionID.isEphemeral())
2956         WebProcess::singleton().addWebsiteDataStore(WebsiteDataStoreParameters::privateSessionParameters(sessionID));
2957     m_page->setSessionID(sessionID);
2958 }
2959
2960 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, std::optional<WebsitePoliciesData>&& websitePolicies)
2961 {
2962     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2963     if (!frame)
2964         return;
2965     if (policyAction == PolicyAction::Suspend) {
2966         ASSERT(frame == m_mainFrame);
2967         setIsSuspended(true);
2968
2969         WebProcess::singleton().sendPrewarmInformation(mainWebFrame()->url());
2970     }
2971     frame->didReceivePolicyDecision(listenerID, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
2972 }
2973
2974 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
2975 {
2976     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2977     if (!frame)
2978         return;
2979     frame->continueWillSubmitForm(listenerID);
2980 }
2981
2982 void WebPage::didStartPageTransition()
2983 {
2984     setLayerTreeStateIsFrozen(true);
2985
2986 #if PLATFORM(MAC)
2987     bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
2988 #endif
2989     m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
2990     m_isAssistingNodeDueToUserInteraction = false;
2991     m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
2992 #if PLATFORM(MAC)
2993     if (hasPreviouslyFocusedDueToUserInteraction)
2994         send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
2995     if (m_needsHiddenContentEditableQuirk) {
2996         m_needsHiddenContentEditableQuirk = false;
2997         send(Messages::WebPageProxy::SetNeedsHiddenContentEditableQuirk(m_needsHiddenContentEditableQuirk));
2998     }
2999     if (m_needsPlainTextQuirk) {
3000         m_needsPlainTextQuirk = false;
3001         send(Messages::WebPageProxy::SetNeedsPlainTextQuirk(m_needsPlainTextQuirk));
3002     }
3003 #endif
3004 }
3005
3006 void WebPage::didCompletePageTransition()
3007 {
3008     // FIXME: Layer tree freezing should be managed entirely in the UI process side.
3009     setLayerTreeStateIsFrozen(false);
3010
3011 #if PLATFORM(MAC)
3012     bool isInitialEmptyDocument = !m_mainFrame;
3013     if (m_shouldAttachDrawingAreaOnPageTransition && !isInitialEmptyDocument) {
3014         m_shouldAttachDrawingAreaOnPageTransition = false;
3015         // Unfreezing the layer tree above schedules a layer flush so we delay attaching the drawing area
3016         // after the next event loop iteration.
3017         RunLoop::main().dispatch([this, weakThis = makeWeakPtr(*this)] {
3018             if (weakThis && m_drawingArea)
3019                 m_drawingArea->attach();
3020         });
3021     }
3022 #endif
3023 }
3024
3025 void WebPage::show()
3026 {
3027     send(Messages::WebPageProxy::ShowPage());
3028 }
3029
3030 String WebPage::userAgent(const URL& webCoreURL) const
3031 {
3032     return userAgent(nullptr, webCoreURL);
3033 }
3034
3035 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
3036 {
3037     if (frame) {
3038         String userAgent = m_loaderClient->userAgentForURL(*frame, webcoreURL);
3039         if (!userAgent.isEmpty())
3040             return userAgent;
3041     }
3042
3043     String userAgent = platformUserAgent(webcoreURL);
3044     if (!userAgent.isEmpty())
3045         return userAgent;
3046     return m_userAgent;
3047 }
3048     
3049 void WebPage::setUserAgent(const String& userAgent)
3050 {
3051     if (m_userAgent == userAgent)
3052         return;
3053
3054     m_userAgent = userAgent;
3055
3056     if (m_page)
3057         m_page->userAgentChanged();
3058 }
3059
3060 void WebPage::suspendActiveDOMObjectsAndAnimations()
3061 {
3062     m_page->suspendActiveDOMObjectsAndAnimations();
3063 }
3064
3065 void WebPage::resumeActiveDOMObjectsAndAnimations()
3066 {
3067     m_page->resumeActiveDOMObjectsAndAnimations();
3068 }
3069
3070 IntPoint WebPage::screenToRootView(const IntPoint& point)
3071 {
3072     IntPoint windowPoint;
3073     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
3074     return windowPoint;
3075 }
3076     
3077 IntRect WebPage::rootViewToScreen(const IntRect& rect)
3078 {
3079     IntRect screenRect;
3080     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
3081     return screenRect;
3082 }
3083     
3084 #if PLATFORM(IOS_FAMILY)
3085 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
3086 {
3087     IntPoint windowPoint;
3088     sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
3089     return windowPoint;
3090 }
3091
3092 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
3093 {
3094     IntRect screenRect;
3095     sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
3096     return screenRect;
3097 }
3098 #endif
3099
3100 KeyboardUIMode WebPage::keyboardUIMode()
3101 {
3102     bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
3103     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
3104 }
3105
3106 void WebPage::runJavaScript(const String& script, bool forceUserGesture, std::optional<String> worldName, CallbackID callbackID)
3107 {
3108     // NOTE: We need to be careful when running scripts that the objects we depend on don't
3109     // disappear during script execution.
3110
3111     RefPtr<SerializedScriptValue> serializedResultValue;
3112     JSLockHolder lock(commonVM());
3113     bool hadException = true;
3114     ExceptionDetails details;
3115     auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
3116     if (world) {
3117         if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
3118             hadException = false;
3119             serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
3120                 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
3121         }
3122     }
3123
3124     IPC::DataReference dataReference;
3125     if (serializedResultValue)
3126         dataReference = serializedResultValue->data();
3127     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
3128 }
3129
3130 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
3131 {
3132     runJavaScript(script, forceUserGesture, std::nullopt, callbackID);
3133 }
3134
3135 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
3136 {
3137     runJavaScript(script, forceUserGesture, worldName, callbackID);
3138 }
3139
3140 void WebPage::getContentsAsString(CallbackID callbackID)
3141 {
3142     String resultString = m_mainFrame->contentsAsString();
3143     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3144 }
3145
3146 #if ENABLE(MHTML)
3147 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
3148 {
3149     send(Messages::WebPageProxy::DataCallback({ MHTMLArchive::generateMHTMLData(m_page.get()) }, callbackID));
3150 }
3151 #endif
3152
3153 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3154 {
3155     String resultString = renderTreeExternalRepresentation();
3156     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3157 }
3158
3159 static Frame* frameWithSelection(Page* page)
3160 {
3161     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3162         if (frame->selection().isRange())
3163             return frame;
3164     }
3165
3166     return 0;
3167 }
3168
3169 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3170 {
3171 #if PLATFORM(COCOA)
3172     RetainPtr<CFDataRef> data;
3173     if (Frame* frame = frameWithSelection(m_page.get()))
3174         data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3175 #endif
3176
3177     IPC::SharedBufferDataReference dataReference;
3178 #if PLATFORM(COCOA)
3179     if (data)
3180         dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3181 #endif
3182     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3183 }
3184
3185 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3186 {
3187     WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3188     String resultString = focusedOrMainFrame->selectionAsString();
3189     if (resultString.isEmpty())
3190         resultString = focusedOrMainFrame->contentsAsString();
3191     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3192 }
3193
3194 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3195 {
3196     String resultString;
3197     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3198        resultString = frame->source();
3199
3200     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3201 }
3202
3203 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3204 {
3205     RefPtr<SharedBuffer> buffer;
3206     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3207         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3208             buffer = pluginView->liveResourceData();
3209         if (!buffer) {
3210             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3211                 buffer = loader->mainResourceData();
3212         }
3213     }
3214
3215     IPC::SharedBufferDataReference dataReference;
3216     if (buffer)
3217         dataReference = { *buffer };
3218     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3219 }
3220
3221 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3222 {
3223     DocumentLoader* loader = frame->loader().documentLoader();
3224     if (!loader)
3225         return nullptr;
3226
3227     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3228     if (!subresource)
3229         return nullptr;
3230
3231     return &subresource->data();
3232 }
3233
3234 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3235 {
3236     RefPtr<SharedBuffer> buffer;
3237     if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3238         URL resourceURL(URL(), resourceURLString);
3239         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3240     }
3241
3242     IPC::SharedBufferDataReference dataReference;
3243     if (buffer)
3244         dataReference = { *buffer };
3245     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3246 }
3247
3248 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3249 {
3250 #if PLATFORM(COCOA)
3251     RetainPtr<CFDataRef> data;
3252     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3253         data = frame->webArchiveData(nullptr, nullptr);
3254 #else
3255     UNUSED_PARAM(frameID);
3256 #endif
3257
3258     IPC::SharedBufferDataReference dataReference;
3259 #if PLATFORM(COCOA)
3260     if (data)
3261         dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3262 #endif
3263     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3264 }
3265
3266 void WebPage::forceRepaintWithoutCallback()
3267 {
3268     m_drawingArea->forceRepaint();
3269 }
3270
3271 void WebPage::forceRepaint(CallbackID callbackID)
3272 {
3273     if (m_drawingArea->forceRepaintAsync(callbackID))
3274         return;
3275
3276     forceRepaintWithoutCallback();
3277     send(Messages::WebPageProxy::VoidCallback(callbackID));
3278 }
3279
3280 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3281 {
3282     WebPreferencesStore::removeTestRunnerOverrides();
3283     updatePreferences(store);
3284 }
3285
3286 void WebPage::updatePreferences(const WebPreferencesStore& store)
3287 {
3288     updatePreferencesGenerated(store);
3289
3290     Settings& settings = m_page->settings();
3291
3292     bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3293     settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3294     settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3295     settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3296     settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3297     settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3298     settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3299     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3300     settings.setFrameFlattening(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()) ? WebCore::FrameFlattening::FullyEnabled : WebCore::FrameFlattening::Disabled);
3301     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3302 #if ENABLE(DATA_DETECTION)
3303     settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3304 #endif
3305
3306     DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3307
3308     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3309     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3310     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3311     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3312
3313     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3314     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3315
3316     if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3317         setSessionID(PAL::SessionID::legacyPrivateSessionID());
3318     else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3319         setSessionID(PAL::SessionID::defaultSessionID());
3320
3321     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3322     if (m_processSuppressionEnabled != processSuppressionEnabled) {
3323         m_processSuppressionEnabled = processSuppressionEnabled;
3324         updateThrottleState();
3325     }
3326
3327 #if PLATFORM(COCOA)
3328     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3329 #endif
3330 #if ENABLE(PAYMENT_REQUEST)
3331     settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3332 #endif
3333
3334     // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3335     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3336
3337 #if PLATFORM(IOS_FAMILY)
3338     m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3339     m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3340     setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3341
3342     settings.setUseImageDocumentForSubframePDF(true);
3343 #if HAVE(AVKIT)
3344     DeprecatedGlobalSettings::setAVKitEnabled(true);
3345 #endif
3346 #endif
3347
3348 #if ENABLE(SERVICE_WORKER)
3349     if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3350         ASSERT(parentProcessHasServiceWorkerEntitlement());
3351         if (!parentProcessHasServiceWorkerEntitlement())
3352             RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3353     }
3354 #endif
3355
3356     settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3357
3358     if (m_drawingArea)
3359         m_drawingArea->updatePreferences(store);
3360 }
3361
3362 #if ENABLE(DATA_DETECTION)
3363 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3364 {
3365     DataDetectionResult dataDetectionResult;
3366     dataDetectionResult.results = detectionResults;
3367     send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3368 }
3369 #endif
3370
3371 #if PLATFORM(COCOA)
3372 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3373 {
3374     FrameView* frameView = corePage()->mainFrame().view();
3375     if (!frameView)
3376         return;
3377
3378     layerTransaction.setContentsSize(frameView->contentsSize());
3379     layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3380     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3381     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3382     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3383
3384     layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3385     layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3386     layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3387
3388 #if PLATFORM(IOS_FAMILY)
3389     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3390     layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3391     layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3392     layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3393     layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3394     layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3395     layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3396     layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3397     layerTransaction.setIsInStableState(m_isInStableState);
3398     layerTransaction.setAllowsUserScaling(allowsUserScaling());
3399     if (m_pendingDynamicViewportSizeUpdateID) {
3400         layerTransaction.setDynamicViewportSizeUpdateID(*m_pendingDynamicViewportSizeUpdateID);
3401         m_pendingDynamicViewportSizeUpdateID = std::nullopt;
3402     }
3403     if (m_lastTransactionPageScaleFactor != layerTransaction.pageScaleFactor()) {
3404         m_lastTransactionPageScaleFactor = layerTransaction.pageScaleFactor();
3405         m_lastTransactionIDWithScaleChange = layerTransaction.transactionID();
3406     }
3407 #endif
3408
3409     layerTransaction.setScrollPosition(frameView->scrollPosition());
3410
3411     if (m_hasPendingEditorStateUpdate) {
3412         layerTransaction.setEditorState(editorState());
3413         m_hasPendingEditorStateUpdate = false;
3414     }
3415 }
3416
3417 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3418 {
3419 #if PLATFORM(IOS_FAMILY)
3420     if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3421         Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3422         m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3423
3424         m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3425     }
3426 #else
3427     UNUSED_PARAM(timestamp);
3428 #endif
3429 }
3430 #endif
3431
3432 void WebPage::willDisplayPage()
3433 {
3434     m_page->willDisplayPage();
3435 }
3436
3437 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3438 {
3439     if (m_isClosed)
3440         return nullptr;
3441     if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3442         m_inspector = WebInspector::create(this);
3443     return m_inspector.get();
3444 }
3445
3446 WebInspectorUI* WebPage::inspectorUI()
3447 {
3448     if (m_isClosed)
3449         return nullptr;
3450     if (!m_inspectorUI)
3451         m_inspectorUI = WebInspectorUI::create(*this);
3452     return m_inspectorUI.get();
3453 }
3454
3455 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3456 {
3457     if (m_isClosed)
3458         return nullptr;
3459     if (!m_remoteInspectorUI)
3460         m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3461     return m_remoteInspectorUI.get();
3462 }
3463
3464 void WebPage::inspectorFrontendCountChanged(unsigned count)
3465 {
3466     send(Messages::WebPageProxy::DidChangeInspectorFrontendCount(count));
3467 }
3468
3469 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3470 PlaybackSessionManager& WebPage::playbackSessionManager()
3471 {
3472     if (!m_playbackSessionManager)
3473         m_playbackSessionManager = PlaybackSessionManager::create(*this);
3474     return *m_playbackSessionManager;
3475 }
3476
3477 VideoFullscreenManager& WebPage::videoFullscreenManager()
3478 {
3479     if (!m_videoFullscreenManager)
3480         m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3481     return *m_videoFullscreenManager;
3482 }
3483
3484 void WebPage::videoControlsManagerDidChange()
3485 {
3486 #if ENABLE(FULLSCREEN_API)
3487     if (auto* manager = fullScreenManager())
3488         manager->videoControlsManagerDidChange();
3489 #endif
3490 }
3491
3492 #endif
3493
3494 #if PLATFORM(IOS_FAMILY)
3495 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3496 {
3497     m_page->setAllowsMediaDocumentInlinePlayback(allows);
3498 }
3499 #endif
3500
3501 #if ENABLE(FULLSCREEN_API)
3502 WebFullScreenManager* WebPage::fullScreenManager()
3503 {
3504     if (!m_fullScreenManager)
3505         m_fullScreenManager = WebFullScreenManager::create(this);
3506     return m_fullScreenManager.get();
3507 }
3508 #endif
3509
3510 void WebPage::addConsoleMessage(uint64_t frameID, MessageSource messageSource, MessageLevel messageLevel, const String& message, uint64_t requestID)
3511 {
3512     if (auto* frame = WebProcess::singleton().webFrame(frameID))
3513         frame->addConsoleMessage(messageSource, messageLevel, message, requestID);
3514 }
3515
3516 void WebPage::sendCSPViolationReport(uint64_t frameID, const WebCore::URL& reportURL, IPC::FormDataReference&& reportData)
3517 {
3518     auto report = reportData.takeData();
3519     if (!report)
3520         return;
3521     if (auto* frame = WebProcess::singleton().webFrame(frameID))
3522         PingLoader::sendViolationReport(*frame->coreFrame(), reportURL, report.releaseNonNull(), ViolationReportType::ContentSecurityPolicy);
3523 }
3524
3525 void WebPage::enqueueSecurityPolicyViolationEvent(uint64_t frameID, SecurityPolicyViolationEvent::Init&& eventInit)
3526 {
3527     auto* frame = WebProcess::singleton().webFrame(frameID);
3528     if (!frame)
3529         return;
3530     auto* coreFrame = frame->coreFrame();
3531     if (!coreFrame)
3532         return;
3533     if (auto* document = coreFrame->document())
3534         document->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
3535 }
3536
3537 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3538 {
3539     if (m_notificationPermissionRequestManager)
3540         return m_notificationPermissionRequestManager.get();
3541
3542     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3543     return m_notificationPermissionRequestManager.get();
3544 }
3545
3546 #if ENABLE(DRAG_SUPPORT)
3547
3548 #if PLATFORM(GTK)
3549 void WebPage::performDragControllerAction(DragControllerAction action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3550 {
3551     if (!m_page) {
3552         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3553         return;
3554     }
3555
3556     DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3557     switch (action) {
3558     case DragControllerAction::Entered: {
3559         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3560         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }));
3561         return;
3562     }
3563     case DragControllerAction::Updated: {
3564         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3565         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }));
3566         return;
3567     }
3568     case DragControllerAction::Exited:
3569         m_page->dragController().dragExited(dragData);
3570         return;
3571
3572     case DragControllerAction::PerformDragOperation: {
3573         m_page->dragController().performDragOperation(dragData);
3574         return;
3575     }
3576     }
3577     ASSERT_NOT_REACHED();
3578 }
3579 #else
3580 void WebPage::performDragControllerAction(DragControllerAction action, const WebCore::DragData& dragData, SandboxExtension::Handle&& sandboxExtensionHandle, SandboxExtension::HandleArray&& sandboxExtensionsHandleArray)
3581 {
3582     if (!m_page) {
3583         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3584         return;
3585     }
3586
3587     switch (action) {
3588     case DragControllerAction::Entered: {
3589         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3590         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), m_page->dragCaretController().caretRectInRootViewCoordinates()));
3591         return;
3592     }
3593     case DragControllerAction::Updated: {
3594         DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3595         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), m_page->dragCaretController().caretRectInRootViewCoordinates()));
3596         return;
3597     }
3598     case DragControllerAction::Exited:
3599         m_page->dragController().dragExited(dragData);
3600         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0, { }));
3601         return;
3602         
3603     case DragControllerAction::PerformDragOperation: {
3604         ASSERT(!m_pendingDropSandboxExtension);
3605
3606         m_pendingDropSandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
3607         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3608             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(WTFMove(sandboxExtensionsHandleArray[i])))
3609                 m_pendingDropExtensionsForFileUpload.append(extension);
3610         }
3611
3612         bool handled = m_page->dragController().performDragOperation(dragData);
3613
3614         // If we started loading a local file, the sandbox extension tracker would have adopted this
3615         // pending drop sandbox extension. If not, we'll play it safe and clear it.
3616         m_pendingDropSandboxExtension = nullptr;
3617
3618         m_pendingDropExtensionsForFileUpload.clear();
3619         send(Messages::WebPageProxy::DidPerformDragOperation(handled));
3620         return;
3621     }
3622     }
3623     ASSERT_NOT_REACHED();
3624 }
3625 #endif
3626
3627 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3628 {
3629     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3630     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3631
3632     m_page->dragController().dragEnded();
3633     FrameView* view = m_page->mainFrame().view();
3634     if (!view)
3635         return;
3636     // FIXME: These are fake modifier keys here, but they should be real ones instead.
3637     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), 0, WebCore::NoTap);
3638     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3639
3640     send(Messages::WebPageProxy::DidEndDragging());
3641 }
3642
3643 void WebPage::willPerformLoadDragDestinationAction()
3644 {
3645     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(WTFMove(m_pendingDropSandboxExtension));
3646 }
3647
3648 void WebPage::mayPerformUploadDragDestinationAction()
3649 {
3650     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3651         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3652     m_pendingDropExtensionsForFileUpload.clear();
3653 }
3654
3655 void WebPage::didStartDrag()
3656 {
3657     m_isStartingDrag = false;
3658     m_page->mainFrame().eventHandler().didStartDrag();
3659 }
3660
3661 void WebPage::dragCancelled()
3662 {
3663     m_isStartingDrag = false;
3664     m_page->mainFrame().eventHandler().dragCancelled();
3665 }
3666     
3667 #endif // ENABLE(DRAG_SUPPORT)
3668
3669 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3670 {
3671     return m_undoStepMap.get(stepID);
3672 }
3673
3674 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3675 {
3676     m_undoStepMap.set(stepID, entry);
3677 }
3678
3679 void WebPage::removeWebEditCommand(uint64_t stepID)
3680 {
3681     m_undoStepMap.remove(stepID);
3682 }
3683
3684 bool WebPage::isAlwaysOnLoggingAllowed() const
3685 {
3686     return corePage() && corePage()->isAlwaysOnLoggingAllowed();
3687 }
3688
3689 void WebPage::unapplyEditCommand(uint64_t stepID)
3690 {
3691     WebUndoStep* step = webUndoStep(stepID);
3692     if (!step)
3693         return;
3694
3695     step->step().unapply();
3696 }
3697
3698 void WebPage::reapplyEditCommand(uint64_t stepID)
3699 {
3700     WebUndoStep* step = webUndoStep(stepID);
3701     if (!step)
3702         return;
3703
3704     m_isInRedo = true;
3705     step->step().reapply();
3706     m_isInRedo = false;
3707 }
3708
3709 void WebPage::didRemoveEditCommand(uint64_t commandID)
3710 {
3711     removeWebEditCommand(commandID);
3712 }
3713
3714 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3715 {
3716     m_activePopupMenu = menu;
3717 }
3718
3719 #if ENABLE(INPUT_TYPE_COLOR)
3720
3721 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3722 {
3723     m_activeColorChooser = colorChooser;
3724 }
3725
3726 void WebPage::didEndColorPicker()
3727 {
3728     m_activeColorChooser->didEndChooser();
3729 }
3730
3731 void WebPage::didChooseColor(const WebCore::Color& color)
3732 {
3733     m_activeColorChooser->didChooseColor(color);
3734 }
3735
3736 #endif
3737
3738 #if ENABLE(DATALIST_ELEMENT)
3739
3740 void WebPage::setActiveDataListSuggestionPicker(WebDataListSuggestionPicker* dataListSuggestionPicker)
3741 {
3742     m_activeDataListSuggestionPicker = dataListSuggestionPicker;
3743 }
3744
3745 void WebPage::didSelectDataListOption(const String& selectedOption)
3746 {
3747     m_activeDataListSuggestionPicker->didSelectOption(selectedOption);
3748 }
3749
3750 void WebPage::didCloseSuggestions()
3751 {
3752     if (m_activeDataListSuggestionPicker)
3753         m_activeDataListSuggestionPicker->didCloseSuggestions();
3754     m_activeDataListSuggestionPicker = nullptr;
3755 }
3756
3757 #endif
3758
3759 void WebPage::setActiveOpenPanelResultListener(Ref<WebOpenPanelResultListener>&& openPanelResultListener)
3760 {
3761     m_activeOpenPanelResultListener = WTFMove(openPanelResultListener);
3762 }
3763
3764 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3765 {
3766     return m_page->findString(target, core(options));
3767 }
3768
3769 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3770 {
3771     findController().findString(string, static_cast<FindOptions>(options), maxMatchCount);
3772 }
3773
3774 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3775 {
3776     findController().findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3777 }
3778
3779 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3780 {
3781     findController().getImageForFindMatch(matchIndex);
3782 }
3783
3784 void WebPage::selectFindMatch(uint32_t matchIndex)
3785 {
3786     findController().selectFindMatch(matchIndex);
3787 }
3788
3789 void WebPage::hideFindUI()
3790 {
3791     findController().hideFindUI();
3792 }
3793
3794 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3795 {
3796     findController().countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3797 }
3798
3799 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3800 {
3801     changeSelectedIndex(newIndex);
3802     m_activePopupMenu = nullptr;
3803 }
3804
3805 void WebPage::changeSelectedIndex(int32_t index)
3806 {
3807     if (!m_activePopupMenu)
3808         return;
3809
3810     m_activePopupMenu->didChangeSelectedIndex(index);
3811 }
3812
3813 #if PLATFORM(IOS_FAMILY)
3814 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3815 {
3816     if (!m_activeOpenPanelResultListener)
3817         return;
3818
3819     RefPtr<Icon> icon;
3820     if (!iconData.isEmpty()) {
3821         RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3822         RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3823         RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3824         icon = Icon::createIconForImage(imageRef.get());
3825     }
3826
3827     m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3828     m_activeOpenPanelResultListener = nullptr;
3829 }
3830 #endif
3831
3832 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3833 {
3834     if (!m_activeOpenPanelResultListener)
3835         return;
3836
3837     m_activeOpenPanelResultListener->didChooseFiles(files);
3838     m_activeOpenPanelResultListener = nullptr;
3839 }
3840
3841 void WebPage::didCancelForOpenPanel()
3842 {
3843     m_activeOpenPanelResultListener = nullptr;
3844 }
3845
3846 #if ENABLE(SANDBOX_EXTENSIONS)
3847 void WebPage::extendSandboxForFilesFromOpenPanel(SandboxExtension::HandleArray&& handles)
3848 {
3849     for (size_t i = 0; i < handles.size(); ++i) {
3850         bool result = SandboxExtension::consumePermanently(handles[i]);
3851         if (!result) {
3852             // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3853             WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3854         }
3855     }
3856 }
3857 #endif
3858
3859 #if ENABLE(GEOLOCATION)
3860 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3861 {
3862     geolocationPermissionRequestManager().didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3863 }
3864 #endif
3865
3866 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3867 {
3868     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3869 }
3870
3871 #if ENABLE(MEDIA_STREAM)
3872
3873 #if !PLATFORM(IOS_FAMILY)
3874 void WebPage::prepareToSendUserMediaPermissionRequest()
3875 {
3876 }
3877 #endif
3878
3879 void WebPage::userMediaAccessWasGranted(uint64_t userMediaID, WebCore::CaptureDevice&& audioDevice, WebCore::CaptureDevice&& videoDevice, String&& mediaDeviceIdentifierHashSalt)
3880 {
3881     m_userMediaPermissionRequestManager->userMediaAccessWasGranted(userMediaID, WTFMove(audioDevice), WTFMove(videoDevice), WTFMove(mediaDeviceIdentifierHashSalt));
3882 }
3883
3884 void WebPage::userMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String&& invalidConstraint)
3885 {
3886     m_userMediaPermissionRequestManager->userMediaAccessWasDenied(userMediaID, static_cast<UserMediaRequest::MediaAccessDenialReason>(reason), WTFMove(invalidConstraint));
3887 }
3888
3889 void WebPage::didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vector<CaptureDevice>& devices, String&& deviceIdentifierHashSalt, bool originHasPersistentAccess)
3890 {
3891     m_userMediaPermissionRequestManager->didCompleteMediaDeviceEnumeration(userMediaID, devices, WTFMove(deviceIdentifierHashSalt), originHasPersistentAccess);
3892 }
3893
3894 void WebPage::captureDevicesChanged(DeviceAccessState accessState)
3895 {
3896     m_userMediaPermissionRequestManager->captureDevicesChanged(accessState);
3897 }
3898
3899 #if ENABLE(SANDBOX_EXTENSIONS)
3900 void WebPage::grantUserMediaDeviceSandboxExtensions(MediaDeviceSandboxExtensions&& extensions)
3901 {
3902     m_userMediaPermissionRequestManager->grantUserMediaDeviceSandboxExtensions(WTFMove(extensions));
3903 }
3904
3905 void WebPage::revokeUserMediaDeviceSandboxExtensions(const Vector<String>& extensionIDs)
3906 {
3907     m_userMediaPermissionRequestManager->revokeUserMediaDeviceSandboxExtensions(extensionIDs);
3908 }
3909 #endif
3910 #endif
3911
3912 #if !PLATFORM(IOS_FAMILY)
3913 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3914 {
3915     Frame& frame = m_page->focusController().focusedOrMainFrame();
3916     frame.editor().advanceToNextMisspelling(startBeforeSelection);
3917 }
3918 #endif
3919
3920 bool WebPage::hasRichlyEditableSelection() const
3921 {
3922     auto& frame = m_page->focusController().focusedOrMainFrame();
3923     if (m_page->dragCaretController().isContentRichlyEditable())
3924         return true;
3925
3926     return frame.selection().selection().isContentRichlyEditable();
3927 }
3928
3929 void WebPage::changeSpellingToWord(const String& word)
3930 {
3931     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3932 }
3933
3934 void WebPage::unmarkAllMisspellings()
3935 {
3936     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3937         if (Document* document = frame->document())
3938             document->markers().removeMarkers(DocumentMarker::Spelling);
3939     }
3940 }
3941
3942 void WebPage::unmarkAllBadGrammar()
3943 {
3944     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3945         if (Document* document = frame->document())
3946             document->markers().removeMarkers(DocumentMarker::Grammar);
3947     }
3948 }
3949
3950 #if USE(APPKIT)
3951 void WebPage::uppercaseWord()
3952 {
3953     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3954 }
3955
3956 void WebPage::lowercaseWord()
3957 {
3958     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3959 }
3960
3961 void WebPage::capitalizeWord()
3962 {
3963     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3964 }
3965 #endif
3966     
3967 void WebPage::setTextForActivePopupMenu(int32_t index)
3968 {
3969     if (!m_activePopupMenu)
3970         return;
3971
3972     m_activePopupMenu->setTextForIndex(index);
3973 }
3974
3975 #if PLATFORM(GTK)
3976 void WebPage::failedToShowPopupMenu()
3977 {
3978     if (!m_activePopupMenu)
3979         return;
3980
3981     m_activePopupMenu->client()->popupDidHide();
3982 }
3983 #endif
3984
3985 #if ENABLE(CONTEXT_MENUS)
3986 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3987 {
3988     if (!m_contextMenu)
3989         return;
3990
3991     m_contextMenu->itemSelected(item);
3992     m_contextMenu = nullptr;
3993 }
3994 #endif
3995
3996 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3997 {
3998     bool selectReplacement = true;
3999     bool smartReplace = false;
4000     return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
4001 }
4002
4003 #if !PLATFORM(IOS_FAMILY)
4004 void WebPage::clearSelection()
4005 {
4006     m_page->focusController().focusedOrMainFrame().selection().clear();
4007 }
4008 #endif
4009
4010 void WebPage::restoreSelectionInFocusedEditableElement()
4011 {
4012     Frame& frame = m_page->focusController().focusedOrMainFrame();
4013     if (!frame.selection().isNone())
4014         return;
4015
4016     if (auto document = frame.document()) {
4017         if (auto element = document->focusedElement())
4018             element->updateFocusAppearance(SelectionRestorationMode::Restore, SelectionRevealMode::DoNotReveal);
4019     }
4020 }
4021
4022 bool WebPage::mainFrameHasCustomContentProvider() const
4023 {
4024     if (Frame* frame = mainFrame()) {
4025         WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
4026         ASSERT(webFrameLoaderClient);
4027         return webFrameLoaderClient->frameHasCustomContentProvider();
4028     }
4029
4030     return false;
4031 }
4032
4033 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
4034 {
4035     m_mimeTypesWithCustomContentProviders.add(mimeType);
4036 }
4037
4038 void WebPage::updateMainFrameScrollOffsetPinning()
4039 {
4040     Frame& frame = m_page->mainFrame();
4041     ScrollPosition scrollPosition = frame.view()->scrollPosition();
4042     ScrollPosition maximumScrollPosition = frame.view()->maximumScrollPosition();
4043     ScrollPosition minimumScrollPosition = frame.view()->minimumScrollPosition();
4044
4045     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
4046     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
4047     bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
4048     bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
4049
4050     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
4051         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
4052         
4053         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
4054         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
4055         m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
4056         m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
4057     }
4058 }
4059
4060 void WebPage::mainFrameDidLayout()
4061 {
4062     unsigned pageCount = m_page->pageCount();
4063     if (pageCount != m_cachedPageCount) {
4064         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
4065         m_cachedPageCount = pageCount;
4066     }
4067
4068 #if PLATFORM(COCOA)
4069     m_viewGestureGeometryCollector->mainFrameDidLayout();
4070 #endif
4071 #if PLATFORM(IOS_FAMILY)
4072     if (FrameView* frameView = mainFrameView()) {
4073         IntSize newContentSize = frameView->contentsSize();
4074         LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " mainFrameDidLayout setting content size to " << newContentSize);
4075         if (m_viewportConfiguration.setContentsSize(newContentSize))
4076             viewportConfigurationChanged();
4077     }
4078     findController().redraw();
4079 #endif
4080 }
4081
4082 void WebPage::addPluginView(PluginView* pluginView)
4083 {
4084     ASSERT(!m_pluginViews.contains(pluginView));
4085
4086     m_pluginViews.add(pluginView);
4087     m_hasSeenPlugin = true;
4088 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
4089     LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
4090     m_determinePrimarySnapshottedPlugInTimer.startOneShot(0_s);
4091 #endif
4092 }
4093
4094 void WebPage::removePluginView(PluginView* pluginView)
4095 {
4096     ASSERT(m_pluginViews.contains(pluginView));
4097
4098     m_pluginViews.remove(pluginView);
4099 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
4100     LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
4101 #endif
4102 }
4103
4104 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
4105 {
4106 #if PLATFORM(COCOA)
4107     m_hasCachedWindowFrame = false;
4108 #endif
4109     send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
4110 }
4111
4112 #if PLATFORM(COCOA)
4113 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
4114 {
4115     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
4116     m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
4117     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
4118     m_accessibilityPosition = accessibilityViewCoordinates;
4119     
4120     // Tell all our plug-in views that the window and view frames have changed.
4121     for (auto* pluginView : m_pluginViews)
4122         pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
4123
4124     m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
4125 }
4126 #endif
4127
4128 void WebPage::setMainFrameIsScrollable(bool isScrollable)
4129 {
4130     m_mainFrameIsScrollable = isScrollable;
4131     m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
4132
4133     if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
4134         frameView->setCanHaveScrollbars(isScrollable);
4135         frameView->setProhibitsScrolling(!isScrollable);
4136     }
4137 }
4138
4139 bool WebPage::windowIsFocused() const
4140 {
4141     return m_page->focusController().isActive();
4142 }
4143
4144 bool WebPage::windowAndWebPageAreFocused() const
4145 {
4146     if (!isVisible())
4147         return false;
4148
4149     return m_page->focusController().isFocused() && m_page->focusController().isActive();
4150 }
4151
4152 void WebPage::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
4153 {
4154     if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
4155         if (WebInspector* inspector = this->inspector())
4156             inspector->didReceiveMessage(connection, decoder);
4157         return;
4158     }
4159
4160     if (decoder.messageReceiverName() == Messages::WebInspectorUI::messageReceiverName()) {
4161         if (WebInspectorUI* inspectorUI = this->inspectorUI())
4162             inspectorUI->didReceiveMessage(connection, decoder);
4163         return;
4164     }
4165
4166     if (decoder.messageReceiverName() == Messages::RemoteWebInspectorUI::messageReceiverName()) {
4167         if (RemoteWebInspectorUI* remoteInspectorUI = this->remoteInspectorUI())
4168             remoteInspectorUI->didReceiveMessage(connection, decoder);
4169         return;
4170     }
4171
4172 #if ENABLE(FULLSCREEN_API)
4173     if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
4174         fullScreenManager()->didReceiveMessage(connection, decoder);
4175         return;
4176     }
4177 #endif
4178
4179     didReceiveWebPageMessage(connection, decoder);
4180 }
4181
4182 void WebPage::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
4183 {