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