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