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