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