[WPE] Add API for webview background color configuration
[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     setUnderlayColor(parameters.underlayColor);
524
525     setPaginationMode(parameters.paginationMode);
526     setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
527     setPageLength(parameters.pageLength);
528     setGapBetweenPages(parameters.gapBetweenPages);
529     setPaginationLineGridEnabled(parameters.paginationLineGridEnabled);
530
531     setUseDarkAppearance(parameters.useDarkAppearance);
532
533 #if PLATFORM(MAC)
534     setUseSystemAppearance(parameters.useSystemAppearance);
535 #endif
536
537     // If the page is created off-screen, its visibilityState should be prerender.
538     m_page->setActivityState(m_activityState);
539     if (!isVisible())
540         m_page->setIsPrerender();
541
542     updateIsInWindow(true);
543
544     setViewLayoutSize(parameters.viewLayoutSize);
545     setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
546     setViewportSizeForCSSViewportUnits(parameters.viewportSizeForCSSViewportUnits);
547     
548     setScrollPinningBehavior(parameters.scrollPinningBehavior);
549     if (parameters.scrollbarOverlayStyle)
550         m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value());
551     else
552         m_scrollbarOverlayStyle = Optional<ScrollbarOverlayStyle>();
553
554     setTopContentInset(parameters.topContentInset);
555
556     m_userAgent = parameters.userAgent;
557     
558     if (!parameters.itemStates.isEmpty())
559         restoreSessionInternal(parameters.itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
560
561     if (parameters.sessionID.isValid())
562         setSessionID(parameters.sessionID);
563
564     m_drawingArea->setPaintingEnabled(true);
565     
566     setMediaVolume(parameters.mediaVolume);
567
568     setMuted(parameters.muted);
569
570     // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree.
571     m_page->addLayoutMilestones({ DidFirstLayout, DidFirstVisuallyNonEmptyLayout });
572
573     auto& webProcess = WebProcess::singleton();
574     webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
575
576     // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
577     webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
578     webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this);
579     webProcess.addMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID, *this);
580 #if ENABLE(FULLSCREEN_API)
581     webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
582 #endif
583
584 #ifndef NDEBUG
585     webPageCounter.increment();
586 #endif
587
588 #if ENABLE(ASYNC_SCROLLING)
589     if (m_useAsyncScrolling)
590         webProcess.eventDispatcher().addScrollingTreeForPage(this);
591 #endif
592
593     for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders)
594         m_mimeTypesWithCustomContentProviders.add(mimeType);
595
596
597 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
598     if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>())
599         m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory());
600 #endif
601     m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled);
602     
603     if (parameters.viewScaleFactor != 1)
604         scaleView(parameters.viewScaleFactor);
605
606     m_page->addLayoutMilestones(parameters.observedLayoutMilestones);
607
608 #if PLATFORM(COCOA)
609     m_page->settings().setContentDispositionAttachmentSandboxEnabled(true);
610     setSmartInsertDeleteEnabled(parameters.smartInsertDeleteEnabled);
611     WebCore::setAdditionalSupportedImageTypes(parameters.additionalSupportedImageTypes);
612 #endif
613
614 #if ENABLE(SERVICE_WORKER)
615     if (parameters.hasRegisteredServiceWorkers)
616         ServiceWorkerProvider::singleton().setMayHaveRegisteredServiceWorkers();
617 #endif
618
619     m_needsFontAttributes = parameters.needsFontAttributes;
620
621 #if ENABLE(WEB_RTC)
622     if (!parameters.iceCandidateFilteringEnabled)
623         disableICECandidateFiltering();
624 #if USE(LIBWEBRTC)
625     if (parameters.enumeratingAllNetworkInterfacesEnabled)
626         enableEnumeratingAllNetworkInterfaces();
627 #endif
628 #endif
629
630     for (const auto& iterator : parameters.urlSchemeHandlers)
631         registerURLSchemeHandler(iterator.value, iterator.key);
632
633     m_userContentController->addUserContentWorlds(parameters.userContentWorlds);
634     m_userContentController->addUserScripts(WTFMove(parameters.userScripts), InjectUserScriptImmediately::No);
635     m_userContentController->addUserStyleSheets(parameters.userStyleSheets);
636     m_userContentController->addUserScriptMessageHandlers(parameters.messageHandlers);
637 #if ENABLE(CONTENT_EXTENSIONS)
638     m_userContentController->addContentRuleLists(parameters.contentRuleLists);
639 #endif
640
641 #if PLATFORM(IOS_FAMILY)
642     setViewportConfigurationViewLayoutSize(parameters.viewportConfigurationViewLayoutSize, parameters.viewportConfigurationLayoutSizeScaleFactor, 0);
643     setMaximumUnobscuredSize(parameters.maximumUnobscuredSize);
644 #endif
645
646 #if USE(AUDIO_SESSION)
647     PlatformMediaSessionManager::setShouldDeactivateAudioSession(true);
648 #endif
649
650     setBackgroundColor(parameters.backgroundColor);
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::setBackgroundColor(const Optional<WebCore::Color>& backgroundColor)
2922 {
2923     if (m_backgroundColor == backgroundColor)
2924         return;
2925
2926     m_backgroundColor = backgroundColor;
2927
2928     if (FrameView* frameView = mainFrameView())
2929         frameView->updateBackgroundRecursively(backgroundColor);
2930
2931     m_drawingArea->setNeedsDisplay();
2932 }
2933
2934 #if PLATFORM(COCOA)
2935 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
2936 {
2937     if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
2938         LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
2939         return;
2940     }
2941
2942     m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
2943
2944     setTopContentInset(contentInset);
2945
2946     deallocateSendRightSafely(fencePort.port());
2947 }
2948 #endif
2949
2950 void WebPage::setTopContentInset(float contentInset)
2951 {
2952     if (contentInset == m_page->topContentInset())
2953         return;
2954
2955     m_page->setTopContentInset(contentInset);
2956
2957     for (auto* pluginView : m_pluginViews)
2958         pluginView->topContentInsetDidChange();
2959 }
2960
2961 void WebPage::viewWillStartLiveResize()
2962 {
2963     if (!m_page)
2964         return;
2965
2966     // FIXME: This should propagate to all ScrollableAreas.
2967     Frame& frame = m_page->focusController().focusedOrMainFrame();
2968     if (FrameView* view = frame.view())
2969         view->willStartLiveResize();
2970 }
2971
2972 void WebPage::viewWillEndLiveResize()
2973 {
2974     if (!m_page)
2975         return;
2976
2977     // FIXME: This should propagate to all ScrollableAreas.
2978     Frame& frame = m_page->focusController().focusedOrMainFrame();
2979     if (FrameView* view = frame.view())
2980         view->willEndLiveResize();
2981 }
2982
2983 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
2984 {
2985     if (!m_page)
2986         return;
2987
2988     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2989
2990     Frame& frame = m_page->focusController().focusedOrMainFrame();
2991     frame.document()->setFocusedElement(0);
2992
2993     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2994         PlatformKeyboardEvent platformEvent(platform(event));
2995         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2996         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
2997
2998         send(Messages::WebPageProxy::VoidCallback(callbackID));
2999         return;
3000     }
3001
3002     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
3003     send(Messages::WebPageProxy::VoidCallback(callbackID));
3004 }
3005
3006 void WebPage::setCanStartMediaTimerFired()
3007 {
3008     if (m_page)
3009         m_page->setCanStartMedia(true);
3010 }
3011
3012 void WebPage::updateIsInWindow(bool isInitialState)
3013 {
3014     bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
3015
3016     if (!isInWindow) {
3017         m_setCanStartMediaTimer.stop();
3018         m_page->setCanStartMedia(false);
3019         
3020         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
3021         if (!isInitialState)
3022             WebProcess::singleton().pageWillLeaveWindow(m_pageID);
3023     } else {
3024         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
3025         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
3026         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
3027         if (m_mayStartMediaWhenInWindow)
3028             m_setCanStartMediaTimer.startOneShot(0_s);
3029
3030         WebProcess::singleton().pageDidEnterWindow(m_pageID);
3031     }
3032
3033     if (isInWindow)
3034         layoutIfNeeded();
3035 }
3036
3037 void WebPage::visibilityDidChange()
3038 {
3039     bool isVisible = m_activityState.contains(ActivityState::IsVisible);
3040     if (!isVisible) {
3041         // We save the document / scroll state when backgrounding a tab so that we are able to restore it
3042         // if it gets terminated while in the background.
3043         if (auto* frame = m_mainFrame->coreFrame())
3044             frame->loader().history().saveDocumentAndScrollState();
3045     }
3046 }
3047
3048 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
3049 {
3050     LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
3051
3052     auto changed = m_activityState ^ activityState;
3053     m_activityState = activityState;
3054
3055     if (changed)
3056         updateThrottleState();
3057
3058     ASSERT_WITH_MESSAGE(m_page, "setActivityState called on %" PRIu64 " but WebCore page was null", pageID());
3059     if (m_page) {
3060         SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
3061         m_page->setActivityState(activityState);
3062     }
3063     
3064     for (auto* pluginView : m_pluginViews)
3065         pluginView->activityStateDidChange(changed);
3066
3067     m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
3068     WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
3069
3070     if (changed & ActivityState::IsInWindow)
3071         updateIsInWindow();
3072
3073     if (changed & ActivityState::IsVisible)
3074         visibilityDidChange();
3075 }
3076
3077 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
3078 {
3079     m_layerHostingMode = layerHostingMode;
3080
3081     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
3082
3083     for (auto* pluginView : m_pluginViews)
3084         pluginView->setLayerHostingMode(m_layerHostingMode);
3085 }
3086
3087 void WebPage::setSessionID(PAL::SessionID sessionID)
3088 {
3089     m_page->setSessionID(sessionID);
3090 }
3091
3092 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyCheckIdentifier identifier, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, Optional<WebsitePoliciesData>&& websitePolicies)
3093 {
3094     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3095     if (!frame)
3096         return;
3097     frame->didReceivePolicyDecision(listenerID, identifier, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
3098 }
3099
3100 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
3101 {
3102     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3103     if (!frame)
3104         return;
3105     frame->continueWillSubmitForm(listenerID);
3106 }
3107
3108 void WebPage::didStartPageTransition()
3109 {
3110     freezeLayerTree(LayerTreeFreezeReason::PageTransition);
3111
3112 #if PLATFORM(MAC)
3113     bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
3114 #endif
3115     m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
3116     m_isFocusingElementDueToUserInteraction = false;
3117     m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
3118 #if PLATFORM(MAC)
3119     if (hasPreviouslyFocusedDueToUserInteraction)
3120         send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
3121     if (m_needsHiddenContentEditableQuirk) {
3122         m_needsHiddenContentEditableQuirk = false;
3123         send(Messages::WebPageProxy::SetNeedsHiddenContentEditableQuirk(m_needsHiddenContentEditableQuirk));
3124     }
3125     if (m_needsPlainTextQuirk) {
3126         m_needsPlainTextQuirk = false;
3127         send(Messages::WebPageProxy::SetNeedsPlainTextQuirk(m_needsPlainTextQuirk));
3128     }
3129 #endif
3130 }
3131
3132 void WebPage::didCompletePageTransition()
3133 {
3134     unfreezeLayerTree(LayerTreeFreezeReason::PageTransition);
3135
3136     bool isInitialEmptyDocument = !m_mainFrame;
3137     if (!isInitialEmptyDocument)
3138         unfreezeLayerTree(LayerTreeFreezeReason::ProcessSwap);
3139 }
3140
3141 void WebPage::show()
3142 {
3143     send(Messages::WebPageProxy::ShowPage());
3144 }
3145
3146 String WebPage::userAgent(const URL& webCoreURL) const
3147 {
3148     return userAgent(nullptr, webCoreURL);
3149 }
3150
3151 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
3152 {
3153     if (frame) {
3154         String userAgent = m_loaderClient->userAgentForURL(*frame, webcoreURL);
3155         if (!userAgent.isEmpty())
3156             return userAgent;
3157     }
3158
3159     String userAgent = platformUserAgent(webcoreURL);
3160     if (!userAgent.isEmpty())
3161         return userAgent;
3162     return m_userAgent;
3163 }
3164     
3165 void WebPage::setUserAgent(const String& userAgent)
3166 {
3167     if (m_userAgent == userAgent)
3168         return;
3169
3170     m_userAgent = userAgent;
3171
3172     if (m_page)
3173         m_page->userAgentChanged();
3174 }
3175
3176 void WebPage::suspendActiveDOMObjectsAndAnimations()
3177 {
3178     m_page->suspendActiveDOMObjectsAndAnimations();
3179 }
3180
3181 void WebPage::resumeActiveDOMObjectsAndAnimations()
3182 {
3183     m_page->resumeActiveDOMObjectsAndAnimations();
3184 }
3185
3186 IntPoint WebPage::screenToRootView(const IntPoint& point)
3187 {
3188     IntPoint windowPoint;
3189     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
3190     return windowPoint;
3191 }
3192     
3193 IntRect WebPage::rootViewToScreen(const IntRect& rect)
3194 {
3195     IntRect screenRect;
3196     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
3197     return screenRect;
3198 }
3199     
3200 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
3201 {
3202     IntPoint windowPoint;
3203     sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
3204     return windowPoint;
3205 }
3206
3207 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
3208 {
3209     IntRect screenRect;
3210     sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
3211     return screenRect;
3212 }
3213
3214 KeyboardUIMode WebPage::keyboardUIMode()
3215 {
3216     bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
3217     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
3218 }
3219
3220 void WebPage::runJavaScript(const String& script, bool forceUserGesture, Optional<String> worldName, CallbackID callbackID)
3221 {
3222     // NOTE: We need to be careful when running scripts that the objects we depend on don't
3223     // disappear during script execution.
3224
3225     RefPtr<SerializedScriptValue> serializedResultValue;
3226     JSLockHolder lock(commonVM());
3227     bool hadException = true;
3228     ExceptionDetails details;
3229     auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
3230     if (world) {
3231         if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
3232             hadException = false;
3233             serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
3234                 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
3235         }
3236     }
3237
3238     IPC::DataReference dataReference;
3239     if (serializedResultValue)
3240         dataReference = serializedResultValue->data();
3241     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
3242 }
3243
3244 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
3245 {
3246     runJavaScript(script, forceUserGesture, WTF::nullopt, callbackID);
3247 }
3248
3249 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
3250 {
3251     runJavaScript(script, forceUserGesture, worldName, callbackID);
3252 }
3253
3254 void WebPage::getContentsAsString(CallbackID callbackID)
3255 {
3256     String resultString = m_mainFrame->contentsAsString();
3257     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3258 }
3259
3260 #if ENABLE(MHTML)
3261 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
3262 {
3263     send(Messages::WebPageProxy::DataCallback({ MHTMLArchive::generateMHTMLData(m_page.get()) }, callbackID));
3264 }
3265 #endif
3266
3267 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3268 {
3269     String resultString = renderTreeExternalRepresentation();
3270     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3271 }
3272
3273 static Frame* frameWithSelection(Page* page)
3274 {
3275     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3276         if (frame->selection().isRange())
3277             return frame;
3278     }
3279
3280     return 0;
3281 }
3282
3283 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3284 {
3285 #if PLATFORM(COCOA)
3286     RetainPtr<CFDataRef> data;
3287     if (Frame* frame = frameWithSelection(m_page.get()))
3288         data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3289 #endif
3290
3291     IPC::SharedBufferDataReference dataReference;
3292 #if PLATFORM(COCOA)
3293     if (data)
3294         dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3295 #endif
3296     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3297 }
3298
3299 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3300 {
3301     WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3302     String resultString = focusedOrMainFrame->selectionAsString();
3303     if (resultString.isEmpty())
3304         resultString = focusedOrMainFrame->contentsAsString();
3305     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3306 }
3307
3308 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3309 {
3310     String resultString;
3311     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3312        resultString = frame->source();
3313
3314     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3315 }
3316
3317 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3318 {
3319     RefPtr<SharedBuffer> buffer;
3320     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3321         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3322             buffer = pluginView->liveResourceData();
3323         if (!buffer) {
3324             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3325                 buffer = loader->mainResourceData();
3326         }
3327     }
3328
3329     IPC::SharedBufferDataReference dataReference;
3330     if (buffer)
3331         dataReference = { *buffer };
3332     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3333 }
3334
3335 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3336 {
3337     DocumentLoader* loader = frame->loader().documentLoader();
3338     if (!loader)
3339         return nullptr;
3340
3341     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3342     if (!subresource)
3343         return nullptr;
3344
3345     return &subresource->data();
3346 }
3347
3348 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3349 {
3350     RefPtr<SharedBuffer> buffer;
3351     if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3352         URL resourceURL(URL(), resourceURLString);
3353         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3354     }
3355
3356     IPC::SharedBufferDataReference dataReference;
3357     if (buffer)
3358         dataReference = { *buffer };
3359     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3360 }
3361
3362 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3363 {
3364 #if PLATFORM(COCOA)
3365     RetainPtr<CFDataRef> data;
3366     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3367         data = frame->webArchiveData(nullptr, nullptr);
3368 #else
3369     UNUSED_PARAM(frameID);
3370 #endif
3371
3372     IPC::SharedBufferDataReference dataReference;
3373 #if PLATFORM(COCOA)
3374     if (data)
3375         dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3376 #endif
3377     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3378 }
3379
3380 void WebPage::forceRepaintWithoutCallback()
3381 {
3382     m_drawingArea->forceRepaint();
3383 }
3384
3385 void WebPage::forceRepaint(CallbackID callbackID)
3386 {
3387     if (m_drawingArea->forceRepaintAsync(callbackID))
3388         return;
3389
3390     forceRepaintWithoutCallback();
3391     send(Messages::WebPageProxy::VoidCallback(callbackID));
3392 }
3393
3394 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3395 {
3396     WebPreferencesStore::removeTestRunnerOverrides();
3397     updatePreferences(store);
3398 }
3399
3400 void WebPage::updatePreferences(const WebPreferencesStore& store)
3401 {
3402     updatePreferencesGenerated(store);
3403
3404     Settings& settings = m_page->settings();
3405
3406 #if !PLATFORM(GTK)
3407     if (!settings.acceleratedCompositingEnabled()) {
3408         RELEASE_LOG_IF_ALLOWED("%p - WebPage - acceleratedCompositingEnabled setting was false. WebKit cannot function in this mode; changing setting to true", this);
3409         settings.setAcceleratedCompositingEnabled(true);
3410     }
3411 #endif
3412
3413     bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3414     settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3415     settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3416     settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3417     settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3418     settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3419     settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3420     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3421     settings.setFrameFlattening(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()) ? WebCore::FrameFlattening::FullyEnabled : WebCore::FrameFlattening::Disabled);
3422     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3423 #if ENABLE(DATA_DETECTION)
3424     settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3425 #endif
3426
3427     DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3428
3429     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3430     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3431     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3432     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3433
3434     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3435     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3436
3437     if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3438         setSessionID(PAL::SessionID::legacyPrivateSessionID());
3439     else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3440         setSessionID(PAL::SessionID::defaultSessionID());
3441
3442     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3443     if (m_processSuppressionEnabled != processSuppressionEnabled) {
3444         m_processSuppressionEnabled = processSuppressionEnabled;
3445         updateThrottleState();
3446     }
3447
3448 #if PLATFORM(COCOA)
3449     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3450 #endif
3451 #if ENABLE(PAYMENT_REQUEST)
3452     settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3453 #endif
3454
3455     // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3456     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3457
3458 #if PLATFORM(IOS_FAMILY)
3459     m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3460     m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3461     setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3462
3463     settings.setUseImageDocumentForSubframePDF(true);
3464 #if HAVE(AVKIT)
3465     DeprecatedGlobalSettings::setAVKitEnabled(true);
3466 #endif
3467 #endif
3468
3469 #if ENABLE(SERVICE_WORKER)
3470     if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3471         ASSERT(parentProcessHasServiceWorkerEntitlement());
3472         if (!parentProcessHasServiceWorkerEntitlement())
3473             RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3474     }
3475 #endif
3476
3477     settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3478
3479     if (m_drawingArea)
3480         m_drawingArea->updatePreferences(store);
3481 }
3482
3483 #if ENABLE(DATA_DETECTION)
3484
3485 void WebPage::setDataDetectionResults(NSArray *detectionResults)
3486 {
3487     DataDetectionResult dataDetectionResult;
3488     dataDetectionResult.results = detectionResults;
3489     send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult));
3490 }
3491
3492 void WebPage::removeDataDetectedLinks(CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3493 {
3494     for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3495         auto document = makeRefPtr(frame->document());
3496         if (!document)
3497             continue;
3498
3499         DataDetection::removeDataDetectedLinksInDocument(*document);
3500         frame->setDataDetectionResults(nullptr);
3501     }
3502     completionHandler({ m_page->mainFrame().dataDetectionResults() });
3503 }
3504
3505 void WebPage::detectDataInAllFrames(uint64_t types, CompletionHandler<void(const DataDetectionResult&)>&& completionHandler)
3506 {
3507     auto dataDetectorTypes = static_cast<WebCore::DataDetectorTypes>(types);
3508     for (auto frame = makeRefPtr(&m_page->mainFrame()); frame; frame = frame->tree().traverseNext()) {
3509         auto document = makeRefPtr(frame->document());
3510         if (!document)
3511             continue;
3512
3513         RefPtr<Range> range = Range::create(*document, Position { document.get(), Position::PositionIsBeforeChildren }, Position { document.get(), Position::PositionIsAfterChildren });
3514         frame->setDataDetectionResults(DataDetection::detectContentInRange(range, dataDetectorTypes, m_dataDetectionContext.get()));
3515     }
3516     completionHandler({ m_page->mainFrame().dataDetectionResults() });
3517 }
3518
3519 #endif // ENABLE(DATA_DETECTION)
3520
3521 #if PLATFORM(COCOA)
3522 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
3523 {
3524     FrameView* frameView = corePage()->mainFrame().view();
3525     if (!frameView)
3526         return;
3527
3528     layerTransaction.setContentsSize(frameView->contentsSize());
3529     layerTransaction.setScrollOrigin(frameView->scrollOrigin());
3530     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
3531     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
3532     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
3533
3534     layerTransaction.setBaseLayoutViewportSize(frameView->baseLayoutViewportSize());
3535     layerTransaction.setMinStableLayoutViewportOrigin(frameView->minStableLayoutViewportOrigin());
3536     layerTransaction.setMaxStableLayoutViewportOrigin(frameView->maxStableLayoutViewportOrigin());
3537
3538 #if PLATFORM(IOS_FAMILY)
3539     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
3540     layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
3541     layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
3542     layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
3543     layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
3544     layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit);
3545     layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument);
3546     layerTransaction.setAvoidsUnsafeArea(m_viewportConfiguration.avoidsUnsafeArea());
3547     layerTransaction.setIsInStableState(m_isInStableState);
3548     layerTransaction.setAllowsUserScaling(allowsUserScaling());
3549     if (m_pendingDynamicViewportSizeUpdateID) {
3550         layerTransaction.setDynamicViewportSizeUpdateID(*m_pendingDynamicViewportSizeUpdateID);
3551         m_pendingDynamicViewportSizeUpdateID = WTF::nullopt;
3552     }
3553     if (m_lastTransactionPageScaleFactor != layerTransaction.pageScaleFactor()) {
3554         m_lastTransactionPageScaleFactor = layerTransaction.pageScaleFactor();
3555         m_lastTransactionIDWithScaleChange = layerTransaction.transactionID();
3556     }
3557 #endif
3558
3559     layerTransaction.setScrollPosition(frameView->scrollPosition());
3560
3561     if (m_hasPendingEditorStateUpdate) {
3562         layerTransaction.setEditorState(editorState());
3563         m_hasPendingEditorStateUpdate = false;
3564     }
3565 }
3566
3567 void WebPage::didFlushLayerTreeAtTime(MonotonicTime timestamp)
3568 {
3569 #if PLATFORM(IOS_FAMILY)
3570     if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != MonotonicTime()) {
3571         Seconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
3572         m_oldestNonStableUpdateVisibleContentRectsTimestamp = MonotonicTime();
3573
3574         m_estimatedLatency = m_estimatedLatency * 0.80 + elapsed * 0.20;
3575     }
3576 #else
3577     UNUSED_PARAM(timestamp);
3578 #endif
3579 }
3580 #endif
3581
3582 void WebPage::willDisplayPage()
3583 {
3584     m_page->willDisplayPage();
3585 }
3586
3587 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
3588 {
3589     if (m_isClosed)
3590         return nullptr;
3591     if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3592         m_inspector = WebInspector::create(this);
3593     return m_inspector.get();
3594 }
3595
3596 WebInspectorUI* WebPage::inspectorUI()
3597 {
3598     if (m_isClosed)
3599         return nullptr;
3600     if (!m_inspectorUI)
3601         m_inspectorUI = WebInspectorUI::create(*this);
3602     return m_inspectorUI.get();
3603 }
3604
3605 RemoteWebInspectorUI* WebPage::remoteInspectorUI()
3606 {
3607     if (m_isClosed)
3608         return nullptr;
3609     if (!m_remoteInspectorUI)
3610         m_remoteInspectorUI = RemoteWebInspectorUI::create(*this);
3611     return m_remoteInspectorUI.get();
3612 }
3613
3614 void WebPage::inspectorFrontendCountChanged(unsigned count)
3615 {
3616     send(Messages::WebPageProxy::DidChangeInspectorFrontendCount(count));
3617 }
3618
3619 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
3620 PlaybackSessionManager& WebPage::playbackSessionManager()
3621 {
3622     if (!m_playbackSessionManager)
3623         m_playbackSessionManager = PlaybackSessionManager::create(*this);
3624     return *m_playbackSessionManager;
3625 }
3626
3627 VideoFullscreenManager& WebPage::videoFullscreenManager()
3628 {
3629     if (!m_videoFullscreenManager)
3630         m_videoFullscreenManager = VideoFullscreenManager::create(*this, playbackSessionManager());
3631     return *m_videoFullscreenManager;
3632 }
3633
3634 void WebPage::videoControlsManagerDidChange()
3635 {
3636 #if ENABLE(FULLSCREEN_API)
3637     if (auto* manager = fullScreenManager())
3638         manager->videoControlsManagerDidChange();
3639 #endif
3640 }
3641
3642 #endif
3643
3644 #if PLATFORM(IOS_FAMILY)
3645 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3646 {
3647     m_page->setAllowsMediaDocumentInlinePlayback(allows);
3648 }
3649 #endif
3650
3651 #if ENABLE(FULLSCREEN_API)
3652 WebFullScreenManager* WebPage::fullScreenManager()
3653 {
3654     if (!m_fullScreenManager)
3655         m_fullScreenManager = WebFullScreenManager::create(this);
3656     return m_fullScreenManager.get();
3657 }
3658 #endif
3659
3660 void WebPage::addConsoleMessage(uint64_t frameID, MessageSource messageSource, MessageLevel messageLevel, const String& message, uint64_t requestID)
3661 {
3662     if (auto* frame = WebProcess::singleton().webFrame(frameID))
3663         frame->addConsoleMessage(messageSource, messageLevel, message, requestID);
3664 }
3665
3666 void WebPage::sendCSPViolationReport(uint64_t frameID, const URL& reportURL, IPC::FormDataReference&& reportData)
3667 {
3668     auto report = reportData.takeData();
3669     if (!report)
3670         return;
3671     if (auto* frame = WebProcess::singleton().webFrame(frameID))
3672         PingLoader::sendViolationReport(*frame->coreFrame(), reportURL, report.releaseNonNull(), ViolationReportType::ContentSecurityPolicy);
3673 }
3674
3675 void WebPage::enqueueSecurityPolicyViolationEvent(uint64_t frameID, SecurityPolicyViolationEvent::Init&& eventInit)
3676 {
3677     auto* frame = WebProcess::singleton().webFrame(frameID);
3678     if (!frame)
3679         return;
3680     auto* coreFrame = frame->coreFrame();
3681     if (!coreFrame)
3682         return;
3683     if (auto* document = coreFrame->document())
3684         document->enqueueSecurityPolicyViolationEvent(WTFMove(eventInit));
3685 }
3686
3687 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3688 {
3689     if (m_notificationPermissionRequestManager)
3690         return m_notificationPermissionRequestManager.get();
3691
3692     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3693     return m_notificationPermissionRequestManager.get();
3694 }
3695
3696 #if ENABLE(DRAG_SUPPORT)
3697
3698 #if PLATFORM(GTK)
3699 void WebPage::performDragControllerAction(DragControllerAction action, const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t draggingSourceOperationMask, WebSelectionData&& selection, uint32_t flags)
3700 {
3701     if (!m_page) {
3702         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3703         return;
3704     }
3705
3706     DragData dragData(selection.selectionData.ptr(), clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3707     switch (action) {
3708     case DragControllerAction::Entered: {
3709         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3710         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3711         return;
3712     }
3713     case DragControllerAction::Updated: {
3714         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3715         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().dragHandlingMethod(), m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted(), { }, { }));
3716         return;
3717     }
3718     case DragControllerAction::Exited:
3719         m_page->dragController().dragExited(dragData);
3720         return;
3721
3722     case DragControllerAction::PerformDragOperation: {
3723         m_page->dragController().performDragOperation(dragData);
3724         return;
3725     }
3726     }
3727     ASSERT_NOT_REACHED();
3728 }
3729 #else
3730 void WebPage::performDragControllerAction(DragControllerAction action, const WebCore::DragData& dragData, SandboxExtension::Handle&& sandboxExtensionHandle, SandboxExtension::HandleArray&& sandboxExtensionsHandleArray)
3731 {
3732     if (!m_page) {
3733         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3734         return;
3735     }
3736
3737     switch (action) {
3738     case DragControllerAction::Entered: {
3739         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3740         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()));
3741         return;
3742     }
3743     case DragControllerAction::Updated: {
3744         DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3745         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()));
3746         return;
3747     }
3748     case DragControllerAction::Exited:
3749         m_page->dragController().dragExited(dragData);
3750         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, DragHandlingMethod::None, false, 0, { }, { }));
3751         return;
3752         
3753     case DragControllerAction::PerformDragOperation: {
3754         ASSERT(!m_pendingDropSandboxExtension);
3755
3756         m_pendingDropSandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
3757         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3758             if (auto extension = SandboxExtension::create(WTFMove(sandboxExtensionsHandleArray[i])))
3759                 m_pendingDropExtensionsForFileUpload.append(extension);
3760         }
3761
3762         bool handled = m_page->dragController().performDragOperation(dragData);
3763
3764         // If we started loading a local file, the sandbox extension tracker would have adopted this
3765         // pending drop sandbox extension. If not, we'll play it safe and clear it.
3766         m_pendingDropSandboxExtension = nullptr;
3767
3768         m_pendingDropExtensionsForFileUpload.clear();
3769         send(Messages::WebPageProxy::DidPerformDragOperation(handled));
3770         return;
3771     }
3772     }
3773     ASSERT_NOT_REACHED();
3774 }
3775 #endif
3776
3777 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3778 {
3779     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3780     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3781
3782     m_page->dragController().dragEnded();
3783     FrameView* view = m_page->mainFrame().view();
3784     if (!view)
3785         return;
3786     // FIXME: These are fake modifier keys here, but they should be real ones instead.
3787     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), 0, WebCore::NoTap);
3788     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3789
3790     send(Messages::WebPageProxy::DidEndDragging());
3791 }
3792
3793 void WebPage::willPerformLoadDragDestinationAction()
3794 {
3795     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(WTFMove(m_pendingDropSandboxExtension));
3796 }
3797
3798 void WebPage::mayPerformUploadDragDestinationAction()
3799 {
3800     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3801         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3802     m_pendingDropExtensionsForFileUpload.clear();
3803 }
3804
3805 void WebPage::didStartDrag()
3806 {
3807     m_isStartingDrag = false;
3808     m_page->mainFrame().eventHandler().didStartDrag();
3809 }
3810
3811 void WebPage::dragCancelled()
3812 {
3813     m_isStartingDrag = false;
3814     m_page->mainFrame().eventHandler().dragCancelled();
3815 }
3816     
3817 #endif // ENABLE(DRAG_SUPPORT)
3818
3819 WebUndoStep* WebPage::webUndoStep(WebUndoStepID stepID)
3820 {
3821     return m_undoStepMap.get(stepID);
3822 }
3823
3824 void WebPage::addWebUndoStep(WebUndoStepID stepID, Ref<WebUndoStep>&& entry)
3825 {
3826     auto addResult = m_undoStepMap.set(stepID, WTFMove(entry));
3827     ASSERT_UNUSED(addResult, addResult.isNewEntry);
3828 }
3829
3830 void WebPage::removeWebEditCommand(WebUndoStepID stepID)
3831 {
3832     if (auto undoStep = m_undoStepMap.take(stepID))
3833         undoStep->didRemoveFromUndoManager();
3834 }
3835
3836 bool WebPage::isAlwaysOnLoggingAllowed() const
3837 {
3838     return corePage() && corePage()->isAlwaysOnLoggingAllowed();
3839 }
3840
3841 void WebPage::unapplyEditCommand(WebUndoStepID stepID)
3842 {
3843     auto* step = webUndoStep(stepID);
3844     if (!step)
3845         return;
3846
3847     step->step().unapply();
3848 }
3849
3850 void WebPage::reapplyEditCommand(WebUndoStepID stepID)
3851 {
3852     auto* step = webUndoStep(stepID);
3853     if (!step)
3854         return;
3855
3856     m_isInRedo = true;
3857     step->step().reapply();
3858     m_isInRedo = false;
3859 }
3860
3861 void WebPage::didRemoveEditCommand(WebUndoStepID commandID)
3862 {
3863     removeWebEditCommand(commandID);
3864 }
3865
3866 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3867 {
3868     m_activePopupMenu = menu;
3869 }
3870
3871 #if ENABLE(INPUT_TYPE_COLOR)
3872
3873 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3874 {
3875     m_activeColorChooser = colorChooser;
3876 }
3877
3878 void WebPage::didEndColorPicker()
3879 {
3880     m_activeColorChooser->didEndChooser();
3881 }
3882
3883 void WebPage::didChooseColor(const WebCore::Color& color)
3884 {
3885     m_activeColorChooser->didChooseColor(color);
3886 }
3887
3888 #endif
3889
3890 #if ENABLE(DATALIST_ELEMENT)
3891
3892 void WebPage::setActiveDataListSuggestionPicker(WebDataListSuggestionPicker* dataListSuggestionPicker)
3893 {
3894     m_activeDataListSuggestionPicker = dataListSuggestionPicker;
3895 }
3896
3897 void WebPage::didSelectDataListOption(const String& selectedOption)
3898 {
3899     m_activeDataListSuggestionPicker->didSelectOption(selectedOption);
3900 }
3901
3902 void WebPage::didCloseSuggestions()
3903 {
3904     if (m_activeDataListSuggestionPicker)
3905         m_activeDataListSuggestionPicker->didCloseSuggestions();
3906     m_activeDataListSuggestionPicker = nullptr;
3907 }
3908
3909 #endif
3910
3911 void WebPage::setActiveOpenPanelResultListener(Ref<WebOpenPanelResultListener>&& openPanelResultListener)
3912 {
3913     m_activeOpenPanelResultListener = WTFMove(openPanelResultListener);
3914 }
3915
3916 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3917 {
3918     return m_page->findString(target, core(options));
3919 }
3920
3921 void WebPage::findStringMatchesFromInjectedBundle(const String& target, FindOptions options)
3922 {
3923     findController().findStringMatches(target, options, 0);
3924 }
3925
3926 void WebPage::replaceStringMatchesFromInjectedBundle(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly)
3927 {
3928     findController().replaceMatches(matchIndices, replacementText, selectionOnly);
3929 }
3930
3931 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3932 {
3933     findController().findString(string, static_cast<FindOptions>(options), maxMatchCount);
3934 }
3935
3936 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3937 {
3938     findController().findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3939 }
3940
3941 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3942 {
3943     findController().getImageForFindMatch(matchIndex);
3944 }
3945
3946 void WebPage::selectFindMatch(uint32_t matchIndex)
3947 {
3948     findController().selectFindMatch(matchIndex);
3949 }
3950
3951 void WebPage::hideFindUI()
3952 {
3953     findController().hideFindUI();
3954 }
3955
3956 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3957 {
3958     findController().countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3959 }
3960
3961 void WebPage::replaceMatches(const Vector<uint32_t>& matchIndices, const String& replacementText, bool selectionOnly, CallbackID callbackID)
3962 {
3963     auto numberOfReplacements = findController().replaceMatches(matchIndices, replacementText, selectionOnly);
3964     send(Messages::WebPageProxy::UnsignedCallback(numberOfReplacements, callbackID));
3965 }
3966
3967 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3968 {
3969     changeSelectedIndex(newIndex);
3970     m_activePopupMenu = nullptr;
3971 }
3972
3973 void WebPage::changeSelectedIndex(int32_t index)
3974 {
3975     if (!m_activePopupMenu)
3976         return;
3977
3978     m_activePopupMenu->didChangeSelectedIndex(index);
3979 }
3980
3981 #if PLATFORM(IOS_FAMILY)
3982 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3983 {
3984     if (!m_activeOpenPanelResultListener)
3985         return;
3986
3987     RefPtr<Icon> icon;
3988     if (!iconData.isEmpty()) {
3989         RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3990         RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3991         RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3992         icon = Icon::createIconForImage(imageRef.get());
3993     }
3994
3995     m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3996     m_activeOpenPanelResultListener = nullptr;
3997 }
3998 #endif
3999
4000 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
4001 {
4002     if (!m_activeOpenPanelResultListener)
4003         return;
4004
4005     m_activeOpenPanelResultListener->didChooseFiles(files);
4006     m_activeOpenPanelResultListener = nullptr;
4007 }
4008
4009 void WebPage::didCancelForOpenPanel()
4010 {
4011     m_activeOpenPanelResultListener = nullptr;
4012 }
4013
4014 #if ENABLE(SANDBOX_EXTENSIONS)
4015 void WebPage::extendSandboxForFilesFromOpenPanel(SandboxExtension::HandleArray&& handles)
4016 {
4017     for (size_t i = 0; i < handles.size(); ++i) {
4018         bool result = SandboxExtension::consumePermanently(handles[i]);
4019         if (!result) {
4020             // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
4021             WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
4022         }
4023     }
4024 }
4025 #endif
4026
4027 #if ENABLE(GEOLOCATION)
4028 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
4029 {
4030     geolocationPermissionRequestManager().didReceiveGeolocationPermissionDecision(geolocationID, allowed);
4031 }
4032 #endif
4033
4034 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
4035 {
4036     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
4037 }
4038
4039 #if ENABLE(MEDIA_STREAM)
4040
4041 void WebPage::userMediaAccessWasGranted(uint64_t userMediaID, WebCore::CaptureDevice&& audioDevice, WebCore::CaptureDevice&& videoDevice, String&& mediaDeviceIdentifierHashSalt)
4042 {
4043     m_userMediaPermissionRequestManager->userMediaAccessWasGranted(userMediaID, WTFMove(audioDevice), WTFMove(videoDevice), WTFMove(mediaDeviceIdentifierHashSalt));
4044 }
4045
4046 void WebPage::userMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String&& invalidConstraint)
4047 {
4048     m_userMediaPermissionRequestManager->userMediaAccessWasDenied(userMediaID, static_cast<UserMediaRequest::MediaAccessDenialReason>(reason), WTFMove(invalidConstraint));
4049 }
4050
4051 void WebPage::didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vector<CaptureDevice>& devices, String&& deviceIdentifierHashSalt, bool originHasPersistentAccess)
4052 {
4053     m_userMediaPermissionRequestManager->didCompleteMediaDeviceEnumeration(userMediaID, devices, WTFMove(deviceIdentifierHashSalt), originHasPersistentAccess);
4054 }
4055
4056 void WebPage::captureDevicesChanged()
4057 {
4058     m_userMediaPermissionRequestManager->captureDevicesChanged();
4059 }
4060
4061 #if ENABLE(SANDBOX_EXTENSIONS)
4062 void WebPage::grantUserMediaDeviceSandboxExtensions(MediaDeviceSandboxExtensions&& extensions)
4063 {
4064     m_userMediaPermissionRequestManager->grantUserMediaDeviceSandboxExtensions(WTFMove(extensions));
4065 }
4066
4067 void WebPage::revokeUserMediaDeviceSandboxExtensions(const Vector<String>& extensionIDs)
4068 {
4069     m_userMediaPermissionRequestManager->revokeUserMediaDeviceSandboxExtensions(extensionIDs);
4070 }
4071 #endif
4072 #endif
4073
4074 #if !PLATFORM(IOS_FAMILY)
4075 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
4076 {
4077     Frame& frame = m_page->focusController().focusedOrMainFrame();
4078     frame.editor().advanceToNextMisspelling(startBeforeSelection);
4079 }
4080 #endif
4081
4082 bool WebPage::hasRichlyEditableSelection() const
4083 {
4084     auto& frame = m_page->focusController().focusedOrMainFrame();
4085     if (m_page->dragCaretController().isContentRichlyEditable())
4086         return true;
4087
4088     return frame.selection().selection().isContentRichlyEditable();
4089 }
4090
4091 void WebPage::changeSpellingToWord(const String& word)
4092 {
4093     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
4094 }
4095
4096 void WebPage::unmarkAllMisspellings()
4097 {
4098     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
4099         if (Document* document = frame->document())
4100             document->markers().removeMarkers(DocumentMarker::Spelling);
4101     }
4102 }
4103
4104 void WebPage::unmarkAllBadGrammar()
4105 {
4106     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
4107         if (Document* document = frame->document())
4108             document->markers().removeMarkers(DocumentMarker::Grammar);
4109     }
4110 }
4111
4112 #if USE(APPKIT)
4113 void WebPage::uppercaseWord()
4114 {
4115     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
4116 }
4117
4118 void WebPage::lowercaseWord()
4119 {
4120     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
4121 }
4122
4123 void WebPage::capitalizeWord()
4124 {
4125     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
4126 }
4127 #endif
4128     
4129 void WebPage::setTextForActivePopupMenu(int32_t index)
4130 {
4131     if (!m_activePopupMenu)
4132         return;
4133
4134     m_activePopupMenu->setTextForIndex(index);
4135 }
4136
4137 #if PLATFORM(GTK)
4138 void WebPage::failedToShowPopupMenu()
4139 {
4140     if (!m_activePopupMenu)
4141         return;
4142
4143     m_activePopupMenu->client()->popupDidHide();
4144 }
4145 #endif
4146
4147 #if ENABLE(CONTEXT_MENUS)
4148 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
4149 {
4150     if (!m_contextMenu)
4151         return;
4152
4153     m_contextMenu->itemSelected(item);
4154     m_contextMenu = nullptr;
4155 }
4156 #endif
4157
4158 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
4159 {
4160     return frame->editor().replaceSelectionWithText(text, WebCore::Editor::SelectReplacement::Yes, WebCore::Editor::SmartReplace::No);
4161 }