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