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