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