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