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