Get rid of WebPage::m_shouldResetDrawingAreaAfterSuspend flag
[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 the UIProcess created a new DrawingArea, then we need to do the same.
728     if (m_drawingArea->identifier() != parameters.drawingAreaIdentifier) {
729         auto oldDrawingArea = std::exchange(m_drawingArea, nullptr);
730         oldDrawingArea->removeMessageReceiverIfNeeded();
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
743     setViewLayoutSize(parameters.viewLayoutSize);
744
745     if (m_activityState != parameters.activityState)
746         setActivityState(parameters.activityState, ActivityStateChangeAsynchronous, Vector<CallbackID>());
747     if (m_layerHostingMode != parameters.layerHostingMode)
748         setLayerHostingMode(parameters.layerHostingMode);
749
750     platformReinitialize();
751 }
752
753 void WebPage::updateThrottleState()
754 {
755     bool isActive = m_activityState.containsAny({ ActivityState::IsLoading, ActivityState::IsAudible, ActivityState::IsCapturingMedia, ActivityState::WindowIsActive });
756     bool isVisuallyIdle = m_activityState.contains(ActivityState::IsVisuallyIdle);
757     bool pageSuppressed = m_processSuppressionEnabled && !isActive && isVisuallyIdle;
758
759 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
760     if (!pageSuppressed) {
761         // App nap must be manually enabled when not running the NSApplication run loop.
762         static std::once_flag onceKey;
763         std::call_once(onceKey, [] {
764             __CFRunLoopSetOptionsReason(__CFRunLoopOptionsEnableAppNap, CFSTR("Finished checkin as application - enable app nap"));
765         });
766     }
767 #endif
768     // The UserActivity keeps the processes runnable. So if the page should be suppressed, stop the activity.
769     // If the page should not be supressed, start it.
770     if (pageSuppressed)
771         m_userActivityHysteresis.stop();
772     else
773         m_userActivityHysteresis.start();
774 }
775
776 void WebPage::updateUserActivity()
777 {
778     if (m_userActivityHysteresis.state() == PAL::HysteresisState::Started)
779         m_userActivity.start();
780     else
781         m_userActivity.stop();
782 }
783
784 WebPage::~WebPage()
785 {
786     ASSERT(!m_page);
787
788     platformDetach();
789     
790     m_sandboxExtensionTracker.invalidate();
791
792     for (auto* pluginView : m_pluginViews)
793         pluginView->webPageDestroyed();
794
795 #if !PLATFORM(IOS_FAMILY)
796     if (m_headerBanner)
797         m_headerBanner->detachFromPage();
798     if (m_footerBanner)
799         m_footerBanner->detachFromPage();
800 #endif // !PLATFORM(IOS_FAMILY)
801
802 #ifndef NDEBUG
803     webPageCounter.decrement();
804 #endif
805     
806 #if (PLATFORM(IOS_FAMILY) && HAVE(AVKIT)) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
807     if (m_playbackSessionManager)
808         m_playbackSessionManager->invalidate();
809
810     if (m_videoFullscreenManager)
811         m_videoFullscreenManager->invalidate();
812 #endif
813 }
814
815 IPC::Connection* WebPage::messageSenderConnection() const
816 {
817     return WebProcess::singleton().parentProcessConnection();
818 }
819
820 uint64_t WebPage::messageSenderDestinationID() const
821 {
822     return pageID();
823 }
824
825 #if ENABLE(CONTEXT_MENUS)
826 void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>&& contextMenuClient)
827 {
828     if (!contextMenuClient) {
829         m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
830         return;
831     }
832
833     m_contextMenuClient = WTFMove(contextMenuClient);
834 }
835 #endif
836
837 void WebPage::setInjectedBundleEditorClient(std::unique_ptr<API::InjectedBundle::EditorClient>&& editorClient)
838 {
839     if (!editorClient) {
840         m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
841         return;
842     }
843
844     m_editorClient = WTFMove(editorClient);
845 }
846
847 void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>&& formClient)
848 {
849     if (!formClient) {
850         m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
851         return;
852     }
853
854     m_formClient = WTFMove(formClient);
855 }
856
857 void WebPage::setInjectedBundlePageLoaderClient(std::unique_ptr<API::InjectedBundle::PageLoaderClient>&& loaderClient)
858 {
859     if (!loaderClient) {
860         m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
861         return;
862     }
863
864     m_loaderClient = WTFMove(loaderClient);
865
866     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
867     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
868     // for backwards compatibility.
869     if (auto milestones = m_loaderClient->layoutMilestones())
870         listenForLayoutMilestones(milestones);
871 }
872
873 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
874 {
875     m_policyClient.initialize(client);
876 }
877
878 void WebPage::setInjectedBundleResourceLoadClient(std::unique_ptr<API::InjectedBundle::ResourceLoadClient>&& client)
879 {
880     if (!m_resourceLoadClient)
881         m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
882     else
883         m_resourceLoadClient = WTFMove(client);
884 }
885
886 void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>&& uiClient)
887 {
888     if (!uiClient) {
889         m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
890         return;
891     }
892
893     m_uiClient = WTFMove(uiClient);
894 }
895
896 #if ENABLE(FULLSCREEN_API)
897 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
898 {
899     m_fullScreenClient.initialize(client);
900 }
901 #endif
902
903 #if ENABLE(NETSCAPE_PLUGIN_API)
904
905 constexpr int smallPluginDimensionThreshold = 5;
906
907 static bool pluginIsSmall(WebCore::HTMLPlugInElement& pluginElement)
908 {
909     auto* renderer = pluginElement.renderer();
910     if (!is<RenderEmbeddedObject>(*renderer))
911         return false;
912
913     auto& box = downcast<RenderBox>(*renderer);
914     return box.contentWidth() <= smallPluginDimensionThreshold && box.contentHeight() <= smallPluginDimensionThreshold;
915 }
916
917 RefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
918 {
919     String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
920     String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
921
922 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
923     HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement);
924     unsigned pluginArea = 0;
925     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
926 #else
927     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
928 #endif
929
930     bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins();
931
932     uint64_t pluginProcessToken;
933     uint32_t pluginLoadPolicy;
934     String unavailabilityDescription;
935     bool isUnsupported;
936     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)))
937         return nullptr;
938
939     PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy);
940     bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility);
941
942     if (isUnsupported || isBlockedPlugin || !pluginProcessToken) {
943 #if ENABLE(PDFKIT_PLUGIN)
944         String path = parameters.url.path();
945         if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWithIgnoringASCIICase(".pdf") || path.endsWithIgnoringASCIICase(".ps")))))
946             return PDFPlugin::create(*frame);
947 #endif
948     }
949
950     if (isUnsupported) {
951         pluginElement->setReplacement(RenderEmbeddedObject::UnsupportedPlugin, unavailabilityDescription);
952         return nullptr;
953     }
954
955     if (isBlockedPlugin) {
956         bool isReplacementObscured = pluginElement->setReplacement(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
957         send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, isReplacementObscured));
958         return nullptr;
959     }
960
961     if (!pluginProcessToken)
962         return nullptr;
963
964     if (m_page->settings().blockingOfSmallPluginsEnabled() && pluginIsSmall(*pluginElement)) {
965         RELEASE_LOG(Plugins, "Blocking a plugin because it is too small");
966         pluginElement->setReplacement(RenderEmbeddedObject::PluginTooSmall, pluginTooSmallText());
967         return nullptr;
968     }
969
970     bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
971     return PluginProxy::create(pluginProcessToken, isRestartedProcess);
972 }
973 #endif // ENABLE(NETSCAPE_PLUGIN_API)
974
975 #if ENABLE(WEBGL) && !PLATFORM(MAC)
976 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const URL&)
977 {
978     return WebGLAllowCreation;
979 }
980
981 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const URL&)
982 {
983     return WebGLAllowCreation;
984 }
985 #endif
986
987 EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const
988 {
989     Frame& frame = m_page->focusController().focusedOrMainFrame();
990
991     EditorState result;
992
993     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
994         if (!pluginView->getSelectionString().isNull()) {
995             result.selectionIsNone = false;
996             result.selectionIsRange = true;
997             result.isInPlugin = true;
998             return result;
999         }
1000     }
1001
1002     const VisibleSelection& selection = frame.selection().selection();
1003     const Editor& editor = frame.editor();
1004
1005     result.selectionIsNone = selection.isNone();
1006     result.selectionIsRange = selection.isRange();
1007     result.isContentEditable = selection.isContentEditable();
1008     result.isContentRichlyEditable = selection.isContentRichlyEditable();
1009     result.isInPasswordField = selection.isInPasswordField();
1010     result.hasComposition = editor.hasComposition();
1011     result.shouldIgnoreSelectionChanges = editor.ignoreSelectionChanges();
1012
1013     if (auto* document = frame.document())
1014         result.originIdentifierForPasteboard = document->originIdentifierForPasteboard();
1015
1016     bool canIncludePostLayoutData = frame.view() && !frame.view()->needsLayout();
1017     if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::Yes && canIncludePostLayoutData) {
1018         auto& postLayoutData = result.postLayoutData();
1019         postLayoutData.canCut = editor.canCut();
1020         postLayoutData.canCopy = editor.canCopy();
1021         postLayoutData.canPaste = editor.canPaste();
1022
1023         if (m_needsFontAttributes)
1024             postLayoutData.fontAttributes = editor.fontAttributesAtSelectionStart();
1025
1026 #if PLATFORM(COCOA)
1027         if (result.isContentEditable && !selection.isNone()) {
1028             if (auto editingStyle = EditingStyle::styleAtSelectionStart(selection)) {
1029                 if (editingStyle->hasStyle(CSSPropertyFontWeight, "bold"))
1030                     postLayoutData.typingAttributes |= AttributeBold;
1031
1032                 if (editingStyle->hasStyle(CSSPropertyFontStyle, "italic") || editingStyle->hasStyle(CSSPropertyFontStyle, "oblique"))
1033                     postLayoutData.typingAttributes |= AttributeItalics;
1034
1035                 if (editingStyle->hasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline"))
1036                     postLayoutData.typingAttributes |= AttributeUnderline;
1037
1038                 if (auto* styleProperties = editingStyle->style()) {
1039                     bool isLeftToRight = styleProperties->propertyAsValueID(CSSPropertyDirection) == CSSValueLtr;
1040                     switch (styleProperties->propertyAsValueID(CSSPropertyTextAlign)) {
1041                     case CSSValueRight:
1042                     case CSSValueWebkitRight:
1043                         postLayoutData.textAlignment = RightAlignment;
1044                         break;
1045                     case CSSValueLeft:
1046                     case CSSValueWebkitLeft:
1047                         postLayoutData.textAlignment = LeftAlignment;
1048                         break;
1049                     case CSSValueCenter:
1050                     case CSSValueWebkitCenter:
1051                         postLayoutData.textAlignment = CenterAlignment;
1052                         break;
1053                     case CSSValueJustify:
1054                         postLayoutData.textAlignment = JustifiedAlignment;
1055                         break;
1056                     case CSSValueStart:
1057                         postLayoutData.textAlignment = isLeftToRight ? LeftAlignment : RightAlignment;
1058                         break;
1059                     case CSSValueEnd:
1060                         postLayoutData.textAlignment = isLeftToRight ? RightAlignment : LeftAlignment;
1061                         break;
1062                     default:
1063                         break;
1064                     }
1065                     if (auto textColor = styleProperties->propertyAsColor(CSSPropertyColor))
1066                         postLayoutData.textColor = *textColor;
1067                 }
1068             }
1069
1070             if (auto* enclosingListElement = enclosingList(selection.start().containerNode())) {
1071                 if (is<HTMLUListElement>(*enclosingListElement))
1072                     postLayoutData.enclosingListType = UnorderedList;
1073                 else if (is<HTMLOListElement>(*enclosingListElement))
1074                     postLayoutData.enclosingListType = OrderedList;
1075                 else
1076                     ASSERT_NOT_REACHED();
1077             }
1078
1079             postLayoutData.baseWritingDirection = editor.baseWritingDirectionForSelectionStart();
1080         }
1081 #endif
1082     }
1083
1084     platformEditorState(frame, result, shouldIncludePostLayoutData);
1085
1086     m_lastEditorStateWasContentEditable = result.isContentEditable ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1087
1088     return result;
1089 }
1090
1091 void WebPage::changeFontAttributes(WebCore::FontAttributeChanges&& changes)
1092 {
1093     auto& frame = m_page->focusController().focusedOrMainFrame();
1094     if (frame.selection().selection().isContentEditable())
1095         frame.editor().applyStyleToSelection(changes.createEditingStyle(), changes.editAction(), Editor::ColorFilterMode::InvertColor);
1096 }
1097
1098 void WebPage::changeFont(WebCore::FontChanges&& changes)
1099 {
1100     auto& frame = m_page->focusController().focusedOrMainFrame();
1101     if (frame.selection().selection().isContentEditable())
1102         frame.editor().applyStyleToSelection(changes.createEditingStyle(), EditAction::SetFont, Editor::ColorFilterMode::InvertColor);
1103 }
1104
1105 void WebPage::executeEditCommandWithCallback(const String& commandName, const String& argument, CallbackID callbackID)
1106 {
1107     executeEditCommand(commandName, argument);
1108     send(Messages::WebPageProxy::VoidCallback(callbackID));
1109 }
1110
1111 void WebPage::updateEditorStateAfterLayoutIfEditabilityChanged()
1112 {
1113     // FIXME: We should update EditorStateIsContentEditable to track whether the state is richly
1114     // editable or plainttext-only.
1115     if (m_lastEditorStateWasContentEditable == EditorStateIsContentEditable::Unset)
1116         return;
1117
1118     Frame& frame = m_page->focusController().focusedOrMainFrame();
1119     EditorStateIsContentEditable editorStateIsContentEditable = frame.selection().selection().isContentEditable() ? EditorStateIsContentEditable::Yes : EditorStateIsContentEditable::No;
1120     if (m_lastEditorStateWasContentEditable != editorStateIsContentEditable)
1121         sendPartialEditorStateAndSchedulePostLayoutUpdate();
1122 }
1123
1124 String WebPage::renderTreeExternalRepresentation() const
1125 {
1126     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
1127 }
1128
1129 String WebPage::renderTreeExternalRepresentationForPrinting() const
1130 {
1131     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
1132 }
1133
1134 uint64_t WebPage::renderTreeSize() const
1135 {
1136     if (!m_page)
1137         return 0;
1138     return m_page->renderTreeSize();
1139 }
1140
1141 void WebPage::setTracksRepaints(bool trackRepaints)
1142 {
1143     if (FrameView* view = mainFrameView())
1144         view->setTracksRepaints(trackRepaints);
1145 }
1146
1147 bool WebPage::isTrackingRepaints() const
1148 {
1149     if (FrameView* view = mainFrameView())
1150         return view->isTrackingRepaints();
1151
1152     return false;
1153 }
1154
1155 void WebPage::resetTrackedRepaints()
1156 {
1157     if (FrameView* view = mainFrameView())
1158         view->resetTrackedRepaints();
1159 }
1160
1161 Ref<API::Array> WebPage::trackedRepaintRects()
1162 {
1163     FrameView* view = mainFrameView();
1164     if (!view)
1165         return API::Array::create();
1166
1167     Vector<RefPtr<API::Object>> repaintRects;
1168     repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
1169
1170     for (const auto& repaintRect : view->trackedRepaintRects())
1171         repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
1172
1173     return API::Array::create(WTFMove(repaintRects));
1174 }
1175
1176 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
1177 {
1178     if (!is<PluginDocument>(frame.document()))
1179         return nullptr;
1180
1181     auto& pluginDocument = downcast<PluginDocument>(*frame.document());
1182     if (pluginDocument.focusedElement() != pluginDocument.pluginElement())
1183         return nullptr;
1184
1185     return pluginViewForFrame(&frame);
1186 }
1187
1188 PluginView* WebPage::pluginViewForFrame(Frame* frame)
1189 {
1190     if (!frame || !is<PluginDocument>(frame->document()))
1191         return nullptr;
1192
1193     auto& document = downcast<PluginDocument>(*frame->document());
1194     return static_cast<PluginView*>(document.pluginWidget());
1195 }
1196
1197 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
1198 {
1199     Frame& frame = m_page->focusController().focusedOrMainFrame();
1200
1201     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
1202         pluginView->handleEditingCommand(commandName, argument);
1203         return;
1204     }
1205     
1206     frame.editor().command(commandName).execute(argument);
1207 }
1208
1209 void WebPage::setEditable(bool editable)
1210 {
1211     m_page->setEditable(editable);
1212     m_page->setTabKeyCyclesThroughElements(!editable);
1213     Frame& frame = m_page->focusController().focusedOrMainFrame();
1214     if (editable) {
1215         frame.editor().applyEditingStyleToBodyElement();
1216         // If the page is made editable and the selection is empty, set it to something.
1217         if (frame.selection().isNone())
1218             frame.selection().setSelectionFromNone();
1219     }
1220 }
1221
1222 void WebPage::increaseListLevel()
1223 {
1224     m_page->focusController().focusedOrMainFrame().editor().increaseSelectionListLevel();
1225 }
1226
1227 void WebPage::decreaseListLevel()
1228 {
1229     m_page->focusController().focusedOrMainFrame().editor().decreaseSelectionListLevel();
1230 }
1231
1232 void WebPage::changeListType()
1233 {
1234     m_page->focusController().focusedOrMainFrame().editor().changeSelectionListType();
1235 }
1236
1237 void WebPage::setBaseWritingDirection(WritingDirection direction)
1238 {
1239     m_page->focusController().focusedOrMainFrame().editor().setBaseWritingDirection(direction);
1240 }
1241
1242 bool WebPage::isEditingCommandEnabled(const String& commandName)
1243 {
1244     Frame& frame = m_page->focusController().focusedOrMainFrame();
1245
1246     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1247         return pluginView->isEditingCommandEnabled(commandName);
1248     
1249     Editor::Command command = frame.editor().command(commandName);
1250     return command.isSupported() && command.isEnabled();
1251 }
1252     
1253 void WebPage::clearMainFrameName()
1254 {
1255     if (Frame* frame = mainFrame())
1256         frame->tree().clearName();
1257 }
1258
1259 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
1260 {
1261     m_drawingArea->setRootCompositingLayer(layer);
1262 }
1263
1264 void WebPage::exitAcceleratedCompositingMode()
1265 {
1266     m_drawingArea->setRootCompositingLayer(nullptr);
1267 }
1268
1269 void WebPage::close()
1270 {
1271     if (m_isClosed)
1272         return;
1273
1274 #if ENABLE(RESOURCE_LOAD_STATISTICS)
1275     WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::ClearPageSpecificDataForResourceLoadStatistics(sessionID(), m_pageID), 0);
1276 #endif
1277
1278     m_isClosed = true;
1279
1280     // If there is still no URL, then we never loaded anything in this page, so nothing to report.
1281     if (!mainWebFrame()->url().isEmpty())
1282         reportUsedFeatures();
1283
1284     if (WebProcess::singleton().injectedBundle())
1285         WebProcess::singleton().injectedBundle()->willDestroyPage(this);
1286
1287     if (m_inspector) {
1288         m_inspector->disconnectFromPage();
1289         m_inspector = nullptr;
1290     }
1291
1292     m_page->inspectorController().disconnectAllFrontends();
1293
1294 #if ENABLE(FULLSCREEN_API)
1295     m_fullScreenManager = nullptr;
1296 #endif
1297
1298     if (m_activePopupMenu) {
1299         m_activePopupMenu->disconnectFromPage();
1300         m_activePopupMenu = nullptr;
1301     }
1302
1303     if (m_activeOpenPanelResultListener) {
1304         m_activeOpenPanelResultListener->disconnectFromPage();
1305         m_activeOpenPanelResultListener = nullptr;
1306     }
1307
1308 #if ENABLE(INPUT_TYPE_COLOR)
1309     if (m_activeColorChooser) {
1310         m_activeColorChooser->disconnectFromPage();
1311         m_activeColorChooser = nullptr;
1312     }
1313 #endif
1314
1315 #if PLATFORM(GTK)
1316     if (m_printOperation) {
1317         m_printOperation->disconnectFromPage();
1318         m_printOperation = nullptr;
1319     }
1320 #endif
1321
1322 #if ENABLE(VIDEO) && USE(GSTREAMER)
1323     if (m_installMediaPluginsCallback) {
1324         m_installMediaPluginsCallback->invalidate();
1325         m_installMediaPluginsCallback = nullptr;
1326     }
1327 #endif
1328
1329     m_sandboxExtensionTracker.invalidate();
1330
1331 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
1332     m_determinePrimarySnapshottedPlugInTimer.stop();
1333 #endif
1334
1335 #if ENABLE(CONTEXT_MENUS)
1336     m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>();
1337 #endif
1338     m_editorClient = std::make_unique<API::InjectedBundle::EditorClient>();
1339     m_formClient = std::make_unique<API::InjectedBundle::FormClient>();
1340     m_loaderClient = std::make_unique<API::InjectedBundle::PageLoaderClient>();
1341     m_policyClient.initialize(0);
1342     m_resourceLoadClient = std::make_unique<API::InjectedBundle::ResourceLoadClient>();
1343     m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>();
1344 #if ENABLE(FULLSCREEN_API)
1345     m_fullScreenClient.initialize(0);
1346 #endif
1347
1348     m_printContext = nullptr;
1349     m_mainFrame->coreFrame()->loader().detachFromParent();
1350     m_drawingArea = nullptr;
1351
1352     DeferredPageDestructor::createDeferredPageDestructor(WTFMove(m_page), this);
1353
1354     bool isRunningModal = m_isRunningModal;
1355     m_isRunningModal = false;
1356
1357     auto& webProcess = WebProcess::singleton();
1358 #if ENABLE(ASYNC_SCROLLING)
1359     if (m_useAsyncScrolling)
1360         webProcess.eventDispatcher().removeScrollingTreeForPage(this);
1361 #endif
1362     webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
1363     // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
1364     webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
1365     webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID);
1366     webProcess.removeMessageReceiver(Messages::RemoteWebInspectorUI::messageReceiverName(), m_pageID);
1367 #if ENABLE(FULLSCREEN_API)
1368     webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
1369 #endif
1370 #if PLATFORM(COCOA) || PLATFORM(GTK)
1371     m_viewGestureGeometryCollector = nullptr;
1372 #endif
1373
1374     // The WebPage can be destroyed by this call.
1375     WebProcess::singleton().removeWebPage(m_pageID);
1376
1377     WebProcess::singleton().updateActivePages();
1378
1379     if (isRunningModal)
1380         RunLoop::main().stop();
1381 }
1382
1383 void WebPage::tryClose()
1384 {
1385     SendStopResponsivenessTimer stopper;
1386
1387     if (!corePage()->userInputBridge().tryClosePage())
1388         return;
1389
1390     send(Messages::WebPageProxy::ClosePage(true));
1391 }
1392
1393 void WebPage::sendClose()
1394 {
1395     send(Messages::WebPageProxy::ClosePage(false));
1396 }
1397
1398 void WebPage::suspendForProcessSwap()
1399 {
1400     auto failedToSuspend = [this, protectedThis = makeRef(*this)] {
1401         send(Messages::WebPageProxy::DidFailToSuspendAfterProcessSwap());
1402     };
1403
1404     auto* currentHistoryItem = m_mainFrame->coreFrame()->loader().history().currentItem();
1405     if (!currentHistoryItem) {
1406         failedToSuspend();
1407         return;
1408     }
1409
1410     if (!PageCache::singleton().addIfCacheable(*currentHistoryItem, corePage())) {
1411         failedToSuspend();
1412         return;
1413     }
1414
1415     send(Messages::WebPageProxy::DidSuspendAfterProcessSwap());
1416 }
1417
1418 void WebPage::loadURLInFrame(URL&& url, uint64_t frameID)
1419 {
1420     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1421     if (!frame)
1422         return;
1423
1424     frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(url), ShouldOpenExternalURLsPolicy::ShouldNotAllow));
1425 }
1426
1427 void WebPage::loadDataInFrame(IPC::DataReference&& data, String&& MIMEType, String&& encodingName, URL&& baseURL, uint64_t frameID)
1428 {
1429     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1430     if (!frame)
1431         return;
1432
1433     auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
1434     ResourceResponse response(baseURL, MIMEType, sharedBuffer->size(), encodingName);
1435     SubstituteData substituteData(WTFMove(sharedBuffer), baseURL, WTFMove(response), SubstituteData::SessionHistoryVisibility::Hidden);
1436     frame->coreFrame()->loader().load(FrameLoadRequest(*frame->coreFrame(), ResourceRequest(baseURL), ShouldOpenExternalURLsPolicy::ShouldNotAllow, WTFMove(substituteData)));
1437 }
1438
1439 #if !PLATFORM(COCOA)
1440 void WebPage::platformDidReceiveLoadParameters(const LoadParameters& loadParameters)
1441 {
1442 }
1443 #endif
1444
1445 void WebPage::loadRequest(LoadParameters&& loadParameters)
1446 {
1447     SendStopResponsivenessTimer stopper;
1448
1449     m_pendingNavigationID = loadParameters.navigationID;
1450     m_pendingWebsitePolicies = WTFMove(loadParameters.websitePolicies);
1451
1452     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), WTFMove(loadParameters.sandboxExtensionHandle));
1453
1454     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1455     // to all the client to set up any needed state.
1456     m_loaderClient->willLoadURLRequest(*this, loadParameters.request, WebProcess::singleton().transformHandlesToObjects(loadParameters.userData.object()).get());
1457
1458     platformDidReceiveLoadParameters(loadParameters);
1459
1460     // Initate the load in WebCore.
1461     FrameLoadRequest frameLoadRequest { *m_mainFrame->coreFrame(), loadParameters.request, ShouldOpenExternalURLsPolicy::ShouldNotAllow };
1462     ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(loadParameters.shouldOpenExternalURLsPolicy);
1463     frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy);
1464     frameLoadRequest.setShouldTreatAsContinuingLoad(loadParameters.shouldTreatAsContinuingLoad);
1465     frameLoadRequest.setLockHistory(loadParameters.lockHistory);
1466     frameLoadRequest.setlockBackForwardList(loadParameters.lockBackForwardList);
1467     frameLoadRequest.setClientRedirectSourceForHistory(loadParameters.clientRedirectSourceForHistory);
1468     frameLoadRequest.setIsRequestFromClientOrUserInput();
1469
1470     corePage()->userInputBridge().loadRequest(WTFMove(frameLoadRequest));
1471
1472     ASSERT(!m_pendingNavigationID);
1473     ASSERT(!m_pendingWebsitePolicies);
1474 }
1475
1476 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)
1477 {
1478     SendStopResponsivenessTimer stopper;
1479
1480     m_pendingNavigationID = navigationID;
1481     m_pendingWebsitePolicies = WTFMove(websitePolicies);
1482
1483     ResourceRequest request(baseURL);
1484     ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName);
1485     SubstituteData substituteData(WTFMove(sharedBuffer), unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden);
1486
1487     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1488     // to all the client to set up any needed state.
1489     m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1490
1491     // Initate the load in WebCore.
1492     FrameLoadRequest frameLoadRequest(*m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData);
1493     frameLoadRequest.setShouldTreatAsContinuingLoad(shouldTreatAsContinuingLoad);
1494     m_mainFrame->coreFrame()->loader().load(WTFMove(frameLoadRequest));
1495 }
1496
1497 void WebPage::loadData(LoadParameters&& loadParameters)
1498 {
1499     platformDidReceiveLoadParameters(loadParameters);
1500
1501     auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1502     URL baseURL = loadParameters.baseURLString.isEmpty() ? WTF::blankURL() : URL(URL(), loadParameters.baseURLString);
1503     loadDataImpl(loadParameters.navigationID, loadParameters.shouldTreatAsContinuingLoad, WTFMove(loadParameters.websitePolicies), WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, URL(), loadParameters.userData);
1504 }
1505
1506 void WebPage::loadAlternateHTML(LoadParameters&& loadParameters)
1507 {
1508     platformDidReceiveLoadParameters(loadParameters);
1509
1510     URL baseURL = loadParameters.baseURLString.isEmpty() ? WTF::blankURL() : URL(URL(), loadParameters.baseURLString);
1511     URL unreachableURL = loadParameters.unreachableURLString.isEmpty() ? URL() : URL(URL(), loadParameters.unreachableURLString);
1512     URL provisionalLoadErrorURL = loadParameters.provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), loadParameters.provisionalLoadErrorURLString);
1513     auto sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(loadParameters.data.data()), loadParameters.data.size());
1514     m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL);    
1515     loadDataImpl(loadParameters.navigationID, loadParameters.shouldTreatAsContinuingLoad, WTFMove(loadParameters.websitePolicies), WTFMove(sharedBuffer), loadParameters.MIMEType, loadParameters.encodingName, baseURL, unreachableURL, loadParameters.userData);
1516     m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ });
1517 }
1518
1519 void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1520 {
1521     Frame* mainFrame = m_mainFrame->coreFrame();
1522     Document* mainFrameDocument = mainFrame->document();
1523     if (!mainFrameDocument)
1524         return;
1525
1526     const int singleClick = 1;
1527     // FIXME: Set modifier keys.
1528     // FIXME: This should probably set IsSimulated::Yes.
1529     auto mouseEvent = MouseEvent::create(eventNames().clickEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes, Event::IsComposed::Yes,
1530         MonotonicTime::now(), nullptr, singleClick, screenPoint, documentPoint, { }, { }, 0, 0, nullptr, 0, WebCore::NoTap, nullptr);
1531
1532     mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.ptr(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1533 }
1534
1535 void WebPage::stopLoadingFrame(uint64_t frameID)
1536 {
1537     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
1538     if (!frame)
1539         return;
1540
1541     corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1542 }
1543
1544 void WebPage::stopLoading()
1545 {
1546     SendStopResponsivenessTimer stopper;
1547
1548     corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1549 }
1550
1551 bool WebPage::defersLoading() const
1552 {
1553     return m_page->defersLoading();
1554 }
1555
1556 void WebPage::setDefersLoading(bool defersLoading)
1557 {
1558     m_page->setDefersLoading(defersLoading);
1559 }
1560
1561 void WebPage::reload(uint64_t navigationID, uint32_t reloadOptions, SandboxExtension::Handle&& sandboxExtensionHandle)
1562 {
1563     SendStopResponsivenessTimer stopper;
1564
1565     ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID);
1566     m_pendingNavigationID = navigationID;
1567
1568     m_sandboxExtensionTracker.beginReload(m_mainFrame.get(), WTFMove(sandboxExtensionHandle));
1569     corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), OptionSet<ReloadOption>::fromRaw(reloadOptions));
1570
1571     if (m_pendingNavigationID) {
1572         // This can happen if FrameLoader::reload() returns early because the document URL is empty.
1573         // The reload does nothing so we need to reset the pending navigation. See webkit.org/b/153210.
1574         m_pendingNavigationID = 0;
1575     }
1576 }
1577
1578 void WebPage::goToBackForwardItem(uint64_t navigationID, const BackForwardItemIdentifier& backForwardItemID, FrameLoadType backForwardType, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad, Optional<WebsitePoliciesData>&& websitePolicies)
1579 {
1580     SendStopResponsivenessTimer stopper;
1581
1582     ASSERT(isBackForwardLoadType(backForwardType));
1583
1584     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1585     ASSERT(item);
1586     if (!item)
1587         return;
1588
1589     LOG(Loading, "In WebProcess pid %i, WebPage %" PRIu64 " is navigating to back/forward URL %s", getCurrentProcessID(), m_pageID, item->url().string().utf8().data());
1590
1591     ASSERT(!m_pendingNavigationID);
1592     m_pendingNavigationID = navigationID;
1593     m_pendingWebsitePolicies = WTFMove(websitePolicies);
1594
1595     m_page->goToItem(*item, backForwardType, shouldTreatAsContinuingLoad);
1596 }
1597
1598 void WebPage::tryRestoreScrollPosition()
1599 {
1600     m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1601 }
1602
1603 void WebPage::layoutIfNeeded()
1604 {
1605     if (m_mainFrame->coreFrame()->view())
1606         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1607 }
1608
1609 WebPage* WebPage::fromCorePage(Page* page)
1610 {
1611     return &static_cast<WebChromeClient&>(page->chrome().client()).page();
1612 }
1613
1614 void WebPage::setSize(const WebCore::IntSize& viewSize)
1615 {
1616     if (m_viewSize == viewSize)
1617         return;
1618
1619     m_viewSize = viewSize;
1620     FrameView* view = m_page->mainFrame().view();
1621     view->resize(viewSize);
1622     m_drawingArea->setNeedsDisplay();
1623
1624 #if USE(COORDINATED_GRAPHICS)
1625     if (view->useFixedLayout())
1626         sendViewportAttributesChanged(m_page->viewportArguments());
1627 #endif
1628 }
1629
1630 #if USE(COORDINATED_GRAPHICS)
1631 void WebPage::sendViewportAttributesChanged(const ViewportArguments& viewportArguments)
1632 {
1633     FrameView* view = m_page->mainFrame().view();
1634     ASSERT(view && view->useFixedLayout());
1635
1636     // Viewport properties have no impact on zero sized fixed viewports.
1637     if (m_viewSize.isEmpty())
1638         return;
1639
1640     // Recalculate the recommended layout size, when the available size (device pixel) changes.
1641     Settings& settings = m_page->settings();
1642
1643     int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1644
1645     // If unset  we use the viewport dimensions. This fits with the behavior of desktop browsers.
1646     int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1647     int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1648
1649     ViewportAttributes attr = computeViewportAttributes(viewportArguments, minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1650
1651     // If no layout was done yet set contentFixedOrigin to (0,0).
1652     IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1653
1654     // Put the width and height to the viewport width and height. In css units however.
1655     // Use FloatSize to avoid truncated values during scale.
1656     FloatSize contentFixedSize = m_viewSize;
1657
1658 #if ENABLE(CSS_DEVICE_ADAPTATION)
1659     // CSS viewport descriptors might be applied to already affected viewport size
1660     // if the page enables/disables stylesheets, so need to keep initial viewport size.
1661     view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1662 #endif
1663
1664     contentFixedSize.scale(1 / attr.initialScale);
1665     view->setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1666
1667     attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1668
1669     // This also takes care of the relayout.
1670     setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1671
1672 #if USE(COORDINATED_GRAPHICS)
1673     m_drawingArea->didChangeViewportAttributes(WTFMove(attr));
1674 #else
1675     send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1676 #endif
1677 }
1678 #endif
1679
1680 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1681 {
1682     FrameView* frameView = m_page->mainFrame().view();
1683
1684     ScrollPosition scrollPosition = frameView->scrollPosition();
1685     ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition();
1686
1687     // If the current scroll position in a direction is the max scroll position 
1688     // we don't want to scroll at all.
1689     IntSize newScrollOffset;
1690     if (scrollPosition.x() < maximumScrollPosition.x())
1691         newScrollOffset.setWidth(scrollOffset.width());
1692     if (scrollPosition.y() < maximumScrollPosition.y())
1693         newScrollOffset.setHeight(scrollOffset.height());
1694
1695     if (newScrollOffset.isZero())
1696         return;
1697
1698     frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1699 }
1700
1701 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1702 {
1703 #if PLATFORM(MAC)
1704     FrameView* mainFrameView = m_page->mainFrame().view();
1705     LocalDefaultSystemAppearance localAppearance(mainFrameView ? mainFrameView->useDarkAppearance() : false);
1706 #endif
1707
1708     GraphicsContextStateSaver stateSaver(graphicsContext);
1709     graphicsContext.clip(rect);
1710
1711     m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect);
1712 }
1713
1714 double WebPage::textZoomFactor() const
1715 {
1716     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1717     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1718         if (pluginView->handlesPageScaleFactor())
1719             return pluginView->pageScaleFactor();
1720         return pageScaleFactor();
1721     }
1722
1723     Frame* frame = m_mainFrame->coreFrame();
1724     if (!frame)
1725         return 1;
1726     return frame->textZoomFactor();
1727 }
1728
1729 void WebPage::setTextZoomFactor(double zoomFactor)
1730 {
1731     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1732     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1733         if (pluginView->handlesPageScaleFactor())
1734             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1735         else
1736             scalePage(zoomFactor, IntPoint());
1737         return;
1738     }
1739
1740     Frame* frame = m_mainFrame->coreFrame();
1741     if (!frame)
1742         return;
1743     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1744 }
1745
1746 double WebPage::pageZoomFactor() const
1747 {
1748     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1749     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1750         if (pluginView->handlesPageScaleFactor())
1751             return pluginView->pageScaleFactor();
1752         return pageScaleFactor();
1753     }
1754
1755     Frame* frame = m_mainFrame->coreFrame();
1756     if (!frame)
1757         return 1;
1758     return frame->pageZoomFactor();
1759 }
1760
1761 void WebPage::setPageZoomFactor(double zoomFactor)
1762 {
1763     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1764     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1765         if (pluginView->handlesPageScaleFactor())
1766             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1767         else
1768             scalePage(zoomFactor, IntPoint());
1769         return;
1770     }
1771
1772     Frame* frame = m_mainFrame->coreFrame();
1773     if (!frame)
1774         return;
1775     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1776 }
1777
1778 static void dumpHistoryItem(HistoryItem& item, size_t indent, bool isCurrentItem, StringBuilder& stringBuilder, const String& directoryName)
1779 {
1780     if (isCurrentItem)
1781         stringBuilder.appendLiteral("curr->  ");
1782     else {
1783         for (size_t i = 0; i < indent; ++i)
1784             stringBuilder.append(' ');
1785     }
1786
1787     auto url = item.url();
1788     if (url.protocolIs("file")) {
1789         size_t start = url.string().find(directoryName);
1790         if (start == WTF::notFound)
1791             start = 0;
1792         else
1793             start += directoryName.length();
1794         stringBuilder.appendLiteral("(file test):");
1795         stringBuilder.append(url.string().substring(start));
1796     } else
1797         stringBuilder.append(url);
1798     
1799     auto& target = item.target();
1800     if (target.length()) {
1801         stringBuilder.appendLiteral(" (in frame \"");
1802         stringBuilder.append(target);
1803         stringBuilder.appendLiteral("\")");
1804     }
1805     
1806     if (item.isTargetItem())
1807         stringBuilder.appendLiteral("  **nav target**");
1808     
1809     stringBuilder.append('\n');
1810     
1811     Vector<Ref<HistoryItem>> children;
1812     children.reserveInitialCapacity(item.children().size());
1813     for (auto& child : item.children())
1814         children.uncheckedAppend(child.copyRef());
1815     std::stable_sort(children.begin(), children.end(), [] (auto& a, auto& b) {
1816         return codePointCompare(a->target(), b->target()) < 0;
1817     });
1818     for (auto& child : children)
1819         dumpHistoryItem(child, indent + 4, false, stringBuilder, directoryName);
1820 }
1821
1822 String WebPage::dumpHistoryForTesting(const String& directory)
1823 {
1824     if (!m_page)
1825         return { };
1826
1827     auto& list = m_page->backForward();
1828     
1829     StringBuilder builder;
1830     int begin = -list.backCount();
1831     if (list.itemAtIndex(begin)->url() == WTF::blankURL())
1832         ++begin;
1833     for (int i = begin; i <= static_cast<int>(list.forwardCount()); ++i)
1834         dumpHistoryItem(*list.itemAtIndex(i), 8, !i, builder, directory);
1835     return builder.toString();
1836 }
1837
1838 void WebPage::clearHistory()
1839 {
1840     if (!m_page)
1841         return;
1842
1843     static_cast<WebBackForwardListProxy&>(m_page->backForward().client()).clear();
1844 }
1845
1846 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1847 {
1848     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1849     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1850         if (pluginView->handlesPageScaleFactor())
1851             pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1852         else
1853             scalePage(pageZoomFactor, IntPoint());
1854         return;
1855     }
1856
1857     Frame* frame = m_mainFrame->coreFrame();
1858     if (!frame)
1859         return;
1860     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1861 }
1862
1863 void WebPage::windowScreenDidChange(uint32_t displayID)
1864 {
1865     m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1866 }
1867
1868 void WebPage::scalePage(double scale, const IntPoint& origin)
1869 {
1870     double totalScale = scale * viewScaleFactor();
1871     bool willChangeScaleFactor = totalScale != totalScaleFactor();
1872
1873 #if PLATFORM(IOS_FAMILY)
1874     if (willChangeScaleFactor) {
1875         if (!m_inDynamicSizeUpdate)
1876             m_dynamicSizeUpdateHistory.clear();
1877         m_scaleWasSetByUIProcess = false;
1878     }
1879 #endif
1880     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1881     if (pluginView && pluginView->handlesPageScaleFactor()) {
1882         // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1883         // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1884         if (m_page->pageScaleFactor() != 1) {
1885             m_page->setPageScaleFactor(1, origin);
1886             for (auto* pluginView : m_pluginViews)
1887                 pluginView->pageScaleFactorDidChange();
1888         }
1889
1890         pluginView->setPageScaleFactor(totalScale, origin);
1891         return;
1892     }
1893
1894     m_page->setPageScaleFactor(totalScale, origin);
1895
1896     // We can't early return before setPageScaleFactor because the origin might be different.
1897     if (!willChangeScaleFactor)
1898         return;
1899
1900     for (auto* pluginView : m_pluginViews)
1901         pluginView->pageScaleFactorDidChange();
1902
1903 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1904     m_drawingArea->deviceOrPageScaleFactorChanged();
1905 #endif
1906
1907     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1908 }
1909
1910 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1911 {
1912     double totalScale = scale * viewScaleFactor();
1913     if (totalScale == totalScaleFactor())
1914         return;
1915
1916     IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1917     double scaleRatio = scale / pageScaleFactor();
1918     scrollPositionAtNewScale.scale(scaleRatio);
1919     scalePage(scale, scrollPositionAtNewScale);
1920 }
1921
1922 double WebPage::totalScaleFactor() const
1923 {
1924     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1925     if (pluginView && pluginView->handlesPageScaleFactor())
1926         return pluginView->pageScaleFactor();
1927
1928     return m_page->pageScaleFactor();
1929 }
1930
1931 double WebPage::pageScaleFactor() const
1932 {
1933     return totalScaleFactor() / viewScaleFactor();
1934 }
1935
1936 double WebPage::viewScaleFactor() const
1937 {
1938     return m_page->viewScaleFactor();
1939 }
1940
1941 void WebPage::scaleView(double scale)
1942 {
1943     if (viewScaleFactor() == scale)
1944         return;
1945
1946     float pageScale = pageScaleFactor();
1947
1948     IntPoint scrollPositionAtNewScale;
1949     if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1950         double scaleRatio = scale / viewScaleFactor();
1951         scrollPositionAtNewScale = mainFrameView->scrollPosition();
1952         scrollPositionAtNewScale.scale(scaleRatio);
1953     }
1954
1955     m_page->setViewScaleFactor(scale);
1956     scalePage(pageScale, scrollPositionAtNewScale);
1957 }
1958
1959 void WebPage::setDeviceScaleFactor(float scaleFactor)
1960 {
1961     if (scaleFactor == m_page->deviceScaleFactor())
1962         return;
1963
1964     m_page->setDeviceScaleFactor(scaleFactor);
1965
1966     // Tell all our plug-in views that the device scale factor changed.
1967 #if PLATFORM(MAC)
1968     for (auto* pluginView : m_pluginViews)
1969         pluginView->setDeviceScaleFactor(scaleFactor);
1970
1971     updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1972 #endif
1973
1974     if (findController().isShowingOverlay()) {
1975         // We must have updated layout to get the selection rects right.
1976         layoutIfNeeded();
1977         findController().deviceScaleFactorDidChange();
1978     }
1979
1980 #if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER)
1981     m_drawingArea->deviceOrPageScaleFactorChanged();
1982 #endif
1983 }
1984
1985 float WebPage::deviceScaleFactor() const
1986 {
1987     return m_page->deviceScaleFactor();
1988 }
1989
1990 void WebPage::accessibilitySettingsDidChange()
1991 {
1992     m_page->accessibilitySettingsDidChange();
1993 }
1994
1995 #if ENABLE(ACCESSIBILITY_EVENTS)
1996 void WebPage::updateAccessibilityEventsEnabled(bool enabled)
1997 {
1998     m_page->settings().setAccessibilityEventsEnabled(enabled);
1999 }
2000 #endif
2001
2002 void WebPage::setUseFixedLayout(bool fixed)
2003 {
2004     // Do not overwrite current settings if initially setting it to false.
2005     if (m_useFixedLayout == fixed)
2006         return;
2007     m_useFixedLayout = fixed;
2008
2009 #if !PLATFORM(IOS_FAMILY)
2010     m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
2011 #endif
2012
2013     FrameView* view = mainFrameView();
2014     if (!view)
2015         return;
2016
2017     view->setUseFixedLayout(fixed);
2018     if (!fixed)
2019         setFixedLayoutSize(IntSize());
2020
2021     send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
2022 }
2023
2024 bool WebPage::setFixedLayoutSize(const IntSize& size)
2025 {
2026     FrameView* view = mainFrameView();
2027     if (!view || view->fixedLayoutSize() == size)
2028         return false;
2029
2030     LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " setFixedLayoutSize " << size);
2031     view->setFixedLayoutSize(size);
2032
2033     send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
2034     return true;
2035 }
2036
2037 IntSize WebPage::fixedLayoutSize() const
2038 {
2039     FrameView* view = mainFrameView();
2040     if (!view)
2041         return IntSize();
2042     return view->fixedLayoutSize();
2043 }
2044
2045 void WebPage::disabledAdaptationsDidChange(const OptionSet<DisabledAdaptations>& disabledAdaptations)
2046 {
2047 #if PLATFORM(IOS_FAMILY)
2048     if (m_viewportConfiguration.setDisabledAdaptations(disabledAdaptations))
2049         viewportConfigurationChanged();
2050 #else
2051     UNUSED_PARAM(disabledAdaptations);
2052 #endif
2053 }
2054
2055 void WebPage::viewportPropertiesDidChange(const ViewportArguments& viewportArguments)
2056 {
2057 #if PLATFORM(IOS_FAMILY)
2058     if (m_viewportConfiguration.setViewportArguments(viewportArguments))
2059         viewportConfigurationChanged();
2060 #endif
2061
2062 #if USE(COORDINATED_GRAPHICS)
2063     FrameView* view = m_page->mainFrame().view();
2064     if (view && view->useFixedLayout())
2065         sendViewportAttributesChanged(viewportArguments);
2066     else
2067         m_drawingArea->didChangeViewportAttributes(ViewportAttributes());
2068 #endif
2069
2070 #if !PLATFORM(IOS_FAMILY) && !USE(COORDINATED_GRAPHICS)
2071     UNUSED_PARAM(viewportArguments);
2072 #endif
2073 }
2074
2075 void WebPage::listenForLayoutMilestones(OptionSet<WebCore::LayoutMilestone> milestones)
2076 {
2077     if (!m_page)
2078         return;
2079     m_page->addLayoutMilestones(milestones);
2080 }
2081
2082 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
2083 {
2084     m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
2085 }
2086     
2087 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
2088 {
2089     m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
2090 }
2091     
2092 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
2093 {
2094     m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
2095 }
2096
2097 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
2098 {
2099     if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
2100         m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
2101 }
2102
2103 void WebPage::setPaginationMode(uint32_t mode)
2104 {
2105     Pagination pagination = m_page->pagination();
2106     pagination.mode = static_cast<Pagination::Mode>(mode);
2107     m_page->setPagination(pagination);
2108 }
2109
2110 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
2111 {
2112     Pagination pagination = m_page->pagination();
2113     pagination.behavesLikeColumns = behavesLikeColumns;
2114     m_page->setPagination(pagination);
2115 }
2116
2117 void WebPage::setPageLength(double pageLength)
2118 {
2119     Pagination pagination = m_page->pagination();
2120     pagination.pageLength = pageLength;
2121     m_page->setPagination(pagination);
2122 }
2123
2124 void WebPage::setGapBetweenPages(double gap)
2125 {
2126     Pagination pagination = m_page->pagination();
2127     pagination.gap = gap;
2128     m_page->setPagination(pagination);
2129 }
2130
2131 void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled)
2132 {
2133     m_page->setPaginationLineGridEnabled(lineGridEnabled);
2134 }
2135
2136 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
2137 {
2138     auto& webProcess = WebProcess::singleton();
2139     InjectedBundle* injectedBundle = webProcess.injectedBundle();
2140     if (!injectedBundle)
2141         return;
2142
2143     injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
2144 }
2145
2146 #if !PLATFORM(IOS_FAMILY)
2147
2148 void WebPage::setHeaderPageBanner(PageBanner* pageBanner)
2149 {
2150     if (m_headerBanner)
2151         m_headerBanner->detachFromPage();
2152
2153     m_headerBanner = pageBanner;
2154
2155     if (m_headerBanner)
2156         m_headerBanner->addToPage(PageBanner::Header, this);
2157 }
2158
2159 PageBanner* WebPage::headerPageBanner()
2160 {
2161     return m_headerBanner.get();
2162 }
2163
2164 void WebPage::setFooterPageBanner(PageBanner* pageBanner)
2165 {
2166     if (m_footerBanner)
2167         m_footerBanner->detachFromPage();
2168
2169     m_footerBanner = pageBanner;
2170
2171     if (m_footerBanner)
2172         m_footerBanner->addToPage(PageBanner::Footer, this);
2173 }
2174
2175 PageBanner* WebPage::footerPageBanner()
2176 {
2177     return m_footerBanner.get();
2178 }
2179
2180 void WebPage::hidePageBanners()
2181 {
2182     if (m_headerBanner)
2183         m_headerBanner->hide();
2184     if (m_footerBanner)
2185         m_footerBanner->hide();
2186 }
2187
2188 void WebPage::showPageBanners()
2189 {
2190     if (m_headerBanner)
2191         m_headerBanner->showIfHidden();
2192     if (m_footerBanner)
2193         m_footerBanner->showIfHidden();
2194 }
2195
2196 void WebPage::setHeaderBannerHeightForTesting(int height)
2197 {
2198     corePage()->setHeaderHeight(height);
2199 }
2200
2201 void WebPage::setFooterBannerHeightForTesting(int height)
2202 {
2203     corePage()->setFooterHeight(height);
2204 }
2205
2206 #endif // !PLATFORM(IOS_FAMILY)
2207
2208 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, CallbackID callbackID)
2209 {
2210     SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
2211     snapshotOptions |= SnapshotOptionsShareable;
2212
2213     RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
2214
2215     ShareableBitmap::Handle handle;
2216     if (image)
2217         image->bitmap().createHandle(handle, SharedMemory::Protection::ReadOnly);
2218
2219     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
2220 }
2221
2222 RefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
2223 {
2224     IntRect snapshotRect = rect;
2225     IntSize bitmapSize = snapshotRect.size();
2226     if (options & SnapshotOptionsPrinting) {
2227         ASSERT(additionalScaleFactor == 1);
2228         Frame* coreFrame = m_mainFrame->coreFrame();
2229         if (!coreFrame)
2230             return nullptr;
2231         bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
2232     } else {
2233         double scaleFactor = additionalScaleFactor;
2234         if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
2235             scaleFactor *= corePage()->deviceScaleFactor();
2236         bitmapSize.scale(scaleFactor);
2237     }
2238
2239     return snapshotAtSize(rect, bitmapSize, options);
2240 }
2241
2242 static void paintSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options, Frame& frame, FrameView& frameView, GraphicsContext& graphicsContext)
2243 {
2244     IntRect snapshotRect = rect;
2245     float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
2246     float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
2247     float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
2248
2249     if (options & SnapshotOptionsPrinting) {
2250         PrintContext::spoolAllPagesWithBoundaries(frame, graphicsContext, snapshotRect.size());
2251         return;
2252     }
2253
2254     Color documentBackgroundColor = frameView.documentBackgroundColor();
2255     Color backgroundColor = (frame.settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView.baseBackgroundColor();
2256     graphicsContext.fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor);
2257
2258     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2259         double deviceScaleFactor = frame.page()->deviceScaleFactor();
2260         graphicsContext.applyDeviceScaleFactor(deviceScaleFactor);
2261         scaleFactor /= deviceScaleFactor;
2262     }
2263
2264     graphicsContext.scale(scaleFactor);
2265     graphicsContext.translate(-snapshotRect.location());
2266
2267     FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
2268     if (options & SnapshotOptionsExcludeSelectionHighlighting)
2269         shouldPaintSelection = FrameView::ExcludeSelection;
2270
2271     FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
2272     if (options & SnapshotOptionsInViewCoordinates)
2273         coordinateSpace = FrameView::ViewCoordinates;
2274
2275     frameView.paintContentsForSnapshot(graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
2276
2277     if (options & SnapshotOptionsPaintSelectionRectangle) {
2278         FloatRect selectionRectangle = frame.selection().selectionBounds();
2279         graphicsContext.setStrokeColor(Color(0xFF, 0, 0));
2280         graphicsContext.strokeRect(selectionRectangle, 1);
2281     }
2282 }
2283
2284 static ShareableBitmap::Configuration snapshotOptionsToBitmapConfiguration(SnapshotOptions options, WebPage& page)
2285 {
2286     ShareableBitmap::Configuration configuration;
2287 #if USE(CG)
2288     if (options & SnapshotOptionsUseScreenColorSpace)
2289         configuration.colorSpace.cgColorSpace = screenColorSpace(page.corePage()->mainFrame().view());
2290 #endif
2291     return configuration;
2292 }
2293
2294 RefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2295 {
2296     Frame* coreFrame = m_mainFrame->coreFrame();
2297     if (!coreFrame)
2298         return nullptr;
2299
2300     FrameView* frameView = coreFrame->view();
2301     if (!frameView)
2302         return nullptr;
2303
2304     auto snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2305     if (!snapshot)
2306         return nullptr;
2307     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2308
2309     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, *graphicsContext);
2310
2311     return snapshot;
2312 }
2313
2314 #if USE(CF)
2315 RetainPtr<CFDataRef> WebPage::pdfSnapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
2316 {
2317     Frame* coreFrame = m_mainFrame->coreFrame();
2318     if (!coreFrame)
2319         return nullptr;
2320
2321     FrameView* frameView = coreFrame->view();
2322     if (!frameView)
2323         return nullptr;
2324
2325     auto data = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0));
2326
2327 #if USE(CG)
2328     auto dataConsumer = adoptCF(CGDataConsumerCreateWithCFData(data.get()));
2329     auto mediaBox = CGRectMake(0, 0, bitmapSize.width(), bitmapSize.height());
2330     auto pdfContext = adoptCF(CGPDFContextCreate(dataConsumer.get(), &mediaBox, nullptr));
2331
2332     CGPDFContextBeginPage(pdfContext.get(), nullptr);
2333
2334     GraphicsContext graphicsContext { pdfContext.get() };
2335     graphicsContext.scale({ 1, -1 });
2336     graphicsContext.translate(0, -bitmapSize.height());
2337     paintSnapshotAtSize(rect, bitmapSize, options, *coreFrame, *frameView, graphicsContext);
2338
2339     CGPDFContextEndPage(pdfContext.get());
2340     CGPDFContextClose(pdfContext.get());
2341 #endif
2342
2343     return data;
2344 }
2345 #endif
2346
2347 RefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
2348 {
2349     Frame* coreFrame = m_mainFrame->coreFrame();
2350     if (!coreFrame)
2351         return nullptr;
2352
2353     FrameView* frameView = coreFrame->view();
2354     if (!frameView)
2355         return nullptr;
2356
2357     if (!node.renderer())
2358         return nullptr;
2359
2360     LayoutRect topLevelRect;
2361     IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
2362     if (snapshotRect.isEmpty())
2363         return nullptr;
2364
2365     double scaleFactor = 1;
2366     IntSize snapshotSize = snapshotRect.size();
2367     unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
2368     if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
2369         scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
2370         snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
2371     }
2372
2373     auto snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options), snapshotOptionsToBitmapConfiguration(options, *this));
2374     if (!snapshot)
2375         return nullptr;
2376     auto graphicsContext = snapshot->bitmap().createGraphicsContext();
2377
2378     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
2379         double deviceScaleFactor = corePage()->deviceScaleFactor();
2380         graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
2381         scaleFactor /= deviceScaleFactor;
2382     }
2383
2384     graphicsContext->scale(scaleFactor);
2385     graphicsContext->translate(-snapshotRect.location());
2386
2387     Color savedBackgroundColor = frameView->baseBackgroundColor();
2388     frameView->setBaseBackgroundColor(Color::transparent);
2389     frameView->setNodeToDraw(&node);
2390
2391     frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
2392
2393     frameView->setBaseBackgroundColor(savedBackgroundColor);
2394     frameView->setNodeToDraw(nullptr);
2395
2396     return snapshot;
2397 }
2398
2399 void WebPage::pageDidScroll()
2400 {
2401 #if PLATFORM(IOS_FAMILY)
2402     if (!m_inDynamicSizeUpdate)
2403         m_dynamicSizeUpdateHistory.clear();
2404 #endif
2405     m_uiClient->pageDidScroll(this);
2406
2407     m_pageScrolledHysteresis.impulse();
2408
2409     send(Messages::WebPageProxy::PageDidScroll());
2410 }
2411
2412 void WebPage::pageStoppedScrolling()
2413 {
2414     // Maintain the current history item's scroll position up-to-date.
2415     if (Frame* frame = m_mainFrame->coreFrame())
2416         frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
2417 }
2418
2419 #if ENABLE(CONTEXT_MENUS)
2420 WebContextMenu* WebPage::contextMenu()
2421 {
2422     if (!m_contextMenu)
2423         m_contextMenu = WebContextMenu::create(this);
2424     return m_contextMenu.get();
2425 }
2426
2427 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
2428 {
2429     corePage()->contextMenuController().clearContextMenu();
2430
2431     // Simulate a mouse click to generate the correct menu.
2432     PlatformMouseEvent mousePressEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2433     corePage()->userInputBridge().handleMousePressEvent(mousePressEvent);
2434     bool handled = corePage()->userInputBridge().handleContextMenuEvent(mousePressEvent, corePage()->mainFrame());
2435     auto* menu = handled ? contextMenu() : nullptr;
2436     PlatformMouseEvent mouseReleaseEvent(point, point, RightButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap);
2437     corePage()->userInputBridge().handleMouseReleaseEvent(mouseReleaseEvent);
2438
2439     return menu;
2440 }
2441 #endif
2442
2443 // Events 
2444
2445 static const WebEvent* g_currentEvent = 0;
2446
2447 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
2448 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
2449 // platform events passed to the event handler code.
2450 const WebEvent* WebPage::currentEvent()
2451 {
2452     return g_currentEvent;
2453 }
2454
2455 void WebPage::freezeLayerTree(LayerTreeFreezeReason reason)
2456 {
2457     RELEASE_LOG(ProcessSuspension, "%p - WebPage (PageID=%llu) - Adding a reason %d to freeze layer tree; current reasons are %d",
2458         this, m_pageID, static_cast<unsigned>(reason), m_LayerTreeFreezeReasons.toRaw());
2459     m_LayerTreeFreezeReasons.add(reason);
2460     updateDrawingAreaLayerTreeFreezeState();
2461 }
2462
2463 void WebPage::unfreezeLayerTree(LayerTreeFreezeReason reason)
2464 {
2465     RELEASE_LOG(ProcessSuspension, "%p - WebPage (PageID=%llu) - Removing a reason %d to freeze layer tree; current reasons are %d",
2466         this, m_pageID, static_cast<unsigned>(reason), m_LayerTreeFreezeReasons.toRaw());
2467     m_LayerTreeFreezeReasons.remove(reason);
2468     updateDrawingAreaLayerTreeFreezeState();
2469 }
2470
2471 void WebPage::updateDrawingAreaLayerTreeFreezeState()
2472 {
2473     if (!m_drawingArea)
2474         return;
2475     m_drawingArea->setLayerTreeStateIsFrozen(!!m_LayerTreeFreezeReasons);
2476 }
2477
2478 void WebPage::callVolatilityCompletionHandlers(bool succeeded)
2479 {
2480     auto completionHandlers = WTFMove(m_markLayersAsVolatileCompletionHandlers);
2481     for (auto& completionHandler : completionHandlers)
2482         completionHandler(succeeded);
2483 }
2484
2485 void WebPage::layerVolatilityTimerFired()
2486 {
2487     Seconds newInterval = m_layerVolatilityTimer.repeatInterval() * 2.;
2488     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2489     if (didSucceed || newInterval > maximumLayerVolatilityTimerInterval) {
2490         m_layerVolatilityTimer.stop();
2491         if (didSucceed)
2492             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Succeeded in marking layers as volatile", this);
2493         else
2494             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Failed to mark layers as volatile within %gms", this, maximumLayerVolatilityTimerInterval.milliseconds());
2495         callVolatilityCompletionHandlers(didSucceed);
2496         return;
2497     }
2498
2499     RELEASE_LOG_ERROR_IF_ALLOWED("%p - WebPage - Failed to mark all layers as volatile, will retry in %g ms", this, newInterval.milliseconds());
2500     m_layerVolatilityTimer.startRepeating(newInterval);
2501 }
2502
2503 bool WebPage::markLayersVolatileImmediatelyIfPossible()
2504 {
2505     return !drawingArea() || drawingArea()->markLayersVolatileImmediatelyIfPossible();
2506 }
2507
2508 void WebPage::markLayersVolatile(WTF::Function<void (bool)>&& completionHandler)
2509 {
2510     RELEASE_LOG_IF_ALLOWED("%p - WebPage::markLayersVolatile()", this);
2511
2512     if (m_layerVolatilityTimer.isActive())
2513         m_layerVolatilityTimer.stop();
2514
2515     if (completionHandler)
2516         m_markLayersAsVolatileCompletionHandlers.append(WTFMove(completionHandler));
2517
2518     bool didSucceed = markLayersVolatileImmediatelyIfPossible();
2519     if (didSucceed || m_isSuspendedUnderLock) {
2520         if (didSucceed)
2521             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Successfully marked layers as volatile", this);
2522         else {
2523             // 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.
2524             RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did what we could to mark IOSurfaces as purgeable after locking the screen", this);
2525         }
2526         callVolatilityCompletionHandlers(didSucceed);
2527         return;
2528     }
2529
2530     RELEASE_LOG_IF_ALLOWED("%p - Failed to mark all layers as volatile, will retry in %g ms", this, initialLayerVolatilityTimerInterval.milliseconds());
2531     m_layerVolatilityTimer.startRepeating(initialLayerVolatilityTimerInterval);
2532 }
2533
2534 void WebPage::cancelMarkLayersVolatile()
2535 {
2536     RELEASE_LOG_IF_ALLOWED("%p - WebPage::cancelMarkLayersVolatile()", this);
2537     m_layerVolatilityTimer.stop();
2538     m_markLayersAsVolatileCompletionHandlers.clear();
2539 }
2540
2541 class CurrentEvent {
2542 public:
2543     explicit CurrentEvent(const WebEvent& event)
2544         : m_previousCurrentEvent(g_currentEvent)
2545     {
2546         g_currentEvent = &event;
2547     }
2548
2549     ~CurrentEvent()
2550     {
2551         g_currentEvent = m_previousCurrentEvent;
2552     }
2553
2554 private:
2555     const WebEvent* m_previousCurrentEvent;
2556 };
2557
2558 #if ENABLE(CONTEXT_MENUS)
2559 static bool isContextClick(const PlatformMouseEvent& event)
2560 {
2561 #if PLATFORM(COCOA)
2562     return WebEventFactory::shouldBeHandledAsContextClick(event);
2563 #else
2564     return event.button() == WebCore::RightButton;
2565 #endif
2566 }
2567
2568 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
2569 {
2570     IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
2571     HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
2572
2573     Frame* frame = &page->corePage()->mainFrame();
2574     if (result.innerNonSharedNode())
2575         frame = result.innerNonSharedNode()->document().frame();
2576
2577     bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, *frame);
2578     if (handled)
2579         page->contextMenu()->show();
2580
2581     return handled;
2582 }
2583
2584 void WebPage::contextMenuForKeyEvent()
2585 {
2586     corePage()->contextMenuController().clearContextMenu();
2587
2588     Frame& frame = m_page->focusController().focusedOrMainFrame();
2589     bool handled = frame.eventHandler().sendContextMenuEventForKey();
2590     if (handled)
2591         contextMenu()->show();
2592 }
2593 #endif
2594
2595 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page)
2596 {
2597     Frame& frame = page->corePage()->mainFrame();
2598     if (!frame.view())
2599         return false;
2600
2601     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2602
2603     switch (platformMouseEvent.type()) {
2604         case PlatformEvent::MousePressed: {
2605 #if ENABLE(CONTEXT_MENUS)
2606             if (isContextClick(platformMouseEvent))
2607                 page->corePage()->contextMenuController().clearContextMenu();
2608 #endif
2609
2610             bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2611 #if ENABLE(CONTEXT_MENUS)
2612             if (isContextClick(platformMouseEvent))
2613                 handled = handleContextMenuEvent(platformMouseEvent, page);
2614 #endif
2615             return handled;
2616         }
2617         case PlatformEvent::MouseReleased:
2618             return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2619
2620         case PlatformEvent::MouseMoved:
2621 #if PLATFORM(COCOA)
2622             // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2623             // button is currently pressed. It is possible that neither of those things will be true since on
2624             // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2625             // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2626             // efficient scrollbars-only version of the event.
2627             if (!(page->corePage()->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)))
2628                 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2629 #endif
2630             return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2631
2632         case PlatformEvent::MouseForceChanged:
2633         case PlatformEvent::MouseForceDown:
2634         case PlatformEvent::MouseForceUp:
2635             return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2636
2637         default:
2638             ASSERT_NOT_REACHED();
2639             return false;
2640     }
2641 }
2642
2643 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2644 {
2645     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2646
2647     m_userActivityHysteresis.impulse();
2648
2649     bool shouldHandleEvent = true;
2650
2651 #if ENABLE(CONTEXT_MENUS)
2652     // Don't try to handle any pending mouse events if a context menu is showing.
2653     if (m_isShowingContextMenu)
2654         shouldHandleEvent = false;
2655 #endif
2656 #if ENABLE(DRAG_SUPPORT)
2657     if (m_isStartingDrag)
2658         shouldHandleEvent = false;
2659 #endif
2660
2661     if (!shouldHandleEvent) {
2662         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2663         return;
2664     }
2665
2666     bool handled = false;
2667
2668 #if !PLATFORM(IOS_FAMILY)
2669     if (!handled && m_headerBanner)
2670         handled = m_headerBanner->mouseEvent(mouseEvent);
2671     if (!handled && m_footerBanner)
2672         handled = m_footerBanner->mouseEvent(mouseEvent);
2673 #endif // !PLATFORM(IOS_FAMILY)
2674
2675     if (!handled) {
2676         CurrentEvent currentEvent(mouseEvent);
2677         handled = handleMouseEvent(mouseEvent, this);
2678     }
2679
2680     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2681 }
2682
2683 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2684 {
2685     Frame& frame = page->mainFrame();
2686     if (!frame.view())
2687         return false;
2688
2689     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2690     return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2691 }
2692
2693 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2694 {
2695     m_userActivityHysteresis.impulse();
2696
2697     CurrentEvent currentEvent(wheelEvent);
2698
2699     bool handled = handleWheelEvent(wheelEvent, m_page.get());
2700
2701     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2702 }
2703
2704 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2705 {
2706     if (!page->mainFrame().view())
2707         return false;
2708
2709     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2710         return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2711     return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2712 }
2713
2714 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2715 {
2716     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2717
2718     m_userActivityHysteresis.impulse();
2719
2720     PlatformKeyboardEvent::setCurrentModifierState(platform(keyboardEvent).modifiers());
2721
2722     CurrentEvent currentEvent(keyboardEvent);
2723
2724     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
2725     // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2726     if (!handled)
2727         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2728
2729     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2730 }
2731
2732 void WebPage::validateCommand(const String& commandName, CallbackID callbackID)
2733 {
2734     bool isEnabled = false;
2735     int32_t state = 0;
2736     Frame& frame = m_page->focusController().focusedOrMainFrame();
2737     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2738         isEnabled = pluginView->isEditingCommandEnabled(commandName);
2739     else {
2740         Editor::Command command = frame.editor().command(commandName);
2741         state = command.state();
2742         isEnabled = command.isSupported() && command.isEnabled();
2743     }
2744
2745     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2746 }
2747
2748 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2749 {
2750     executeEditingCommand(commandName, argument);
2751 }
2752
2753 void WebPage::setNeedsFontAttributes(bool needsFontAttributes)
2754 {
2755     if (m_needsFontAttributes == needsFontAttributes)
2756         return;
2757
2758     m_needsFontAttributes = needsFontAttributes;
2759
2760     if (m_needsFontAttributes)
2761         sendPartialEditorStateAndSchedulePostLayoutUpdate();
2762 }
2763
2764 void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest, WebBackForwardListProxy::OverwriteExistingItem overwrite)
2765 {
2766     // Since we're merely restoring HistoryItems from the UIProcess, there is no need to send HistoryItem update notifications back to the UIProcess.
2767     // Also, with process-swap on navigation, these updates may actually overwrite important state in the UIProcess such as the scroll position.
2768     SetForScope<void (*)(WebCore::HistoryItem&)> bypassHistoryItemUpdateNotifications(WebCore::notifyHistoryItemChanged, [](WebCore::HistoryItem&){});
2769     for (const auto& itemState : itemStates) {
2770         auto historyItem = toHistoryItem(itemState);
2771         historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes);
2772         static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, overwrite);
2773     }
2774 }
2775
2776 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2777 {
2778     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes, WebBackForwardListProxy::OverwriteExistingItem::No);
2779 }
2780
2781 void WebPage::updateBackForwardListForReattach(const Vector<WebKit::BackForwardListItemState>& itemStates)
2782 {
2783     restoreSessionInternal(itemStates, WasRestoredByAPIRequest::No, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2784 }
2785
2786 void WebPage::setCurrentHistoryItemForReattach(WebKit::BackForwardListItemState&& itemState)
2787 {
2788     auto historyItem = toHistoryItem(itemState);
2789     auto& historyItemRef = historyItem.get();
2790     static_cast<WebBackForwardListProxy&>(corePage()->backForward().client()).addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID, WebBackForwardListProxy::OverwriteExistingItem::Yes);
2791     corePage()->mainFrame().loader().history().setCurrentItem(historyItemRef);
2792 }
2793
2794 void WebPage::requestFontAttributesAtSelectionStart(CallbackID callbackID)
2795 {
2796     auto attributes = m_page->focusController().focusedOrMainFrame().editor().fontAttributesAtSelectionStart();
2797     send(Messages::WebPageProxy::FontAttributesCallback(attributes, callbackID));
2798 }
2799
2800 void WebPage::cancelGesturesBlockedOnSynchronousReplies()
2801 {
2802 #if ENABLE(IOS_TOUCH_EVENTS)
2803     if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2804         reply(true);
2805 #endif
2806
2807 #if PLATFORM(IOS_FAMILY)
2808     if (auto reply = WTFMove(m_pendingSynchronousPositionInformationReply))
2809         reply(InteractionInformationAtPosition::invalidInformation());
2810 #endif
2811 }
2812
2813 #if ENABLE(TOUCH_EVENTS)
2814 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2815 {
2816     if (!page->mainFrame().view())
2817         return false;
2818
2819     return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2820 }
2821 #endif
2822
2823 #if ENABLE(IOS_TOUCH_EVENTS)
2824 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2825 {
2826     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
2827
2828     auto oldFocusedFrame = makeRefPtr(m_page->focusController().focusedFrame());
2829     auto oldFocusedElement = makeRefPtr(oldFocusedFrame ? oldFocusedFrame->document()->focusedElement() : nullptr);
2830
2831     m_lastInteractionLocation = touchEvent.position();
2832     CurrentEvent currentEvent(touchEvent);
2833     handled = handleTouchEvent(touchEvent, m_page.get());
2834     updatePotentialTapSecurityOrigin(touchEvent, handled);
2835
2836     if (handled && oldFocusedElement) {
2837         auto newFocusedFrame = makeRefPtr(m_page->focusController().focusedFrame());
2838         auto newFocusedElement = makeRefPtr(newFocusedFrame ? newFocusedFrame->document()->focusedElement() : nullptr);
2839         if (oldFocusedElement == newFocusedElement)
2840             elementDidRefocus(*newFocusedElement);
2841     }
2842 }
2843
2844 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, CompletionHandler<void(bool)>&& reply)
2845 {
2846     m_pendingSynchronousTouchEventReply = WTFMove(reply);
2847
2848     EventDispatcher::TouchEventQueue queuedEvents;
2849     WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2850     dispatchAsynchronousTouchEvents(queuedEvents);
2851
2852     bool handled = true;
2853     dispatchTouchEvent(touchEvent, handled);
2854
2855     if (auto reply = WTFMove(m_pendingSynchronousTouchEventReply))
2856         reply(handled);
2857 }
2858
2859 void WebPage::updatePotentialTapSecurityOrigin(const WebTouchEvent& touchEvent, bool wasHandled)
2860 {
2861     if (wasHandled)
2862         return;
2863
2864     if (!touchEvent.isPotentialTap())
2865         return;
2866
2867     if (touchEvent.type() != WebEvent::TouchStart)
2868         return;
2869
2870     auto& mainFrame = m_page->mainFrame();
2871     auto document = mainFrame.document();
2872     if (!document)
2873         return;
2874
2875     if (!document->handlingTouchEvent())
2876         return;
2877
2878     Frame* touchEventTargetFrame = &mainFrame;
2879     while (auto subframe = touchEventTargetFrame->eventHandler().touchEventTargetSubframe())
2880         touchEventTargetFrame = subframe;
2881
2882     auto& touches = touchEventTargetFrame->eventHandler().touches();
2883     if (touches.isEmpty())
2884         return;
2885
2886     ASSERT(touches.size() == 1);
2887
2888     if (auto targetDocument = touchEventTargetFrame->document())
2889         m_potentialTapSecurityOrigin = &targetDocument->securityOrigin();
2890 }
2891 #elif ENABLE(TOUCH_EVENTS)
2892 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2893 {
2894     CurrentEvent currentEvent(touchEvent);
2895
2896     bool handled = handleTouchEvent(touchEvent, m_page.get());
2897
2898     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2899 }
2900 #endif
2901
2902 #if ENABLE(POINTER_EVENTS)
2903 void WebPage::cancelPointer(WebCore::PointerID pointerId, const WebCore::IntPoint& documentPoint)
2904 {
2905     m_page->pointerCaptureController().cancelPointer(pointerId, documentPoint);
2906 }
2907 #endif
2908
2909 #if ENABLE(MAC_GESTURE_EVENTS)
2910 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2911 {
2912     if (!page->mainFrame().view())
2913         return false;
2914
2915     return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2916 }
2917
2918 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2919 {
2920     CurrentEvent currentEvent(gestureEvent);
2921     bool handled = handleGestureEvent(gestureEvent, m_page.get());
2922     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2923 }
2924 #endif
2925
2926 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2927 {
2928     return page->userInputBridge().scrollRecursively(direction, granularity);
2929 }
2930
2931 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2932 {
2933     return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2934 }
2935
2936 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2937 {
2938     return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2939 }
2940
2941 void WebPage::centerSelectionInVisibleArea()
2942 {
2943     Frame& frame = m_page->focusController().focusedOrMainFrame();
2944     frame.selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
2945     findController().showFindIndicatorInSelection();
2946 }
2947
2948 bool WebPage::isControlledByAutomation() const
2949 {
2950     return m_page->isControlledByAutomation();
2951 }
2952
2953 void WebPage::setControlledByAutomation(bool controlled)
2954 {
2955     m_page->setControlledByAutomation(controlled);
2956 }
2957
2958 void WebPage::connectInspector(const String& targetId, Inspector::FrontendChannel::ConnectionType connectionType)
2959 {
2960     m_inspectorTargetController->connectInspector(targetId, connectionType);
2961 }
2962
2963 void WebPage::disconnectInspector(const String& targetId)
2964 {
2965     m_inspectorTargetController->disconnectInspector(targetId);
2966 }
2967
2968 void WebPage::sendMessageToTargetBackend(const String& targetId, const String& message)
2969 {
2970     m_inspectorTargetController->sendMessageToTargetBackend(targetId, message);
2971 }
2972
2973 void WebPage::insertNewlineInQuotedContent()
2974 {
2975     Frame& frame = m_page->focusController().focusedOrMainFrame();
2976     if (frame.selection().isNone())
2977         return;
2978     frame.editor().insertParagraphSeparatorInQuotedContent();
2979 }
2980
2981 #if ENABLE(REMOTE_INSPECTOR)
2982 void WebPage::setIndicating(bool indicating)
2983 {
2984     m_page->inspectorController().setIndicating(indicating);
2985 }
2986 #endif
2987
2988 void WebPage::setBackgroundColor(const Optional<WebCore::Color>& backgroundColor)
2989 {
2990     if (m_backgroundColor == backgroundColor)
2991         return;
2992
2993     m_backgroundColor = backgroundColor;
2994
2995     if (FrameView* frameView = mainFrameView())
2996         frameView->updateBackgroundRecursively(backgroundColor);
2997
2998     m_drawingArea->setNeedsDisplay();
2999 }
3000
3001 #if PLATFORM(COCOA)
3002 void WebPage::setTopContentInsetFenced(float contentInset, IPC::Attachment fencePort)
3003 {
3004     if (fencePort.disposition() != MACH_MSG_TYPE_MOVE_SEND) {
3005         LOG(Layers, "WebPage::setTopContentInsetFenced(%g, fencePort) Received an invalid fence port: %d, disposition: %d", contentInset, fencePort.port(), fencePort.disposition());
3006         return;
3007     }
3008
3009     m_drawingArea->addFence(MachSendRight::create(fencePort.port()));
3010
3011     setTopContentInset(contentInset);
3012
3013     deallocateSendRightSafely(fencePort.port());
3014 }
3015 #endif
3016
3017 void WebPage::setTopContentInset(float contentInset)
3018 {
3019     if (contentInset == m_page->topContentInset())
3020         return;
3021
3022     m_page->setTopContentInset(contentInset);
3023
3024     for (auto* pluginView : m_pluginViews)
3025         pluginView->topContentInsetDidChange();
3026 }
3027
3028 void WebPage::viewWillStartLiveResize()
3029 {
3030     if (!m_page)
3031         return;
3032
3033     // FIXME: This should propagate to all ScrollableAreas.
3034     Frame& frame = m_page->focusController().focusedOrMainFrame();
3035     if (FrameView* view = frame.view())
3036         view->willStartLiveResize();
3037 }
3038
3039 void WebPage::viewWillEndLiveResize()
3040 {
3041     if (!m_page)
3042         return;
3043
3044     // FIXME: This should propagate to all ScrollableAreas.
3045     Frame& frame = m_page->focusController().focusedOrMainFrame();
3046     if (FrameView* view = frame.view())
3047         view->willEndLiveResize();
3048 }
3049
3050 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, CallbackID callbackID)
3051 {
3052     if (!m_page)
3053         return;
3054
3055     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
3056
3057     Frame& frame = m_page->focusController().focusedOrMainFrame();
3058     frame.document()->setFocusedElement(0);
3059
3060     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
3061         PlatformKeyboardEvent platformEvent(platform(event));
3062         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
3063         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, &frame.windowProxy()).get());
3064
3065         send(Messages::WebPageProxy::VoidCallback(callbackID));
3066         return;
3067     }
3068
3069     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, nullptr);
3070     send(Messages::WebPageProxy::VoidCallback(callbackID));
3071 }
3072
3073 void WebPage::setCanStartMediaTimerFired()
3074 {
3075     if (m_page)
3076         m_page->setCanStartMedia(true);
3077 }
3078
3079 void WebPage::updateIsInWindow(bool isInitialState)
3080 {
3081     bool isInWindow = m_activityState.contains(WebCore::ActivityState::IsInWindow);
3082
3083     if (!isInWindow) {
3084         m_setCanStartMediaTimer.stop();
3085         m_page->setCanStartMedia(false);
3086         
3087         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
3088         if (!isInitialState)
3089             WebProcess::singleton().pageWillLeaveWindow(m_pageID);
3090     } else {
3091         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
3092         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
3093         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
3094         if (m_mayStartMediaWhenInWindow)
3095             m_setCanStartMediaTimer.startOneShot(0_s);
3096
3097         WebProcess::singleton().pageDidEnterWindow(m_pageID);
3098     }
3099
3100     if (isInWindow)
3101         layoutIfNeeded();
3102 }
3103
3104 void WebPage::visibilityDidChange()
3105 {
3106     bool isVisible = m_activityState.contains(ActivityState::IsVisible);
3107     if (!isVisible) {
3108         // We save the document / scroll state when backgrounding a tab so that we are able to restore it
3109         // if it gets terminated while in the background.
3110         if (auto* frame = m_mainFrame->coreFrame())
3111             frame->loader().history().saveDocumentAndScrollState();
3112     }
3113 }
3114
3115 void WebPage::setActivityState(OptionSet<ActivityState::Flag> activityState, ActivityStateChangeID activityStateChangeID, const Vector<CallbackID>& callbackIDs)
3116 {
3117     LOG_WITH_STREAM(ActivityState, stream << "WebPage " << pageID() << " setActivityState to " << activityState);
3118
3119     auto changed = m_activityState ^ activityState;
3120     m_activityState = activityState;
3121
3122     if (changed)
3123         updateThrottleState();
3124
3125     ASSERT_WITH_MESSAGE(m_page, "setActivityState called on %" PRIu64 " but WebCore page was null", pageID());
3126     if (m_page) {
3127         SetForScope<bool> currentlyChangingActivityState { m_changingActivityState, true };
3128         m_page->setActivityState(activityState);
3129     }
3130     
3131     for (auto* pluginView : m_pluginViews)
3132         pluginView->activityStateDidChange(changed);
3133
3134     m_drawingArea->activityStateDidChange(changed, activityStateChangeID, callbackIDs);
3135     WebProcess::singleton().pageActivityStateDidChange(m_pageID, changed);
3136
3137     if (changed & ActivityState::IsInWindow)
3138         updateIsInWindow();
3139
3140     if (changed & ActivityState::IsVisible)
3141         visibilityDidChange();
3142 }
3143
3144 void WebPage::setLayerHostingMode(LayerHostingMode layerHostingMode)
3145 {
3146     m_layerHostingMode = layerHostingMode;
3147
3148     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
3149
3150     for (auto* pluginView : m_pluginViews)
3151         pluginView->setLayerHostingMode(m_layerHostingMode);
3152 }
3153
3154 void WebPage::setSessionID(PAL::SessionID sessionID)
3155 {
3156     m_page->setSessionID(sessionID);
3157 }
3158
3159 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, PolicyCheckIdentifier identifier, PolicyAction policyAction, uint64_t navigationID, const DownloadID& downloadID, Optional<WebsitePoliciesData>&& websitePolicies)
3160 {
3161     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3162     if (!frame)
3163         return;
3164     frame->didReceivePolicyDecision(listenerID, identifier, policyAction, navigationID, downloadID, WTFMove(websitePolicies));
3165 }
3166
3167 void WebPage::continueWillSubmitForm(uint64_t frameID, uint64_t listenerID)
3168 {
3169     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3170     if (!frame)
3171         return;
3172     frame->continueWillSubmitForm(listenerID);
3173 }
3174
3175 void WebPage::didStartPageTransition()
3176 {
3177     freezeLayerTree(LayerTreeFreezeReason::PageTransition);
3178
3179 #if PLATFORM(MAC)
3180     bool hasPreviouslyFocusedDueToUserInteraction = m_hasEverFocusedElementDueToUserInteractionSincePageTransition;
3181 #endif
3182     m_hasEverFocusedElementDueToUserInteractionSincePageTransition = false;
3183     m_lastEditorStateWasContentEditable = EditorStateIsContentEditable::Unset;
3184 #if PLATFORM(MAC)
3185     if (hasPreviouslyFocusedDueToUserInteraction)
3186         send(Messages::WebPageProxy::SetHasHadSelectionChangesFromUserInteraction(m_hasEverFocusedElementDueToUserInteractionSincePageTransition));
3187     if (m_isTouchBarUpdateSupressedForHiddenContentEditable) {
3188         m_isTouchBarUpdateSupressedForHiddenContentEditable = false;
3189         send(Messages::WebPageProxy::SetIsTouchBarUpdateSupressedForHiddenContentEditable(m_isTouchBarUpdateSupressedForHiddenContentEditable));
3190     }
3191     if (m_isNeverRichlyEditableForTouchBar) {
3192         m_isNeverRichlyEditableForTouchBar = false;
3193         send(Messages::WebPageProxy::SetIsNeverRichlyEditableForTouchBar(m_isNeverRichlyEditableForTouchBar));
3194     }
3195 #endif
3196 #if PLATFORM(IOS_FAMILY)
3197     m_isShowingInputViewForFocusedElement = false;
3198 #endif
3199 }
3200
3201 void WebPage::didCompletePageTransition()
3202 {
3203     unfreezeLayerTree(LayerTreeFreezeReason::PageTransition);
3204
3205     RELEASE_LOG_IF_ALLOWED("%p - WebPage - Did complete page transition", this);
3206
3207     bool isInitialEmptyDocument = !m_mainFrame;
3208     if (!isInitialEmptyDocument)
3209         unfreezeLayerTree(LayerTreeFreezeReason::ProcessSwap);
3210 }
3211
3212 void WebPage::show()
3213 {
3214     send(Messages::WebPageProxy::ShowPage());
3215 }
3216
3217 String WebPage::userAgent(const URL& webCoreURL) const
3218 {
3219     String userAgent = platformUserAgent(webCoreURL);
3220     if (!userAgent.isEmpty())
3221         return userAgent;
3222     return m_userAgent;
3223 }
3224
3225 void WebPage::setUserAgent(const String& userAgent)
3226 {
3227     if (m_userAgent == userAgent)
3228         return;
3229
3230     m_userAgent = userAgent;
3231
3232     if (m_page)
3233         m_page->userAgentChanged();
3234 }
3235
3236 void WebPage::suspendActiveDOMObjectsAndAnimations()
3237 {
3238     m_page->suspendActiveDOMObjectsAndAnimations();
3239 }
3240
3241 void WebPage::resumeActiveDOMObjectsAndAnimations()
3242 {
3243     m_page->resumeActiveDOMObjectsAndAnimations();
3244 }
3245
3246 IntPoint WebPage::screenToRootView(const IntPoint& point)
3247 {
3248     IntPoint windowPoint;
3249     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
3250     return windowPoint;
3251 }
3252     
3253 IntRect WebPage::rootViewToScreen(const IntRect& rect)
3254 {
3255     IntRect screenRect;
3256     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
3257     return screenRect;
3258 }
3259     
3260 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
3261 {
3262     IntPoint windowPoint;
3263     sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
3264     return windowPoint;
3265 }
3266
3267 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
3268 {
3269     IntRect screenRect;
3270     sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
3271     return screenRect;
3272 }
3273
3274 KeyboardUIMode WebPage::keyboardUIMode()
3275 {
3276     bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
3277     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
3278 }
3279
3280 void WebPage::runJavaScript(const String& script, bool forceUserGesture, Optional<String> worldName, CallbackID callbackID)
3281 {
3282     // NOTE: We need to be careful when running scripts that the objects we depend on don't
3283     // disappear during script execution.
3284
3285     RefPtr<SerializedScriptValue> serializedResultValue;
3286     JSLockHolder lock(commonVM());
3287     bool hadException = true;
3288     ExceptionDetails details;
3289     auto* world = worldName ? InjectedBundleScriptWorld::find(worldName.value()) : &InjectedBundleScriptWorld::normalWorld();
3290     if (world) {
3291         if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeUserAgentScriptInWorld(world->coreWorld(), script, forceUserGesture, &details)) {
3292             hadException = false;
3293             serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContextForWorld(world),
3294                 toRef(m_mainFrame->coreFrame()->script().globalObject(world->coreWorld())->globalExec(), resultValue), nullptr);
3295         }
3296     }
3297
3298     IPC::DataReference dataReference;
3299     if (serializedResultValue)
3300         dataReference = serializedResultValue->data();
3301     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
3302 }
3303
3304 void WebPage::runJavaScriptInMainFrame(const String& script, bool forceUserGesture, CallbackID callbackID)
3305 {
3306     runJavaScript(script, forceUserGesture, WTF::nullopt, callbackID);
3307 }
3308
3309 void WebPage::runJavaScriptInMainFrameScriptWorld(const String& script, bool forceUserGesture, const String& worldName, CallbackID callbackID)
3310 {
3311     runJavaScript(script, forceUserGesture, worldName, callbackID);
3312 }
3313
3314 void WebPage::getContentsAsString(CallbackID callbackID)
3315 {
3316     String resultString = m_mainFrame->contentsAsString();
3317     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3318 }
3319
3320 #if ENABLE(MHTML)
3321 void WebPage::getContentsAsMHTMLData(CallbackID callbackID)
3322 {
3323     send(Messages::WebPageProxy::DataCallback({ MHTMLArchive::generateMHTMLData(m_page.get()) }, callbackID));
3324 }
3325 #endif
3326
3327 void WebPage::getRenderTreeExternalRepresentation(CallbackID callbackID)
3328 {
3329     String resultString = renderTreeExternalRepresentation();
3330     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3331 }
3332
3333 static Frame* frameWithSelection(Page* page)
3334 {
3335     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3336         if (frame->selection().isRange())
3337             return frame;
3338     }
3339
3340     return 0;
3341 }
3342
3343 void WebPage::getSelectionAsWebArchiveData(CallbackID callbackID)
3344 {
3345 #if PLATFORM(COCOA)
3346     RetainPtr<CFDataRef> data;
3347     if (Frame* frame = frameWithSelection(m_page.get()))
3348         data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
3349 #endif
3350
3351     IPC::SharedBufferDataReference dataReference;
3352 #if PLATFORM(COCOA)
3353     if (data)
3354         dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3355 #endif
3356     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3357 }
3358
3359 void WebPage::getSelectionOrContentsAsString(CallbackID callbackID)
3360 {
3361     WebFrame* focusedOrMainFrame = WebFrame::fromCoreFrame(m_page->focusController().focusedOrMainFrame());
3362     String resultString = focusedOrMainFrame->selectionAsString();
3363     if (resultString.isEmpty())
3364         resultString = focusedOrMainFrame->contentsAsString();
3365     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3366 }
3367
3368 void WebPage::getSourceForFrame(uint64_t frameID, CallbackID callbackID)
3369 {
3370     String resultString;
3371     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3372        resultString = frame->source();
3373
3374     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
3375 }
3376
3377 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, CallbackID callbackID)
3378 {
3379     RefPtr<SharedBuffer> buffer;
3380     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3381         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3382             buffer = pluginView->liveResourceData();
3383         if (!buffer) {
3384             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
3385                 buffer = loader->mainResourceData();
3386         }
3387     }
3388
3389     IPC::SharedBufferDataReference dataReference;
3390     if (buffer)
3391         dataReference = { *buffer };
3392     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3393 }
3394
3395 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3396 {
3397     DocumentLoader* loader = frame->loader().documentLoader();
3398     if (!loader)
3399         return nullptr;
3400
3401     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
3402     if (!subresource)
3403         return nullptr;
3404
3405     return &subresource->data();
3406 }
3407
3408 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, CallbackID callbackID)
3409 {
3410     RefPtr<SharedBuffer> buffer;
3411     if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3412         URL resourceURL(URL(), resourceURLString);
3413         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3414     }
3415
3416     IPC::SharedBufferDataReference dataReference;
3417     if (buffer)
3418         dataReference = { *buffer };
3419     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3420 }
3421
3422 void WebPage::getWebArchiveOfFrame(uint64_t frameID, CallbackID callbackID)
3423 {
3424 #if PLATFORM(COCOA)
3425     RetainPtr<CFDataRef> data;
3426     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
3427         data = frame->webArchiveData(nullptr, nullptr);
3428 #else
3429     UNUSED_PARAM(frameID);
3430 #endif
3431
3432     IPC::SharedBufferDataReference dataReference;
3433 #if PLATFORM(COCOA)
3434     if (data)
3435         dataReference = { CFDataGetBytePtr(data.get()), static_cast<size_t>(CFDataGetLength(data.get())) };
3436 #endif
3437     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
3438 }
3439
3440 void WebPage::forceRepaintWithoutCallback()
3441 {
3442     m_drawingArea->forceRepaint();
3443 }
3444
3445 void WebPage::forceRepaint(CallbackID callbackID)
3446 {
3447     if (m_drawingArea->forceRepaintAsync(callbackID))
3448         return;
3449
3450     forceRepaintWithoutCallback();
3451     send(Messages::WebPageProxy::VoidCallback(callbackID));
3452 }
3453
3454 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
3455 {
3456     WebPreferencesStore::removeTestRunnerOverrides();
3457     updatePreferences(store);
3458 }
3459
3460 void WebPage::updatePreferences(const WebPreferencesStore& store)
3461 {
3462     updatePreferencesGenerated(store);
3463
3464     Settings& settings = m_page->settings();
3465
3466 #if !PLATFORM(GTK)
3467     if (!settings.acceleratedCompositingEnabled()) {
3468         RELEASE_LOG_IF_ALLOWED("%p - WebPage - acceleratedCompositingEnabled setting was false. WebKit cannot function in this mode; changing setting to true", this);
3469         settings.setAcceleratedCompositingEnabled(true);
3470     }
3471 #endif
3472
3473     bool requiresUserGestureForMedia = store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey());
3474     settings.setVideoPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForVideoPlaybackKey()));
3475     settings.setAudioPlaybackRequiresUserGesture(requiresUserGestureForMedia || store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey()));
3476     settings.setLayoutInterval(Seconds(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())));
3477     settings.setUserInterfaceDirectionPolicy(static_cast<WebCore::UserInterfaceDirectionPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::userInterfaceDirectionPolicyKey())));
3478     settings.setSystemLayoutDirection(static_cast<TextDirection>(store.getUInt32ValueForKey(WebPreferencesKey::systemLayoutDirectionKey())));
3479     settings.setJavaScriptRuntimeFlags(static_cast<RuntimeFlags>(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
3480     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
3481     settings.setFrameFlattening(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()) ? WebCore::FrameFlattening::FullyEnabled : WebCore::FrameFlattening::Disabled);
3482     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
3483 #if ENABLE(DATA_DETECTION)
3484     settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey())));
3485 #endif
3486
3487     DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
3488
3489     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
3490     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
3491     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
3492     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
3493
3494     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
3495     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
3496
3497     if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
3498         setSessionID(PAL::SessionID::legacyPrivateSessionID());
3499     else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == PAL::SessionID::legacyPrivateSessionID())
3500         setSessionID(PAL::SessionID::defaultSessionID());
3501
3502     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
3503     if (m_processSuppressionEnabled != processSuppressionEnabled) {
3504         m_processSuppressionEnabled = processSuppressionEnabled;
3505         updateThrottleState();
3506     }
3507
3508 #if PLATFORM(COCOA)
3509     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
3510 #endif
3511 #if ENABLE(PAYMENT_REQUEST)
3512     settings.setPaymentRequestEnabled(store.getBoolValueForKey(WebPreferencesKey::applePayEnabledKey()));
3513 #endif
3514
3515     // FIXME: This is both a RuntimeEnabledFeatures (generated) and a setting. It should pick one.
3516     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
3517
3518 #if PLATFORM(IOS_FAMILY)
3519     m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey());
3520     m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints);
3521     setForceAlwaysUserScalable(m_forceAlwaysUserScalable || store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
3522
3523     settings.setUseImageDocumentForSubframePDF(true);
3524 #if HAVE(AVKIT)
3525     DeprecatedGlobalSettings::setAVKitEnabled(true);
3526 #endif
3527 #endif
3528
3529 #if ENABLE(SERVICE_WORKER)
3530     if (store.getBoolValueForKey(WebPreferencesKey::serviceWorkersEnabledKey())) {
3531         ASSERT(parentProcessHasServiceWorkerEntitlement());
3532         if (!parentProcessHasServiceWorkerEntitlement())
3533             RuntimeEnabledFeatures::sharedFeatures().setServiceWorkerEnabled(false);
3534     }
3535 #endif
3536
3537     settings.setLayoutViewportHeightExpansionFactor(store.getDoubleValueForKey(WebPreferencesKey::layoutViewportHeightExpansionFactorKey()));
3538
3539     if (m_drawingArea)
3540         m_drawingArea->updatePreferences(store);