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