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