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