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