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