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