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