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