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