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