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