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