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