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