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