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