[iOS] Consistent 1 sec hang when triggering modal alerts while handling synchronous...
[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 #if ENABLE(RUBBER_BANDING)
2132     corePage()->addHeaderWithHeight(height);
2133 #endif
2134 }
2135
2136 void WebPage::setFooterBannerHeightForTesting(int height)
2137 {
2138 #if ENABLE(RUBBER_BANDING)
2139     corePage()->addFooterWithHeight(height);
2140 #endif
2141 }
2142
2143 #endif // !PLATFORM(IOS_FAMILY)
2144
2145 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
2146 {
2147     SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
2148     snapshotOptions |= SnapshotOptionsShareable;
2149
2150     RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
2151
2152     ShareableBitmap::Handle handle;
2153     if (image)
2154         image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
2155
2156     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
2157 }
2158
2159 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
2160 {
2161     IntRect snapshotRect = rect;
2162     IntSize bitmapSize = snapshotRect.size();
2163     if (options & SnapshotOptionsPrinting) {
2164         ASSERT(additionalScaleFactor == 1);
2165         Frame* coreFrame = m_mainFrame->coreFrame();
2166         if (!coreFrame)
2167             return nullptr;
2168         bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
2169     } else {
2170         double scaleFactor = additionalScaleFactor;
2171         if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
2172             scaleFactor *= corePage()->deviceScaleFactor();
2173         bitmapSize.scale(scaleFactor);
2174     }
2175
2176     return snapshotAtSize(rect, bitmapSize, options);
2177 }
2178
2179 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
2180 {
2181     IntRect snapshotRect = rect;
2182     float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
2183     float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
2184     float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
2185
2186     if (options & SnapshotOptionsPrinting) {
2187         PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
2188         return;
2189     }
2190
2191     Color documentBackgroundColor = frameView.documentBackgroundColor();
2192     Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
2193     graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
2194
2195     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2196         double deviceScaleFactor = frame.page()->deviceScaleFactor();
2197         graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
2198         scaleFactor /= deviceScaleFactor;
2199     }
2200
2201     graphicsContext.scale(scaleFactor);
2202     graphicsContext.translate(-snapshotRect.location());
2203
2204     FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
2205     if (options & SnapshotOptionsExcludeSelectionHighlighting)
2206         shouldPaintSelection = FrameView::ExcludeSelection;
2207
2208     FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
2209     if (options & SnapshotOptionsInViewCoordinates)
2210         coordinateSpace = FrameView::ViewCoordinates;
2211
2212     frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
2213
2214     if (options & SnapshotOptionsPaintSelectionRectangle) {
2215         FloatRect selectionRectangle = frame.selection().selectionBounds();
2216         graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
2217         graphicsContext.strokeRect(selectionRectangle, 1);
2218     }
2219 }
2220
2221 static ShareableBitmap::Configuration snapshotOptionsToBitmapConfiguration(SnapshotOptions options, WebPage& page)
2222 {
2223     ShareableBitmap::Configuration configuration;
2224 #if USE(CG)
2225     if (options & SnapshotOptionsUseScreenColorSpace)
2226         configuration.colorSpace.cgColorSpace = screenColorSpace(page.corePage()->mainFrame().view());
2227 #endif
2228     return configuration;
2229 }
2230
2231 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2232 {
2233     Frame* coreFrame = m_mainFrame->coreFrame();
2234     if (!coreFrame)
2235         return nullptr;
2236
2237     FrameView* frameView = coreFrame->view();
2238     if (!frameView)
2239         return nullptr;
2240
2241     auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2242     if (!snapshot)
2243         return nullptr;
2244     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2245
2246     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2247
2248     return snapshot;
2249 }
2250
2251 #if USE(CF)
2252 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2253 {
2254     Frame* coreFrame = m_mainFrame->coreFrame();
2255     if (!coreFrame)
2256         return nullptr;
2257
2258     FrameView* frameView = coreFrame->view();
2259     if (!frameView)
2260         return nullptr;
2261
2262     auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2263
2264 #if USE(CG)
2265     auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2266     auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2267     auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2268
2269     CGPDFContextBeginPage(pdfContext.get(), nullptr);
2270
2271     GraphicsContext graphicsContext { pdfContext.get() };
2272     graphicsContext.scale({ 1, -1 });
2273     graphicsContext.translate(0, -bitmapSize.height());
2274     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2275
2276     CGPDFContextEndPage(pdfContext.get());
2277     CGPDFContextClose(pdfContext.get());
2278 #endif
2279
2280     return WTFMove(data);
2281 }
2282 #endif
2283
2284 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2285 {
2286     Frame* coreFrame = m_mainFrame->coreFrame();
2287     if (!coreFrame)
2288         return nullptr;
2289
2290     FrameView* frameView = coreFrame->view();
2291     if (!frameView)
2292         return nullptr;
2293
2294     if (!node.renderer())
2295         return nullptr;
2296
2297     LayoutRect topLevelRect;
2298     IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2299     if (snapshotRect.isEmpty())
2300         return nullptr;
2301
2302     double scaleFactor = 1;
2303     IntSize snapshotSize = snapshotRect.size();
2304     unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2305     if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2306         scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2307         snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2308     }
2309
2310     auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2311     if (!snapshot)
2312         return nullptr;
2313     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2314
2315     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2316         double deviceScaleFactor = corePage()->deviceScaleFactor();
2317         graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2318         scaleFactor /= deviceScaleFactor;
2319     }
2320
2321     graphicsContext->scale(scaleFactor);
2322     graphicsContext->translate(-snapshotRect.location());
2323
2324     Color savedBackgroundColor = frameView->baseBackgroundColor();
2325     frameView->setBaseBackgroundColor(Color::transparent);
2326     frameView->setNodeToDraw(&node);
2327
2328     frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2329
2330     frameView->setBaseBackgroundColor(savedBackgroundColor);
2331     frameView->setNodeToDraw(nullptr);
2332
2333     return snapshot;
2334 }
2335
2336 void WebPage::pageDidScroll()
2337 {
2338 #if PLATFORM(IOS_FAMILY)
2339     if (!m_inDynamicSizeUpdate)
2340         m_dynamicSizeUpdateHistory.clear();
2341 #endif
2342     m_uiClient->pageDidScroll(this);
2343
2344     m_pageScrolledHysteresis.impulse();
2345
2346     send(Messages::WebPageProxy::PageDidScroll());
2347 }
2348
2349 void WebPage::pageStoppedScrolling()
2350 {
2351     // Maintain the current history item's scroll position up-to-date.
2352     if (Frame* frame = m_mainFrame->coreFrame())
2353         frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2354 }
2355
2356 #if ENABLE(CONTEXT_MENUS)
2357 WebContextMenu* WebPage::contextMenu()
2358 {
2359     if (!m_contextMenu)
2360         m_contextMenu = WebContextMenu::create(this);
2361     return m_contextMenu.get();
2362 }
2363
2364 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2365 {
2366     corePage()->contextMenuController().clearContextMenu();
2367
2368     // Simulate a mouse click to generate the correct menu.
2369     PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2370     corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2371     bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2372     auto* menu = handled ? contextMenu() : nullptr;
2373     PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2374     corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2375
2376     return menu;
2377 }
2378 #endif
2379
2380 // Events 
2381
2382 static const WebEvent* g_currentEvent = 0;
2383
2384 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2385 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2386 // platform events passed to the event handler code.
2387 const WebEvent* WebPage::currentEvent()
2388 {
2389     return g_currentEvent;
2390 }
2391
2392 void WebPage::freezeLayerTree(LayerTreeFreezeReason reason)
2393 {
2394     m_LayerTreeFreezeReasons.add(reason);
2395     updateDrawingAreaLayerTreeFreezeState();
2396 }
2397
2398 void WebPage::unfreezeLayerTree(LayerTreeFreezeReason reason)
2399 {
2400     m_LayerTreeFreezeReasons.remove(reason);
2401     updateDrawingAreaLayerTreeFreezeState();
2402 }
2403
2404 void WebPage::updateDrawingAreaLayerTreeFreezeState()
2405 {
2406     if (!m_drawingArea)
2407         return;
2408     m_drawingArea->setLayerTreeStateIsFrozen(!!m_LayerTreeFreezeReasons);
2409 }
2410
2411 void WebPage::callVolatilityCompletionHandlers(bool succeeded)
2412 {
2413     auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2414     for (auto& completionHandler : completionHandlers)
2415         completionHandler(succeeded);
2416 }
2417
2418 void WebPage::layerVolatilityTimerFired()
2419 {
2420     Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2421     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2422     if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2423         m_layerVolatilityTimer.stop();
2424         if (didSucceed)
2425             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Succeeded in marking layers as volatile", this);
2426         else
2427             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Failed to mark layers as volatile within %gms", this, maximumLayerVolatilityTimerInterval.milliseconds());
2428         callVolatilityCompletionHandlers(didSucceed);
2429         return;
2430     }
2431
2432     RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.milliseconds());
2433     m_layerVolatilityTimer.startRepeating(newInterval);
2434 }
2435
2436 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2437 {
2438     return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2439 }
2440
2441 void WebPage::markLayersVolatile(WTF::Function<void (bool)>&& completionHandler)
2442 {
2443     RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2444
2445     if (m_layerVolatilityTimer.isActive())
2446         m_layerVolatilityTimer.stop();
2447
2448     if (completionHandler)
2449         m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2450
2451     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2452     if (didSucceed || m_isSuspendedUnderLock) {
2453         if (didSucceed)
2454             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2455         else {
2456             // 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.
2457             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2458         }
2459         callVolatilityCompletionHandlers(didSucceed);
2460         return;
2461     }
2462
2463     RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.milliseconds());
2464     m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2465 }
2466
2467 void WebPage::cancelMarkLayersVolatile()
2468 {
2469     RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2470     m_layerVolatilityTimer.stop();
2471     m_markLayersAsVolatileCompletionHandlers.clear();
2472 }
2473
2474 class CurrentEvent {
2475 public:
2476     explicit CurrentEvent(const WebEvent& event)
2477         : m_previousCurrentEvent(g_currentEvent)
2478     {
2479         g_currentEvent = &event;
2480     }
2481
2482     ~CurrentEvent()
2483     {
2484         g_currentEvent = m_previousCurrentEvent;
2485     }
2486
2487 private:
2488     const WebEvent* m_previousCurrentEvent;
2489 };
2490
2491 #if ENABLE(CONTEXT_MENUS)
2492 static bool isContextClick(const PlatformMouseEvent& event)
2493 {
2494 #if PLATFORM(COCOA)
2495     return WebEventFactory::shouldBeHandledAsContextClick(event);
2496 #else
2497     return event.button() == WebCore::RightButton;
2498 #endif
2499 }
2500
2501 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2502 {
2503     IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2504     HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2505
2506     Frame* frame = &page->corePage()->mainFrame();
2507     if (result.innerNonSharedNode())
2508         frame = result.innerNonSharedNode()->document().frame();
2509
2510     bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2511     if (handled)
2512         page->contextMenu()->show();
2513
2514     return handled;
2515 }
2516
2517 void WebPage::contextMenuForKeyEvent()
2518 {
2519     corePage()->contextMenuController().clearContextMenu();
2520
2521     Frame& frame = m_page->focusController().focusedOrMainFrame();
2522     bool handled = frame.eventHandler().sendContextMenuEventForKey();
2523     if (handled)
2524         contextMenu()->show();
2525 }
2526 #endif
2527
2528 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2529 {
2530     Frame& frame = page->corePage()->mainFrame();
2531     if (!frame.view())
2532         return false;
2533
2534     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2535
2536     switch (platformMouseEvent.type()) {
2537         case PlatformEvent::MousePressed: {
2538 #if ENABLE(CONTEXT_MENUS)
2539             if (isContextClick(platformMouseEvent))
2540                 page->corePage()->contextMenuController().clearContextMenu();
2541 #endif
2542
2543             bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2544 #if ENABLE(CONTEXT_MENUS)
2545             if (isContextClick(platformMouseEvent))
2546                 handled = handleContextMenuEvent(platformMouseEvent, page);
2547 #endif
2548             return handled;
2549         }
2550         case PlatformEvent::MouseReleased:
2551             return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2552
2553         case PlatformEvent::MouseMoved:
2554 #if PLATFORM(COCOA)
2555             // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2556             // button is currently pressed. It is possible that neither of those things will be true since on
2557             // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2558             // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2559             // efficient scrollbars-only version of the event.
2560             if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2561                 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2562 #endif
2563             return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2564
2565         case PlatformEvent::MouseForceChanged:
2566         case PlatformEvent::MouseForceDown:
2567         case PlatformEvent::MouseForceUp:
2568             return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2569
2570         default:
2571             ASSERT_NOT_REACHED();
2572             return false;
2573     }
2574 }
2575
2576 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2577 {
2578     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2579
2580     m_userActivityHysteresis.impulse();
2581
2582     bool shouldHandleEvent = true;
2583
2584 #if ENABLE(CONTEXT_MENUS)
2585     // Don't try to handle any pending mouse events if a context menu is showing.
2586     if (m_isShowingContextMenu)
2587         shouldHandleEvent = false;
2588 #endif
2589 #if ENABLE(DRAG_SUPPORT)
2590     if (m_isStartingDrag)
2591         shouldHandleEvent = false;
2592 #endif
2593
2594     if (!shouldHandleEvent) {
2595         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2596         return;
2597     }
2598
2599     bool handled = false;
2600
2601 #if !PLATFORM(IOS_FAMILY)
2602     if (!handled && m_headerBanner)
2603         handled = m_headerBanner->mouseEvent(mouseEvent);
2604     if (!handled && m_footerBanner)
2605         handled = m_footerBanner->mouseEvent(mouseEvent);
2606 #endif // !PLATFORM(IOS_FAMILY)
2607
2608     if (!handled) {
2609         CurrentEvent currentEvent(mouseEvent);
2610         handled = handleMouseEvent(mouseEvent, this);
2611     }
2612
2613     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2614 }
2615
2616 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2617 {
2618     Frame& frame = page->mainFrame();
2619     if (!frame.view())
2620         return false;
2621
2622     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2623     return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2624 }
2625
2626 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2627 {
2628     m_userActivityHysteresis.impulse();
2629
2630     CurrentEvent currentEvent(wheelEvent);
2631
2632     bool handled = handleWheelEvent(wheelEvent, m_page.get());
2633
2634     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2635 }
2636
2637 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2638 {
2639     if (!page->mainFrame().view())
2640         return false;
2641
2642     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2643         return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2644     return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2645 }
2646
2647 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2648 {
2649     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2650
2651     m_userActivityHysteresis.impulse();
2652
2653     PlatformKeyboardEvent::setCurrentModifierState(platform(keyboardEvent).modifiers());
2654
2655     CurrentEvent currentEvent(keyboardEvent);
2656
2657     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2658     // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2659     if (!handled)
2660         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2661
2662     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2663 }
2664
2665 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2666 {
2667     bool isEnabled = false;
2668     int32_t state = 0;
2669     Frame& frame = m_page->focusController().focusedOrMainFrame();
2670     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2671         isEnabled = pluginView->isEditingCommandEnabled(commandName);
2672     else {
2673         Editor::Command command = frame.editor().command(commandName);
2674         state = command.state();
2675         isEnabled = command.isSupported() && command.isEnabled();
2676     }
2677
2678     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2679 }
2680
2681 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2682 {
2683     executeEditingCommand(commandName, argument);
2684 }
2685
2686 void WebPage::setNeedsFontAttributes(bool needsFontAttributes)
2687 {
2688     if (m_needsFontAttributes == needsFontAttributes)
2689         return;
2690
2691     m_needsFontAttributes = needsFontAttributes;
2692
2693     if (m_needsFontAttributes)
2694         sendPartialEditorStateAndSchedulePostLayoutUpdate();
2695 }
2696
2697 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest, WebBackForwardListProxy::OverwriteExistingItem overwrite)
2698 {
2699     for (const auto& itemState : itemStates) {
2700         auto historyItem = toHistoryItem(itemState);
2701         historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2702         static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, overwrite);
2703     }
2704 }
2705
2706 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2707 {
2708     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes, WebBackForwardListProxy::OverwriteExistingItem::No);
2709 }
2710
2711 void WebPage::updateBackForwardListForReattach(const Vector<WebKit::BackForwardListItemState>& itemStates)
2712 {
2713     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2714 }
2715
2716 void WebPage::setCurrentHistoryItemForReattach(WebKit::BackForwardListItemState&& itemState)
2717 {
2718     auto historyItem = toHistoryItem(itemState);
2719     auto& historyItemRef = historyItem.get();
2720     static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2721     corePage()->mainFrame().loader().history().setCurrentItem(historyItemRef);
2722 }
2723
2724 void WebPage::requestFontAttributesAtSelectionStart(CallbackID callbackID)
2725 {
2726     auto attributes = m_page->focusController().focusedOrMainFrame().editor().fontAttributesAtSelectionStart();
2727     send(Messages::WebPageProxy::FontAttributesCallback(attributes, callbackID));
2728 }
2729
2730 void WebPage::cancelGesturesBlockedOnSynchronousReplies()
2731 {
2732 #if ENABLE(IOS_TOUCH_EVENTS)
2733     if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2734         reply(true);
2735 #endif
2736
2737 #if PLATFORM(IOS_FAMILY)
2738     if (auto reply = WTFMove(m_pendingSynchronousPositionInformationReply))
2739         reply(InteractionInformationAtPosition::invalidInformation());
2740 #endif
2741 }
2742
2743 #if ENABLE(TOUCH_EVENTS)
2744 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2745 {
2746     if (!page->mainFrame().view())
2747         return false;
2748
2749     return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2750 }
2751 #endif
2752
2753 #if ENABLE(IOS_TOUCH_EVENTS)
2754 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2755 {
2756     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2757
2758     m_lastInteractionLocation = touchEvent.position();
2759     CurrentEvent currentEvent(touchEvent);
2760     handled = handleTouchEvent(touchEvent, m_page.get());
2761     updatePotentialTapSecurityOrigin(touchEvent, handled);
2762 }
2763
2764 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, CompletionHandler<void(bool)>&& reply)
2765 {
2766     m_pendingSynchronousTouchEventReply = WTFMove(reply);
2767
2768     EventDispatcher::TouchEventQueue queuedEvents;
2769     WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2770     dispatchAsynchronousTouchEvents(queuedEvents);
2771
2772     bool handled = true;
2773     dispatchTouchEvent(touchEvent, handled);
2774
2775     if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2776         reply(handled);
2777 }
2778
2779 void WebPage::updatePotentialTapSecurityOrigin(const WebTouchEvent& touchEvent, bool wasHandled)
2780 {
2781     if (wasHandled)
2782         return;
2783
2784     if (!touchEvent.isPotentialTap())
2785         return;
2786
2787     if (touchEvent.type() != WebEvent::TouchStart)
2788         return;
2789
2790     auto& mainFrame = m_page->mainFrame();
2791     auto document = mainFrame.document();
2792     if (!document)
2793         return;
2794
2795     if (!document->handlingTouchEvent())
2796         return;
2797
2798     Frame* touchEventTargetFrame = &mainFrame;
2799     while (auto subframe = touchEventTargetFrame->eventHandler().touchEventTargetSubframe())
2800         touchEventTargetFrame = subframe;
2801
2802     auto& touches = touchEventTargetFrame->eventHandler().touches();
2803     if (touches.isEmpty())
2804         return;
2805
2806     ASSERT(touches.size() == 1);
2807
2808     if (auto targetDocument = touchEventTargetFrame->document())
2809         m_potentialTapSecurityOrigin = &targetDocument->securityOrigin();
2810 }
2811 #elif ENABLE(TOUCH_EVENTS)
2812 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2813 {
2814     CurrentEvent currentEvent(touchEvent);
2815
2816     bool handled = handleTouchEvent(touchEvent, m_page.get());
2817
2818     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2819 }
2820 #endif
2821
2822 #if ENABLE(POINTER_EVENTS)
2823 void WebPage::cancelPointer(int32_t pointerId, const WebCore::IntPoint& documentPoint)
2824 {
2825     m_page->pointerCaptureController().cancelPointer(pointerId, documentPoint);
2826 }
2827 #endif
2828
2829 #if ENABLE(MAC_GESTURE_EVENTS)
2830 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2831 {
2832     if (!page->mainFrame().view())
2833         return false;
2834
2835     return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2836 }
2837
2838 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2839 {
2840     CurrentEvent currentEvent(gestureEvent);
2841     bool handled = handleGestureEvent(gestureEvent, m_page.get());
2842     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2843 }
2844 #endif
2845
2846 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2847 {
2848     return page->userInputBridge().scrollRecursively(direction, granularity);
2849 }
2850
2851 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2852 {
2853     return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2854 }
2855
2856 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2857 {
2858     return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2859 }
2860
2861 void WebPage::centerSelectionInVisibleArea()
2862 {
2863     Frame& frame = m_page->focusController().focusedOrMainFrame();
2864     frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2865     findController().showFindIndicatorInSelection();
2866 }
2867
2868 bool WebPage::isControlledByAutomation() const
2869 {
2870     return m_page->isControlledByAutomation();
2871 }
2872
2873 void WebPage::setControlledByAutomation(bool controlled)
2874 {
2875     m_page->setControlledByAutomation(controlled);
2876 }
2877
2878 void WebPage::connectInspector(const String& targetId, Inspector::FrontendChannel::ConnectionType connectionType)
2879 {
2880     m_inspectorTargetController->connectInspector(targetId, connectionType);
2881 }
2882
2883 void WebPage::disconnectInspector(const String& targetId)
2884 {
2885     m_inspectorTargetController->disconnectInspector(targetId);
2886 }
2887
2888 void WebPage::sendMessageToTargetBackend(const String& targetId, const String& message)
2889 {
2890     m_inspectorTargetController->sendMessageToTargetBackend(targetId, message);
2891 }
2892
2893 void WebPage::insertNewlineInQuotedContent()
2894 {
2895     Frame& frame = m_page->focusController().focusedOrMainFrame();
2896     if (frame.selection().isNone())
2897         return;
2898     frame.editor().insertParagraphSeparatorInQuotedContent();
2899 }
2900
2901 #if ENABLE(REMOTE_INSPECTOR)
2902 void WebPage::setIndicating(bool indicating)
2903 {
2904     m_page->inspectorController().setIndicating(indicating);
2905 }
2906 #endif
2907
2908 void WebPage::setDrawsBackground(bool drawsBackground)
2909 {
2910     if (m_drawsBackground == drawsBackground)
2911         return;
2912
2913     m_drawsBackground = drawsBackground;
2914
2915     if (FrameView* frameView = mainFrameView()) {
2916         bool isTransparent = !drawsBackground;
2917         frameView->updateBackgroundRecursively(isTransparent);
2918     }
2919
2920     m_drawingArea->pageBackgroundTransparencyChanged();
2921     m_drawingArea->setNeedsDisplay();
2922 }
2923
2924 #if PLATFORM(COCOA)
2925 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
2926 {
2927     if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
2928         LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
2929         return;
2930     }
2931
2932     m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
2933
2934     setTopContentInset(contentInset);
2935
2936     deallocateSendRightSafely(fencePort.port());
2937 }
2938 #endif
2939
2940 void WebPage::setTopContentInset(float contentInset)
2941 {
2942     if (contentInset == m_page->topContentInset())
2943         return;
2944
2945     m_page->setTopContentInset(contentInset);
2946
2947     for (auto* pluginView : m_pluginViews)
2948         pluginView->topContentInsetDidChange();
2949 }
2950
2951 void WebPage::viewWillStartLiveResize()
2952 {
2953     if (!m_page)
2954         return;
2955
2956     // FIXME: This should propagate to all ScrollableAreas.
2957     Frame& frame = m_page->focusController().focusedOrMainFrame();
2958     if (FrameView* view = frame.view())
2959         view->willStartLiveResize();
2960 }
2961
2962 void WebPage::viewWillEndLiveResize()
2963 {
2964     if (!m_page)
2965         return;
2966
2967     // FIXME: This should propagate to all ScrollableAreas.
2968     Frame& frame = m_page->focusController().focusedOrMainFrame();
2969     if (FrameView* view = frame.view())
2970         view->willEndLiveResize();
2971 }
2972
2973 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
2974 {
2975     if (!m_page)
2976         return;
2977
2978     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2979
2980     Frame& frame = m_page->focusController().focusedOrMainFrame();
2981     frame.document()->setFocusedElement(0);
2982
2983     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2984         PlatformKeyboardEvent platformEvent(platform(event));
2985         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2986         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
2987
2988         send(Messages::WebPageProxy::VoidCallback(callbackID));
2989         return;
2990     }
2991
2992     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
2993     send(Messages::WebPageProxy::VoidCallback(callbackID));
2994 }
2995
2996 void WebPage::setCanStartMediaTimerFired()
2997 {
2998     if (m_page)
2999         m_page->setCanStartMedia(true);
3000 }
3001
3002 void WebPage::updateIsInWindow(bool isInitialState)
3003 {
3004     bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
3005
3006     if (!isInWindow) {
3007         m_setCanStartMediaTimer.stop();
3008         m_page->setCanStartMedia(false);
3009         
3010         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
3011         if (!isInitialState)
3012             WebProcess::singleton().pageWillLeaveWindow(m_pageID);
3013     } else {
3014         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
3015         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
3016         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
3017         if (m_mayStartMediaWhenInWindow)
3018             m_setCanStartMediaTimer.startOneShot(0_s);
3019
3020         WebProcess::singleton().pageDidEnterWindow(m_pageID);
3021     }
3022
3023     if (isInWindow)
3024         layoutIfNeeded();
3025 }
3026
3027 void WebPage::visibilityDidChange()
3028 {
3029     bool isVisible = m_activityState.contains(ActivityState::IsVisible);
3030     if (!isVisible) {
3031         // We save the document / scroll state when backgrounding a tab so that we are able to restore it
3032         // if it gets terminated while in the background.
3033         if (auto* frame = m_mainFrame->coreFrame())
3034             frame->loader().history().saveDocumentAndScrollState();
3035     }
3036 }
3037
3038 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
3039 {
3040     LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
3041
3042     auto changed = m_activityState ^ activityState;
3043     m_activityState = activityState;
3044
3045     if (changed)
3046         updateThrottleState();
3047
3048     {
3049         SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
3050         m_page->setActivityState(activityState);
3051     }
3052     
3053     for (auto* pluginView : m_pluginViews)
3054         pluginView->activityStateDidChange(changed);
3055
3056     m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
3057     WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
3058
3059     if (changed & ActivityState::IsInWindow)
3060         updateIsInWindow();
3061
3062     if (changed & ActivityState::IsVisible)
3063         visibilityDidChange();
3064 }
3065
3066 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
3067 {
3068     m_layerHostingMode = layerHostingMode;
3069
3070     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
3071
3072     for (auto* pluginView : m_pluginViews)
3073         pluginView->setLayerHostingMode(m_layerHostingMode);
3074 }
3075
3076 void WebPage::setSessionID(PAL::SessionID sessionID)
3077 {
3078     m_page->setSessionID(sessionID);
3079 }
3080
3081 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, Optional<WebsitePoliciesData>&& websitePolicies)
3082 {
3083     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3084     if (!frame)
3085         return;
3086     frame->didReceivePolicyDecision(listenerID, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
3087 }
3088
3089 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
3090 {
3091     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3092     if (!frame)
3093         return;
3094     frame->continueWillSubmitForm(listenerID);
3095 }
3096
3097 void WebPage::didStartPageTransition()
3098 {
3099     freezeLayerTree(LayerTreeFreezeReason::PageTransition);
3100
3101 #if PLATFORM(MAC)
3102     bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
3103 #endif
3104     m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
3105     m_isFocusingElementDueToUserInteraction = false;
3106     m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
3107 #if PLATFORM(MAC)
3108     if (hasPreviouslyFocusedDueToUserInteraction)
3109         send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
3110     if (m_needsHiddenContentEditableQuirk) {
3111         m_needsHiddenContentEditableQuirk = false;
3112         send(Messages::WebPageProxy::SetNeedsHiddenContentEditableQuirk(m_needsHiddenContentEditableQuirk));
3113     }
3114     if (m_needsPlainTextQuirk) {
3115         m_needsPlainTextQuirk = false;
3116         send(Messages::WebPageProxy::SetNeedsPlainTextQuirk(m_needsPlainTextQuirk));
3117     }
3118 #endif
3119 }
3120
3121 void WebPage::didCompletePageTransition()
3122 {
3123     unfreezeLayerTree(LayerTreeFreezeReason::PageTransition);
3124
3125     bool isInitialEmptyDocument = !m_mainFrame;
3126     if (!isInitialEmptyDocument)
3127         unfreezeLayerTree(LayerTreeFreezeReason::ProcessSwap);
3128 }
3129
3130 void WebPage::show()
3131 {
3132     send(Messages::WebPageProxy::ShowPage());
3133 }
3134
3135 String WebPage::userAgent(const URL& webCoreURL) const
3136 {
3137     return userAgent(nullptr, webCoreURL);
3138 }
3139
3140 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
3141 {
3142     if (frame) {
3143         String userAgent = m_loaderClient->userAgentForURL(*frame, webcoreURL);
3144         if (!userAgent.isEmpty())
3145             return userAgent;
3146     }
3147
3148     String userAgent = platformUserAgent(webcoreURL);
3149     if (!userAgent.isEmpty())
3150         return userAgent;
3151     return m_userAgent;
3152 }
3153     
3154 void WebPage::setUserAgent(const String& userAgent)
3155 {
3156     if (m_userAgent == userAgent)
3157         return;
3158
3159     m_userAgent = userAgent;
3160
3161     if (m_page)
3162         m_page->userAgentChanged();
3163 }
3164
3165 void WebPage::suspendActiveDOMObjectsAndAnimations()
3166 {
3167     m_page->suspendActiveDOMObjectsAndAnimations();
3168 }
3169
3170 void WebPage::resumeActiveDOMObjectsAndAnimations()
3171 {
3172     m_page->resumeActiveDOMObjectsAndAnimations();
3173 }
3174
3175 IntPoint WebPage::screenToRootView(const IntPoint& point)
3176 {
3177     IntPoint windowPoint;
3178     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
3179     return windowPoint;
3180 }
3181     
3182 IntRect WebPage::rootViewToScreen(const IntRect& rect)
3183 {
3184     IntRect screenRect;
3185     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
3186     return screenRect;
3187 }
3188     
3189 #if PLATFORM(IOS_FAMILY)
3190 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
3191 {
3192     IntPoint windowPoint;
3193     sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
3194     return windowPoint;
3195 }
3196
3197 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
3198 {
3199     IntRect screenRect;
3200     sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
3201     return screenRect;
3202 }
3203 #endif
3204
3205 KeyboardUIMode WebPage::keyboardUIMode()
3206 {
3207     bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
3208     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
3209 }
3210
3211 void WebPage::runJavaScript(const String& script, bool forceUserGesture, Optional<String> worldName, CallbackID callbackID)
3212 {
3213     // NOTE: We need to be careful when running scripts that the objects we depend on don't
3214     // disappear during script execution.
3215
3216     RefPtr<SerializedScriptValue> serializedResultValue;
3217     JSLockHolder lock(commonVM());
3218     bool hadException = true;
3219     ExceptionDetails details;
3220     auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
3221     if (world) {
3222         if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
3223             hadException = false;
3224             serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
3225                 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
3226         }
3227     }
3228
3229     IPC::DataReference dataReference;
3230     if (serializedResultValue)
3231         dataReference = serializedResultValue->data();
3232     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
3233 }
3234
3235 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
3236 {
3237     runJavaScript(script, forceUserGesture, WTF::nullopt, callbackID);
3238 }
3239
3240 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
3241 {
3242     runJavaScript(script, forceUserGesture, worldName, callbackID);
3243 }
3244
3245 void WebPage::getContentsAsString(CallbackID callbackID)
3246 {
3247     String resultString = m_mainFrame->contentsAsString();
3248     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3249 }
3250
3251 #if ENABLE(MHTML)
3252 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
3253 {
3254     send(Messages::WebPageProxy::DataCallback({ MHTMLArchive::generateMHTMLData(m_page.get()) }, callbackID));
3255 }
3256 #endif
3257
3258 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3259 {
3260     String resultString = renderTreeExternalRepresentation();
3261     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3262 }
3263
3264 static Frame* frameWithSelection(Page* page)
3265 {
3266     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3267         if (frame->selection().isRange())
3268             return frame;
3269     }
3270
3271     return 0;
3272 }
3273
3274 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3275 {
3276 #if PLATFORM(COCOA)
3277     RetainPtr<CFDataRef> data;
3278     if (Frame* frame = frameWithSelection(m_page.get()))
3279         data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3280 #endif
3281
3282     IPC::SharedBufferDataReference dataReference;
3283 #if PLATFORM(COCOA)
3284     if (data)
3285         dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3286 #endif
3287     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3288 }
3289
3290 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3291 {
3292     WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3293     String resultString = focusedOrMainFrame->selectionAsString();
3294     if (resultString.isEmpty())
3295         resultString = focusedOrMainFrame->contentsAsString();
3296     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3297 }
3298
3299 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3300 {
3301     String resultString;
3302     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3303        resultString = frame->source();
3304
3305     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3306 }
3307
3308 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3309 {
3310     RefPtr<SharedBuffer> buffer;
3311     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3312         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3313             buffer = pluginView->liveResourceData();
3314         if (!buffer) {
3315             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3316                 buffer = loader->mainResourceData();
3317         }
3318     }
3319
3320     IPC::SharedBufferDataReference dataReference;
3321     if (buffer)
3322         dataReference = { *buffer };
3323     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3324 }
3325
3326 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3327 {
3328     DocumentLoader* loader = frame->loader().documentLoader();
3329     if (!loader)
3330         return nullptr;
3331
3332     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3333     if (!subresource)
3334         return nullptr;
3335
3336     return &subresource->data();
3337 }
3338
3339 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3340 {
3341     RefPtr<SharedBuffer> buffer;
3342     if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3343         URL resourceURL(URL(), resourceURLString);
3344         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3345     }
3346
3347     IPC::SharedBufferDataReference dataReference;
3348     if (buffer)
3349         dataReference = { *buffer };
3350     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3351 }
3352
3353 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3354 {
3355 #if PLATFORM(COCOA)
3356     RetainPtr<CFDataRef> data;
3357     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3358         data = frame->webArchiveData(nullptr, nullptr);
3359 #else
3360     UNUSED_PARAM(frameID);
3361 #endif
3362
3363     IPC::SharedBufferDataReference dataReference;
3364 #if PLATFORM(COCOA)
3365     if (data)
3366         dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3367 #endif
3368     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3369 }
3370
3371 void WebPage::forceRepaintWithoutCallback()
3372 {
3373     m_drawingArea->forceRepaint();
3374 }
3375
3376 void WebPage::forceRepaint(CallbackID callbackID)
3377 {
3378     if (m_drawingArea->forceRepaintAsync(callbackID))
3379         return;
3380
3381     forceRepaintWithoutCallback();
3382     send(Messages::WebPageProxy::VoidCallback(callbackID));
3383 }
3384
3385 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3386 {
3387     WebPreferencesStore::removeTestRunnerOverrides();
3388     updatePreferences(store);
3389 }
3390
3391 void WebPage::updatePreferences(const WebPreferencesStore& store)
3392 {
3393     updatePreferencesGenerated(store);
3394
3395     Settings& settings = m_page->settings();
3396
3397     if (!settings.acceleratedCompositingEnabled()) {
3398         RELEASE_LOG_IF_ALLOWED("%p - WebPage - acceleratedCompositingEnabled setting was false. WebKit cannot function in this mode; changing setting to true", this);
3399         settings.setAcceleratedCompositingEnabled(true);
3400     }
3401
3402     bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3403     settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3404     settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3405     settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3406     settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3407     settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3408     settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3409     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3410     settings.setFrameFlattening(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()) ? WebCore::FrameFlattening::FullyEnabled : WebCore::FrameFlattening::Disabled);
3411     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3412 #if ENABLE(DATA_DETECTION)
3413     settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3414 #endif
3415
3416     DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3417
3418     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3419     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3420     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3421     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3422
3423     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3424     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3425
3426     if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3427         setSessionID(PAL::SessionID::legacyPrivateSessionID());
3428     else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3429         setSessionID(PAL::SessionID::defaultSessionID());
3430
3431     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3432     if (m_processSuppressionEnabled != processSuppressionEnabled) {
3433         m_processSuppressionEnabled = processSuppressionEnabled;
3434         updateThrottleState();
3435     }
3436
3437 #if PLATFORM(COCOA)
3438     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3439 #endif
3440 #if ENABLE(PAYMENT_REQUEST)
3441     settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3442 #endif
3443
3444     // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3445     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3446
3447 #if PLATFORM(IOS_FAMILY)
3448     m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3449     m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3450     setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3451
3452     settings.setUseImageDocumentForSubframePDF(true);
3453 #if HAVE(AVKIT)
3454     DeprecatedGlobalSettings::setAVKitEnabled(true);
3455 #endif
3456 #endif
3457
3458 #if ENABLE(SERVICE_WORKER)
3459     if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3460         ASSERT(parentProcessHasServiceWorkerEntitlement());
3461         if (!parentProcessHasServiceWorkerEntitlement())
3462             RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3463     }
3464 #endif
3465
3466     settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3467
3468     if (m_drawingArea)
3469         m_drawingArea->updatePreferences(store);
3470 }
3471
3472 #if ENABLE(DATA_DETECTION)
3473
3474 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3475 {
3476     DataDetectionResult dataDetectionResult;
3477     dataDetectionResult.results = detectionResults;
3478     send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3479 }
3480
3481 void WebPage::removeDataDetectedLinks(CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3482 {
3483     for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3484         auto document = makeRefPtr(frame->document());
3485         if (!document)
3486             continue;
3487
3488         DataDetection::removeDataDetectedLinksInDocument(*document);
3489         frame->setDataDetectionResults(nullptr);
3490     }
3491     completionHandler({ m_page->mainFrame().dataDetectionResults() });
3492 }
3493
3494 void WebPage::detectDataInAllFrames(uint64_t types, CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3495 {
3496     auto dataDetectorTypes = static_cast<WebCore::DataDetectorTypes>(types);
3497     for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3498         auto document = makeRefPtr(frame->document());
3499         if (!document)
3500             continue;
3501
3502         RefPtr<Range> range = Range::create(*document, Position { document.get(), Position::PositionIsBeforeChildren }, Position { document.get(), Position::PositionIsAfterChildren });
3503         frame->setDataDetectionResults(DataDetection::detectContentInRange(range, dataDetectorTypes, m_dataDetectionContext.get()));
3504     }
3505     completionHandler({ m_page->mainFrame().dataDetectionResults() });
3506 }
3507
3508 #endif // ENABLE(DATA_DETECTION)
3509
3510 #if PLATFORM(COCOA)
3511 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3512 {
3513     FrameView* frameView = corePage()->mainFrame().view();
3514     if (!frameView)
3515         return;
3516
3517     layerTransaction.setContentsSize(frameView->contentsSize());
3518     layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3519     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3520     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3521     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3522
3523     layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3524     layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3525     layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3526
3527 #if PLATFORM(IOS_FAMILY)
3528     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3529     layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3530     layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3531     layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3532     layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3533     layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3534     layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3535     layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3536     layerTransaction.setIsInStableState(m_isInStableState);
3537     layerTransaction.setAllowsUserScaling(allowsUserScaling());
3538     if (m_pendingDynamicViewportSizeUpdateID) {
3539         layerTransaction.setDynamicViewportSizeUpdateID(*m_pendingDynamicViewportSizeUpdateID);
3540         m_pendingDynamicViewportSizeUpdateID = WTF::nullopt;
3541     }
3542     if (m_lastTransactionPageScaleFactor != layerTransaction.pageScaleFactor()) {
3543         m_lastTransactionPageScaleFactor = layerTransaction.pageScaleFactor();
3544         m_lastTransactionIDWithScaleChange = layerTransaction.transactionID();
3545     }
3546 #endif
3547
3548     layerTransaction.setScrollPosition(frameView->scrollPosition());
3549
3550     if (m_hasPendingEditorStateUpdate) {
3551         layerTransaction.setEditorState(editorState());
3552         m_hasPendingEditorStateUpdate = false;
3553     }
3554 }
3555
3556 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3557 {
3558 #if PLATFORM(IOS_FAMILY)
3559     if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3560         Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3561         m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3562
3563         m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3564     }
3565 #else
3566     UNUSED_PARAM(timestamp);
3567 #endif
3568 }
3569 #endif
3570
3571 void WebPage::willDisplayPage()
3572 {
3573     m_page->willDisplayPage();
3574 }
3575
3576 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3577 {
3578     if (m_isClosed)
3579         return nullptr;
3580     if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3581         m_inspector = WebInspector::create(this);
3582     return m_inspector.get();
3583 }
3584
3585 WebInspectorUI* WebPage::inspectorUI()
3586 {
3587     if (m_isClosed)
3588         return nullptr;
3589     if (!m_inspectorUI)
3590         m_inspectorUI = WebInspectorUI::create(*this);
3591     return m_inspectorUI.get();
3592 }
3593
3594 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3595 {
3596     if (m_isClosed)
3597         return nullptr;
3598     if (!m_remoteInspectorUI)
3599         m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3600     return m_remoteInspectorUI.get();
3601 }
3602
3603 void WebPage::inspectorFrontendCountChanged(unsigned count)
3604 {
3605     send(Messages::WebPageProxy::DidChangeInspectorFrontendCount(count));
3606 }
3607
3608 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3609 PlaybackSessionManager& WebPage::playbackSessionManager()
3610 {
3611     if (!m_playbackSessionManager)
3612         m_playbackSessionManager = PlaybackSessionManager::create(*this);
3613     return *m_playbackSessionManager;
3614 }
3615
3616 VideoFullscreenManager& WebPage::videoFullscreenManager()
3617 {
3618     if (!m_videoFullscreenManager)
3619         m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3620     return *m_videoFullscreenManager;
3621 }
3622
3623 void WebPage::videoControlsManagerDidChange()
3624 {
3625 #if ENABLE(FULLSCREEN_API)
3626     if (auto* manager = fullScreenManager())
3627         manager->videoControlsManagerDidChange();
3628 #endif
3629 }
3630
3631 #endif
3632
3633 #if PLATFORM(IOS_FAMILY)
3634 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3635 {
3636     m_page->setAllowsMediaDocumentInlinePlayback(allows);
3637 }
3638 #endif
3639
3640 #if ENABLE(FULLSCREEN_API)
3641 WebFullScreenManager* WebPage::fullScreenManager()
3642 {
3643     if (!m_fullScreenManager)
3644         m_fullScreenManager = WebFullScreenManager::create(this);
3645     return m_fullScreenManager.get();
3646 }
3647 #endif
3648
3649 void WebPage::addConsoleMessage(uint64_t frameID, MessageSource messageSource, MessageLevel messageLevel, const String& message, uint64_t requestID)
3650 {
3651     if (auto* frame = WebProcess::singleton().webFrame(frameID))
3652         frame->addConsoleMessage(messageSource, messageLevel, message, requestID);
3653 }
3654
3655 void WebPage::sendCSPViolationReport(uint64_t frameID, const URL& reportURL, IPC::FormDataReference&& reportData)
3656 {
3657     auto report = reportData.takeData();
3658     if (!report)
3659         return;
3660     if (auto* frame = WebProcess::singleton().webFrame(frameID))
3661         PingLoader::sendViolationReport(*frame->coreFrame(), reportURL, report.releaseNonNull(), ViolationReportType::ContentSecurityPolicy);
3662 }
3663
3664 void WebPage::enqueueSecurityPolicyViolationEvent(uint64_t frameID, SecurityPolicyViolationEvent::Init&& eventInit)
3665 {
3666     auto* frame = WebProcess::singleton().webFrame(frameID);
3667     if (!frame)
3668         return;
3669     auto* coreFrame = frame->coreFrame();
3670     if (!coreFrame)
3671         return;
3672     if (auto* document = coreFrame->document())
3673         document->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
3674 }
3675
3676 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3677 {
3678     if (m_notificationPermissionRequestManager)
3679         return m_notificationPermissionRequestManager.get();
3680
3681     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3682     return m_notificationPermissionRequestManager.get();
3683 }
3684
3685 #if ENABLE(DRAG_SUPPORT)
3686
3687 #if PLATFORM(GTK)
3688 void WebPage::performDragControllerAction(DragControllerAction action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3689 {
3690     if (!m_page) {
3691         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3692         return;
3693     }
3694
3695     DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3696     switch (action) {
3697     case DragControllerAction::Entered: {
3698         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3699         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3700         return;
3701     }
3702     case DragControllerAction::Updated: {
3703         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3704         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3705         return;
3706     }
3707     case DragControllerAction::Exited:
3708         m_page->dragController().dragExited(dragData);
3709         return;
3710
3711     case DragControllerAction::PerformDragOperation: {
3712         m_page->dragController().performDragOperation(dragData);
3713         return;
3714     }
3715     }
3716     ASSERT_NOT_REACHED();
3717 }
3718 #else
3719 void WebPage::performDragControllerAction(DragControllerAction action, const WebCore::DragData& dragData, SandboxExtension::Handle&& sandboxExtensionHandle, SandboxExtension::HandleArray&& sandboxExtensionsHandleArray)
3720 {
3721     if (!m_page) {
3722         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3723         return;
3724     }
3725
3726     switch (action) {
3727     case DragControllerAction::Entered: {
3728         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3729         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()));
3730         return;
3731     }
3732     case DragControllerAction::Updated: {
3733         DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3734         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()));
3735         return;
3736     }
3737     case DragControllerAction::Exited:
3738         m_page->dragController().dragExited(dragData);
3739         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3740         return;
3741         
3742     case DragControllerAction::PerformDragOperation: {
3743         ASSERT(!m_pendingDropSandboxExtension);
3744
3745         m_pendingDropSandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
3746         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3747             if (auto extension = SandboxExtension::create(WTFMove(sandboxExtensionsHandleArray[i])))
3748                 m_pendingDropExtensionsForFileUpload.append(extension);
3749         }
3750
3751         bool handled = m_page->dragController().performDragOperation(dragData);
3752
3753         // If we started loading a local file, the sandbox extension tracker would have adopted this
3754         // pending drop sandbox extension. If not, we'll play it safe and clear it.
3755         m_pendingDropSandboxExtension = nullptr;
3756
3757         m_pendingDropExtensionsForFileUpload.clear();
3758         send(Messages::WebPageProxy::DidPerformDragOperation(handled));
3759         return;
3760     }
3761     }
3762     ASSERT_NOT_REACHED();
3763 }
3764 #endif
3765
3766 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3767 {
3768     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3769     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3770
3771     m_page->dragController().dragEnded();
3772     FrameView* view = m_page->mainFrame().view();
3773     if (!view)
3774         return;
3775     // FIXME: These are fake modifier keys here, but they should be real ones instead.
3776     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), 0, WebCore::NoTap);
3777     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3778
3779     send(Messages::WebPageProxy::DidEndDragging());
3780 }
3781
3782 void WebPage::willPerformLoadDragDestinationAction()
3783 {
3784     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(WTFMove(m_pendingDropSandboxExtension));
3785 }
3786
3787 void WebPage::mayPerformUploadDragDestinationAction()
3788 {
3789     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3790         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3791     m_pendingDropExtensionsForFileUpload.clear();
3792 }
3793
3794 void WebPage::didStartDrag()
3795 {
3796     m_isStartingDrag = false;
3797     m_page->mainFrame().eventHandler().didStartDrag();
3798 }
3799
3800 void WebPage::dragCancelled()
3801 {
3802     m_isStartingDrag = false;
3803     m_page->mainFrame().eventHandler().dragCancelled();
3804 }
3805     
3806 #endif // ENABLE(DRAG_SUPPORT)
3807
3808 WebUndoStep* WebPage::webUndoStep(WebUndoStepID stepID)
3809 {
3810     return m_undoStepMap.get(stepID);
3811 }
3812
3813 void WebPage::addWebUndoStep(WebUndoStepID stepID, Ref<WebUndoStep>&& entry)
3814 {
3815     auto addResult = m_undoStepMap.set(stepID, WTFMove(entry));
3816     ASSERT_UNUSED(addResult, addResult.isNewEntry);
3817 }
3818
3819 void WebPage::removeWebEditCommand(WebUndoStepID stepID)
3820 {
3821     if (auto undoStep = m_undoStepMap.take(stepID))
3822         undoStep->didRemoveFromUndoManager();
3823 }
3824
3825 bool WebPage::isAlwaysOnLoggingAllowed() const
3826 {
3827     return corePage() && corePage()->isAlwaysOnLoggingAllowed();
3828 }
3829
3830 void WebPage::unapplyEditCommand(WebUndoStepID stepID)
3831 {
3832     auto* step = webUndoStep(stepID);
3833     if (!step)
3834         return;
3835
3836     step->step().unapply();
3837 }
3838
3839 void WebPage::reapplyEditCommand(WebUndoStepID stepID)
3840 {
3841     auto* step = webUndoStep(stepID);
3842     if (!step)
3843         return;
3844
3845     m_isInRedo = true;
3846     step->step().reapply();
3847     m_isInRedo = false;
3848 }
3849
3850 void WebPage::didRemoveEditCommand(WebUndoStepID commandID)
3851 {
3852     removeWebEditCommand(commandID);
3853 }
3854
3855 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3856 {
3857     m_activePopupMenu = menu;
3858 }
3859
3860 #if ENABLE(INPUT_TYPE_COLOR)
3861
3862 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3863 {
3864     m_activeColorChooser = colorChooser;
3865 }
3866
3867 void WebPage::didEndColorPicker()
3868 {
3869     m_activeColorChooser->didEndChooser();
3870 }
3871
3872 void WebPage::didChooseColor(const WebCore::Color& color)
3873 {
3874     m_activeColorChooser->didChooseColor(color);
3875 }
3876
3877 #endif
3878
3879 #if ENABLE(DATALIST_ELEMENT)
3880
3881 void WebPage::setActiveDataListSuggestionPicker(WebDataListSuggestionPicker* dataListSuggestionPicker)
3882 {
3883     m_activeDataListSuggestionPicker = dataListSuggestionPicker;
3884 }
3885
3886 void WebPage::didSelectDataListOption(const String& selectedOption)
3887 {
3888     m_activeDataListSuggestionPicker->didSelectOption(selectedOption);
3889 }
3890
3891 void WebPage::didCloseSuggestions()
3892 {
3893     if (m_activeDataListSuggestionPicker)
3894         m_activeDataListSuggestionPicker->didCloseSuggestions();
3895     m_activeDataListSuggestionPicker = nullptr;
3896 }
3897
3898 #endif
3899
3900 void WebPage::setActiveOpenPanelResultListener(Ref<WebOpenPanelResultListener>&& openPanelResultListener)
3901 {
3902     m_activeOpenPanelResultListener = WTFMove(openPanelResultListener);
3903 }
3904
3905 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3906 {
3907     return m_page->findString(target, core(options));
3908 }
3909
3910 void WebPage::findStringMatchesFromInjectedBundle(const String& target, FindOptions options)
3911 {
3912     findController().findStringMatches(target, options, 0);
3913 }
3914
3915 void WebPage::replaceStringMatchesFromInjectedBundle(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly)
3916 {
3917     findController().replaceMatches(matchIndices, replacementText, selectionOnly);
3918 }
3919
3920 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3921 {
3922     findController().findString(string, static_cast<FindOptions>(options), maxMatchCount);
3923 }
3924
3925 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3926 {
3927     findController().findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3928 }
3929
3930 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3931 {
3932     findController().getImageForFindMatch(matchIndex);
3933 }
3934
3935 void WebPage::selectFindMatch(uint32_t matchIndex)
3936 {
3937     findController().selectFindMatch(matchIndex);
3938 }
3939
3940 void WebPage::hideFindUI()
3941 {
3942     findController().hideFindUI();
3943 }
3944
3945 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3946 {
3947     findController().countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3948 }
3949
3950 void WebPage::replaceMatches(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly, CallbackID callbackID)
3951 {
3952     auto numberOfReplacements = findController().replaceMatches(matchIndices, replacementText, selectionOnly);
3953     send(Messages::WebPageProxy::UnsignedCallback(numberOfReplacements, callbackID));
3954 }
3955
3956 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3957 {
3958     changeSelectedIndex(newIndex);
3959     m_activePopupMenu = nullptr;
3960 }
3961
3962 void WebPage::changeSelectedIndex(int32_t index)
3963 {
3964     if (!m_activePopupMenu)
3965         return;
3966
3967     m_activePopupMenu->didChangeSelectedIndex(index);
3968 }
3969
3970 #if PLATFORM(IOS_FAMILY)
3971 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3972 {
3973     if (!m_activeOpenPanelResultListener)
3974         return;
3975
3976     RefPtr<Icon> icon;
3977     if (!iconData.isEmpty()) {
3978         RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3979         RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3980         RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3981         icon = Icon::createIconForImage(imageRef.get());
3982     }
3983
3984     m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3985     m_activeOpenPanelResultListener = nullptr;
3986 }
3987 #endif
3988
3989 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3990 {
3991     if (!m_activeOpenPanelResultListener)
3992         return;
3993
3994     m_activeOpenPanelResultListener->didChooseFiles(files);
3995     m_activeOpenPanelResultListener = nullptr;
3996 }
3997
3998 void WebPage::didCancelForOpenPanel()
3999 {
4000     m_activeOpenPanelResultListener = nullptr;
4001 }
4002
4003 #if ENABLE(SANDBOX_EXTENSIONS)
4004 void WebPage::extendSandboxForFilesFromOpenPanel(SandboxExtension::HandleArray&& handles)
4005 {
4006     for (size_t i = 0; i < handles.size(); ++i) {
4007         bool result = SandboxExtension::consumePermanently(handles[i]);
4008         if (!result) {
4009             // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
4010             WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
4011         }
4012     }
4013 }
4014 #endif
4015
4016 #if ENABLE(GEOLOCATION)
4017 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
4018 {
4019     geolocationPermissionRequestManager().didReceiveGeolocationPermissionDecision(geolocationID, allowed);
4020 }
4021 #endif
4022
4023 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
4024 {
4025     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
4026 }
4027
4028 #if ENABLE(MEDIA_STREAM)
4029
4030 #if !PLATFORM(IOS_FAMILY)
4031 void WebPage::prepareToSendUserMediaPermissionRequest()
4032 {
4033 }
4034 #endif
4035
4036 void WebPage::userMediaAccessWasGranted(uint64_t userMediaID, WebCore::CaptureDevice&& audioDevice, WebCore::CaptureDevice&& videoDevice, String&& mediaDeviceIdentifierHashSalt)
4037 {
4038     m_userMediaPermissionRequestManager->userMediaAccessWasGranted(userMediaID, WTFMove(audioDevice), WTFMove(videoDevice), WTFMove(mediaDeviceIdentifierHashSalt));
4039 }
4040
4041 void WebPage::userMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String&& invalidConstraint)
4042 {
4043     m_userMediaPermissionRequestManager->userMediaAccessWasDenied(userMediaID, static_cast<UserMediaRequest::MediaAccessDenialReason>(reason), WTFMove(invalidConstraint));
4044 }
4045
4046 void WebPage::didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vector<CaptureDevice>& devices, String&& deviceIdentifierHashSalt, bool originHasPersistentAccess)
4047 {
4048     m_userMediaPermissionRequestManager->didCompleteMediaDeviceEnumeration(userMediaID, devices, WTFMove(deviceIdentifierHashSalt), originHasPersistentAccess);
4049 }
4050
4051 void WebPage::captureDevicesChanged()
4052 {
4053     m_userMediaPermissionRequestManager->captureDevicesChanged();
4054 }
4055
4056 #if ENABLE(SANDBOX_EXTENSIONS)
4057 void WebPage::grantUserMediaDeviceSandboxExtensions(MediaDeviceSandboxExtensions&& extensions)
4058 {
4059     m_userMediaPermissionRequestManager->grantUserMediaDeviceSandboxExtensions(WTFMove(extensions));
4060 }
4061
4062 void WebPage::revokeUserMediaDeviceSandboxExtensions(const Vector<String>& extensionIDs)
4063 {
4064     m_userMediaPermissionRequestManager->revokeUserMediaDeviceSandboxExtensions(extensionIDs);
4065 }
4066 #endif
4067 #endif
4068
4069 #if !PLATFORM(IOS_FAMILY)
4070 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
4071 {
4072     Frame& frame = m_page->focusController().focusedOrMainFrame();
4073     frame.editor().advanceToNextMisspelling(startBeforeSelection);
4074 }
4075 #endif
4076
4077 bool WebPage::hasRichlyEditableSelection() const
4078 {
4079     auto& frame = m_page->focusController().focusedOrMainFrame();
4080     if (m_page->dragCaretController().isContentRichlyEditable())
4081         return true;
4082
4083     return frame.selection().selection().isContentRichlyEditable();
4084 }
4085
4086 void WebPage::changeSpellingToWord(const String& word)
4087 {
4088     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
4089 }
4090
4091 void WebPage::unmarkAllMisspellings()
4092 {
4093     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
4094         if (Document* document = frame->document())
4095             document->markers().removeMarkers(DocumentMarker::Spelling);
4096     }
4097 }
4098
4099 void WebPage::unmarkAllBadGrammar()
4100 {
4101     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
4102         if (Document* document = frame->document())
4103             document->markers().removeMarkers(DocumentMarker::Grammar);
4104     }
4105 }
4106
4107 #if USE(APPKIT)
4108 void WebPage::uppercaseWord()
4109 {
4110     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
4111 }
4112
4113 void WebPage::lowercaseWord()
4114 {
4115     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
4116 }
4117
4118 void WebPage::capitalizeWord()
4119 {
4120     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
4121 }
4122 #endif
4123     
4124 void WebPage::setTextForActivePopupMenu(int32_t index)
4125 {
4126     if (!m_activePopupMenu)
4127         return;
4128
4129     m_activePopupMenu->setTextForIndex(index);
4130 }
4131
4132 #if PLATFORM(GTK)
4133 void WebPage::failedToShowPopupMenu()
4134 {
4135     if (!m_activePopupMenu)
4136         return;
4137
4138     m_activePopupMenu->client()->popupDidHide();
4139 }
4140 #endif
4141
4142 #if ENABLE(CONTEXT_MENUS)
4143 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
4144 {
4145     if (!m_contextMenu)
4146         return;
4147
4148     m_contextMenu->itemSelected(item);
4149     m_contextMenu = nullptr;
4150 }
4151 #endif
4152
4153 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
4154 {
4155     return frame->editor().replaceSelectionWithText(text, WebCore::Editor::SelectReplacement::Yes, WebCore::Editor::SmartReplace::No);
4156 }
4157
4158 #if !PLATFORM(IOS_FAMILY)
4159 void WebPage::clearSelection()
4160 {
4161     m_page->focusController().focusedOrMainFrame().selection().clear();
4162 }
4163 #endif
4164
4165 void WebPage::restoreSelectionInFocusedEditableElement()
4166 {
4167     Frame& frame =&nbs