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