Add runtime and compile time flags for enabling Web Animations API and model.
[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     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1345     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1346         if (pluginView->handlesPageScaleFactor())
1347             return pluginView->pageScaleFactor();
1348         return pageScaleFactor();
1349     }
1350
1351     Frame* frame = m_mainFrame->coreFrame();
1352     if (!frame)
1353         return 1;
1354     return frame->textZoomFactor();
1355 }
1356
1357 void WebPage::setTextZoomFactor(double zoomFactor)
1358 {
1359     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1360     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1361         if (pluginView->handlesPageScaleFactor())
1362             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1363         else
1364             scalePage(zoomFactor, IntPoint());
1365         return;
1366     }
1367
1368     Frame* frame = m_mainFrame->coreFrame();
1369     if (!frame)
1370         return;
1371     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1372 }
1373
1374 double WebPage::pageZoomFactor() const
1375 {
1376     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1377     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1378         if (pluginView->handlesPageScaleFactor())
1379             return pluginView->pageScaleFactor();
1380         return pageScaleFactor();
1381     }
1382
1383     Frame* frame = m_mainFrame->coreFrame();
1384     if (!frame)
1385         return 1;
1386     return frame->pageZoomFactor();
1387 }
1388
1389 void WebPage::setPageZoomFactor(double zoomFactor)
1390 {
1391     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1392     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1393         if (pluginView->handlesPageScaleFactor())
1394             pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1395         else
1396             scalePage(zoomFactor, IntPoint());
1397         return;
1398     }
1399
1400     Frame* frame = m_mainFrame->coreFrame();
1401     if (!frame)
1402         return;
1403     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1404 }
1405
1406 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1407 {
1408     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1409     if (pluginView && pluginView->requiresUnifiedScaleFactor()) {
1410         if (pluginView->handlesPageScaleFactor())
1411             pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1412         else
1413             scalePage(pageZoomFactor, IntPoint());
1414         return;
1415     }
1416
1417     Frame* frame = m_mainFrame->coreFrame();
1418     if (!frame)
1419         return;
1420     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1421 }
1422
1423 void WebPage::windowScreenDidChange(uint32_t displayID)
1424 {
1425     m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1426 }
1427
1428 void WebPage::scalePage(double scale, const IntPoint& origin)
1429 {
1430     double totalScale = scale * viewScaleFactor();
1431     bool willChangeScaleFactor = totalScale != totalScaleFactor();
1432
1433 #if PLATFORM(IOS)
1434     if (willChangeScaleFactor) {
1435         if (!m_inDynamicSizeUpdate)
1436             m_dynamicSizeUpdateHistory.clear();
1437         m_scaleWasSetByUIProcess = false;
1438     }
1439 #endif
1440     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1441     if (pluginView && pluginView->handlesPageScaleFactor()) {
1442         // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale.
1443         // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does.
1444         if (m_page->pageScaleFactor() != 1) {
1445             m_page->setPageScaleFactor(1, origin);
1446             for (auto* pluginView : m_pluginViews)
1447                 pluginView->pageScaleFactorDidChange();
1448         }
1449
1450         pluginView->setPageScaleFactor(totalScale, origin);
1451         return;
1452     }
1453
1454     m_page->setPageScaleFactor(totalScale, origin);
1455
1456     // We can't early return before setPageScaleFactor because the origin might be different.
1457     if (!willChangeScaleFactor)
1458         return;
1459
1460     for (auto* pluginView : m_pluginViews)
1461         pluginView->pageScaleFactorDidChange();
1462
1463     if (m_drawingArea->layerTreeHost())
1464         m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1465
1466     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1467 }
1468
1469 void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates)
1470 {
1471     double totalScale = scale * viewScaleFactor();
1472     if (totalScale == totalScaleFactor())
1473         return;
1474
1475     IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates);
1476     double scaleRatio = scale / pageScaleFactor();
1477     scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1478     scalePage(scale, scrollPositionAtNewScale);
1479 }
1480
1481 double WebPage::totalScaleFactor() const
1482 {
1483     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1484     if (pluginView && pluginView->handlesPageScaleFactor())
1485         return pluginView->pageScaleFactor();
1486
1487     return m_page->pageScaleFactor();
1488 }
1489
1490 double WebPage::pageScaleFactor() const
1491 {
1492     return totalScaleFactor() / viewScaleFactor();
1493 }
1494
1495 double WebPage::viewScaleFactor() const
1496 {
1497     return m_page->viewScaleFactor();
1498 }
1499
1500 void WebPage::scaleView(double scale)
1501 {
1502     if (viewScaleFactor() == scale)
1503         return;
1504
1505     float pageScale = pageScaleFactor();
1506
1507     IntPoint scrollPositionAtNewScale;
1508     if (FrameView* mainFrameView = m_page->mainFrame().view()) {
1509         double scaleRatio = scale / viewScaleFactor();
1510         scrollPositionAtNewScale = mainFrameView->scrollPosition();
1511         scrollPositionAtNewScale.scale(scaleRatio, scaleRatio);
1512     }
1513
1514     m_page->setViewScaleFactor(scale);
1515     scalePage(pageScale, scrollPositionAtNewScale);
1516 }
1517
1518 void WebPage::setDeviceScaleFactor(float scaleFactor)
1519 {
1520     if (scaleFactor == m_page->deviceScaleFactor())
1521         return;
1522
1523     m_page->setDeviceScaleFactor(scaleFactor);
1524
1525     // Tell all our plug-in views that the device scale factor changed.
1526 #if PLATFORM(MAC)
1527     for (auto* pluginView : m_pluginViews)
1528         pluginView->setDeviceScaleFactor(scaleFactor);
1529
1530     updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1531 #endif
1532
1533     if (m_findController.isShowingOverlay()) {
1534         // We must have updated layout to get the selection rects right.
1535         layoutIfNeeded();
1536         m_findController.deviceScaleFactorDidChange();
1537     }
1538
1539     if (m_drawingArea->layerTreeHost())
1540         m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1541 }
1542
1543 float WebPage::deviceScaleFactor() const
1544 {
1545     return m_page->deviceScaleFactor();
1546 }
1547
1548 void WebPage::setUseFixedLayout(bool fixed)
1549 {
1550     // Do not overwrite current settings if initially setting it to false.
1551     if (m_useFixedLayout == fixed)
1552         return;
1553     m_useFixedLayout = fixed;
1554
1555 #if !PLATFORM(IOS)
1556     m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1557 #endif
1558 #if USE(COORDINATED_GRAPHICS)
1559     m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1560     m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1561     m_page->settings().setDelegatesPageScaling(fixed);
1562     m_page->settings().setScrollingCoordinatorEnabled(fixed);
1563 #endif
1564
1565 #if USE(COORDINATED_GRAPHICS) && ENABLE(SMOOTH_SCROLLING)
1566     // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1567     // Ensure we don't do animated scrolling in the WebProcess in that case.
1568     m_page->settings().setScrollAnimatorEnabled(!fixed);
1569 #endif
1570
1571     FrameView* view = mainFrameView();
1572     if (!view)
1573         return;
1574
1575 #if USE(COORDINATED_GRAPHICS)
1576     view->setDelegatesScrolling(fixed);
1577     view->setPaintsEntireContents(fixed);
1578 #endif
1579     view->setUseFixedLayout(fixed);
1580     if (!fixed)
1581         setFixedLayoutSize(IntSize());
1582
1583     send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed));
1584 }
1585
1586 void WebPage::setFixedLayoutSize(const IntSize& size)
1587 {
1588     FrameView* view = mainFrameView();
1589     if (!view || view->fixedLayoutSize() == size)
1590         return;
1591
1592     view->setFixedLayoutSize(size);
1593
1594     send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size));
1595 }
1596
1597 IntSize WebPage::fixedLayoutSize() const
1598 {
1599     FrameView* view = mainFrameView();
1600     if (!view)
1601         return IntSize();
1602     return view->fixedLayoutSize();
1603 }
1604
1605 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1606 {
1607     if (!m_page)
1608         return;
1609     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1610 }
1611
1612 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1613 {
1614     m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1615 }
1616     
1617 void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
1618 {
1619     m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1620 }
1621     
1622 void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
1623 {
1624     m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone);
1625 }
1626
1627 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1628 {
1629     if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1630         m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1631 }
1632
1633 void WebPage::setPaginationMode(uint32_t mode)
1634 {
1635     Pagination pagination = m_page->pagination();
1636     pagination.mode = static_cast<Pagination::Mode>(mode);
1637     m_page->setPagination(pagination);
1638 }
1639
1640 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1641 {
1642     Pagination pagination = m_page->pagination();
1643     pagination.behavesLikeColumns = behavesLikeColumns;
1644     m_page->setPagination(pagination);
1645 }
1646
1647 void WebPage::setPageLength(double pageLength)
1648 {
1649     Pagination pagination = m_page->pagination();
1650     pagination.pageLength = pageLength;
1651     m_page->setPagination(pagination);
1652 }
1653
1654 void WebPage::setGapBetweenPages(double gap)
1655 {
1656     Pagination pagination = m_page->pagination();
1657     pagination.gap = gap;
1658     m_page->setPagination(pagination);
1659 }
1660
1661 void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData)
1662 {
1663     auto& webProcess = WebProcess::singleton();
1664     InjectedBundle* injectedBundle = webProcess.injectedBundle();
1665     if (!injectedBundle)
1666         return;
1667
1668     injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get());
1669 }
1670
1671 #if !PLATFORM(IOS)
1672 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1673 {
1674     if (m_headerBanner)
1675         m_headerBanner->detachFromPage();
1676
1677     m_headerBanner = pageBanner;
1678
1679     if (m_headerBanner)
1680         m_headerBanner->addToPage(PageBanner::Header, this);
1681 }
1682
1683 PageBanner* WebPage::headerPageBanner()
1684 {
1685     return m_headerBanner.get();
1686 }
1687
1688 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1689 {
1690     if (m_footerBanner)
1691         m_footerBanner->detachFromPage();
1692
1693     m_footerBanner = pageBanner;
1694
1695     if (m_footerBanner)
1696         m_footerBanner->addToPage(PageBanner::Footer, this);
1697 }
1698
1699 PageBanner* WebPage::footerPageBanner()
1700 {
1701     return m_footerBanner.get();
1702 }
1703
1704 void WebPage::hidePageBanners()
1705 {
1706     if (m_headerBanner)
1707         m_headerBanner->hide();
1708     if (m_footerBanner)
1709         m_footerBanner->hide();
1710 }
1711
1712 void WebPage::showPageBanners()
1713 {
1714     if (m_headerBanner)
1715         m_headerBanner->showIfHidden();
1716     if (m_footerBanner)
1717         m_footerBanner->showIfHidden();
1718 }
1719 #endif // !PLATFORM(IOS)
1720
1721 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1722 {
1723     SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1724     snapshotOptions |= SnapshotOptionsShareable;
1725
1726     RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1727
1728     ShareableBitmap::Handle handle;
1729     if (image)
1730         image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly);
1731
1732     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1733 }
1734
1735 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options)
1736 {
1737     IntRect snapshotRect = rect;
1738     IntSize bitmapSize = snapshotRect.size();
1739     if (options & SnapshotOptionsPrinting) {
1740         ASSERT(additionalScaleFactor == 1);
1741         Frame* coreFrame = m_mainFrame->coreFrame();
1742         if (!coreFrame)
1743             return nullptr;
1744         bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1);
1745     } else {
1746         double scaleFactor = additionalScaleFactor;
1747         if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1748             scaleFactor *= corePage()->deviceScaleFactor();
1749         bitmapSize.scale(scaleFactor);
1750     }
1751
1752     return snapshotAtSize(rect, bitmapSize, options);
1753 }
1754
1755 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1756 {
1757     Frame* coreFrame = m_mainFrame->coreFrame();
1758     if (!coreFrame)
1759         return nullptr;
1760
1761     FrameView* frameView = coreFrame->view();
1762     if (!frameView)
1763         return nullptr;
1764
1765     IntRect snapshotRect = rect;
1766     float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1767     float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1768     float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor);
1769
1770     RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1771     if (!snapshot->bitmap())
1772         return nullptr;
1773
1774     auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1775
1776     if (options & SnapshotOptionsPrinting) {
1777         PrintContext::spoolAllPagesWithBoundaries(*coreFrame, *graphicsContext, snapshotRect.size());
1778         return snapshot.release();
1779     }
1780
1781     Color documentBackgroundColor = frameView->documentBackgroundColor();
1782     Color backgroundColor = (coreFrame->settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView->baseBackgroundColor();
1783     graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor, ColorSpaceDeviceRGB);
1784
1785     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1786         double deviceScaleFactor = corePage()->deviceScaleFactor();
1787         graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1788         scaleFactor /= deviceScaleFactor;
1789     }
1790
1791     graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1792     graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1793
1794     FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1795     if (options & SnapshotOptionsExcludeSelectionHighlighting)
1796         shouldPaintSelection = FrameView::ExcludeSelection;
1797
1798     FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1799     if (options & SnapshotOptionsInViewCoordinates)
1800         coordinateSpace = FrameView::ViewCoordinates;
1801
1802     frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace);
1803
1804     if (options & SnapshotOptionsPaintSelectionRectangle) {
1805         FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1806         graphicsContext->setStrokeColor(Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
1807         graphicsContext->strokeRect(selectionRectangle, 1);
1808     }
1809     
1810     return snapshot.release();
1811 }
1812
1813 PassRefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount)
1814 {
1815     Frame* coreFrame = m_mainFrame->coreFrame();
1816     if (!coreFrame)
1817         return nullptr;
1818
1819     FrameView* frameView = coreFrame->view();
1820     if (!frameView)
1821         return nullptr;
1822
1823     if (!node.renderer())
1824         return nullptr;
1825
1826     LayoutRect topLevelRect;
1827     IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect));
1828     if (snapshotRect.isEmpty())
1829         return nullptr;
1830
1831     double scaleFactor = 1;
1832     IntSize snapshotSize = snapshotRect.size();
1833     unsigned maximumHeight = maximumPixelCount / snapshotSize.width();
1834     if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) {
1835         scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height();
1836         snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight);
1837     }
1838
1839     RefPtr<WebImage> snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options));
1840     if (!snapshot->bitmap())
1841         return nullptr;
1842
1843     auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1844
1845     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) {
1846         double deviceScaleFactor = corePage()->deviceScaleFactor();
1847         graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1848         scaleFactor /= deviceScaleFactor;
1849     }
1850
1851     graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1852     graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1853
1854     Color savedBackgroundColor = frameView->baseBackgroundColor();
1855     frameView->setBaseBackgroundColor(Color::transparent);
1856     frameView->setNodeToDraw(&node);
1857
1858     frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates);
1859
1860     frameView->setBaseBackgroundColor(savedBackgroundColor);
1861     frameView->setNodeToDraw(nullptr);
1862
1863     return snapshot.release();
1864 }
1865
1866 void WebPage::pageDidScroll()
1867 {
1868 #if PLATFORM(IOS)
1869     if (!m_inDynamicSizeUpdate)
1870         m_dynamicSizeUpdateHistory.clear();
1871 #endif
1872     m_uiClient->pageDidScroll(this);
1873
1874     m_pageScrolledHysteresis.impulse();
1875
1876     send(Messages::WebPageProxy::PageDidScroll());
1877 }
1878
1879 void WebPage::pageStoppedScrolling()
1880 {
1881     // Maintain the current history item's scroll position up-to-date.
1882     if (Frame* frame = m_mainFrame->coreFrame())
1883         frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem());
1884 }
1885
1886 #if USE(COORDINATED_GRAPHICS)
1887 void WebPage::pageDidRequestScroll(const IntPoint& point)
1888 {
1889 #if USE(COORDINATED_GRAPHICS_THREADED)
1890     drawingArea()->scroll(IntRect(point, IntSize()), IntSize());
1891 #elif USE(COORDINATED_GRAPHICS_MULTIPROCESS)
1892     send(Messages::WebPageProxy::PageDidRequestScroll(point));
1893 #endif
1894 }
1895 #endif
1896
1897 #if ENABLE(CONTEXT_MENUS)
1898 WebContextMenu* WebPage::contextMenu()
1899 {
1900     if (!m_contextMenu)
1901         m_contextMenu = WebContextMenu::create(this);
1902     return m_contextMenu.get();
1903 }
1904
1905 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1906 {
1907     corePage()->contextMenuController().clearContextMenu();
1908     
1909     // Simulate a mouse click to generate the correct menu.
1910     PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick);
1911     bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
1912     if (!handled)
1913         return 0;
1914
1915     return contextMenu();
1916 }
1917 #endif
1918
1919 // Events 
1920
1921 static const WebEvent* g_currentEvent = 0;
1922
1923 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1924 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1925 // platform events passed to the event handler code.
1926 const WebEvent* WebPage::currentEvent()
1927 {
1928     return g_currentEvent;
1929 }
1930
1931 void WebPage::setLayerTreeStateIsFrozen(bool frozen)
1932 {
1933     auto* drawingArea = this->drawingArea();
1934     if (!drawingArea)
1935         return;
1936
1937     drawingArea->setLayerTreeStateIsFrozen(frozen);
1938 }
1939
1940 bool WebPage::markLayersVolatileImmediatelyIfPossible()
1941 {
1942     auto* drawingArea = this->drawingArea();
1943     if (!drawingArea)
1944         return true;
1945
1946     return drawingArea->markLayersVolatileImmediatelyIfPossible();
1947 }
1948
1949 class CurrentEvent {
1950 public:
1951     explicit CurrentEvent(const WebEvent& event)
1952         : m_previousCurrentEvent(g_currentEvent)
1953     {
1954         g_currentEvent = &event;
1955     }
1956
1957     ~CurrentEvent()
1958     {
1959         g_currentEvent = m_previousCurrentEvent;
1960     }
1961
1962 private:
1963     const WebEvent* m_previousCurrentEvent;
1964 };
1965
1966 #if ENABLE(CONTEXT_MENUS)
1967 static bool isContextClick(const PlatformMouseEvent& event)
1968 {
1969 #if PLATFORM(COCOA)
1970     return WebEventFactory::shouldBeHandledAsContextClick(event);
1971 #else
1972     return event.button() == WebCore::RightButton;
1973 #endif
1974 }
1975
1976 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1977 {
1978     IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
1979     HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
1980
1981     Frame* frame = &page->corePage()->mainFrame();
1982     if (result.innerNonSharedNode())
1983         frame = result.innerNonSharedNode()->document().frame();
1984
1985     bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
1986     if (handled)
1987         page->contextMenu()->show();
1988
1989     return handled;
1990 }
1991 #endif
1992
1993 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1994 {
1995     Frame& frame = page->corePage()->mainFrame();
1996     if (!frame.view())
1997         return false;
1998
1999     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
2000
2001     switch (platformMouseEvent.type()) {
2002         case PlatformEvent::MousePressed: {
2003 #if ENABLE(CONTEXT_MENUS)
2004             if (isContextClick(platformMouseEvent))
2005                 page->corePage()->contextMenuController().clearContextMenu();
2006 #endif
2007
2008             bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
2009 #if ENABLE(CONTEXT_MENUS)
2010             if (isContextClick(platformMouseEvent))
2011                 handled = handleContextMenuEvent(platformMouseEvent, page);
2012 #endif
2013             return handled;
2014         }
2015         case PlatformEvent::MouseReleased:
2016             return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
2017
2018         case PlatformEvent::MouseMoved:
2019             if (onlyUpdateScrollbars)
2020                 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
2021             return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
2022
2023         case PlatformEvent::MouseForceChanged:
2024         case PlatformEvent::MouseForceDown:
2025         case PlatformEvent::MouseForceUp:
2026             return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent);
2027
2028         default:
2029             ASSERT_NOT_REACHED();
2030             return false;
2031     }
2032 }
2033
2034 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
2035 {
2036     m_page->pageThrottler().didReceiveUserInput();
2037
2038     bool shouldHandleEvent = true;
2039
2040 #if ENABLE(CONTEXT_MENUS)
2041     // Don't try to handle any pending mouse events if a context menu is showing.
2042     if (m_isShowingContextMenu)
2043         shouldHandleEvent = false;
2044 #endif
2045 #if ENABLE(DRAG_SUPPORT)
2046     if (m_isStartingDrag)
2047         shouldHandleEvent = false;
2048 #endif
2049
2050     if (!shouldHandleEvent) {
2051         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
2052         return;
2053     }
2054
2055     bool handled = false;
2056
2057 #if !PLATFORM(IOS)
2058     if (!handled && m_headerBanner)
2059         handled = m_headerBanner->mouseEvent(mouseEvent);
2060     if (!handled && m_footerBanner)
2061         handled = m_footerBanner->mouseEvent(mouseEvent);
2062 #endif // !PLATFORM(IOS)
2063
2064     if (!handled && canHandleUserEvents()) {
2065         CurrentEvent currentEvent(mouseEvent);
2066
2067         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
2068         // button is currently pressed. It is possible that neither of those things will be true since on
2069         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
2070         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
2071         // efficient scrollbars-only version of the event.
2072         bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
2073         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
2074     }
2075
2076     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
2077 }
2078
2079 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
2080 {
2081     Frame& frame = page->mainFrame();
2082     if (!frame.view())
2083         return false;
2084
2085     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
2086     return page->userInputBridge().handleWheelEvent(platformWheelEvent);
2087 }
2088
2089 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
2090 {
2091     m_page->pageThrottler().didReceiveUserInput();
2092
2093     bool handled = false;
2094
2095     if (canHandleUserEvents()) {
2096         CurrentEvent currentEvent(wheelEvent);
2097
2098         handled = handleWheelEvent(wheelEvent, m_page.get());
2099     }
2100     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
2101 }
2102
2103 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
2104 {
2105     if (!page->mainFrame().view())
2106         return false;
2107
2108     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
2109         return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
2110     return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
2111 }
2112
2113 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
2114 {
2115     m_page->pageThrottler().didReceiveUserInput();
2116
2117     bool handled = false;
2118
2119     if (canHandleUserEvents()) {
2120         CurrentEvent currentEvent(keyboardEvent);
2121
2122         handled = handleKeyEvent(keyboardEvent, m_page.get());
2123         // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
2124         if (!handled)
2125             handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
2126     }
2127     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
2128 }
2129
2130 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
2131 {
2132     bool isEnabled = false;
2133     int32_t state = 0;
2134     Frame& frame = m_page->focusController().focusedOrMainFrame();
2135     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
2136         isEnabled = pluginView->isEditingCommandEnabled(commandName);
2137     else {
2138         Editor::Command command = frame.editor().command(commandName);
2139         state = command.state();
2140         isEnabled = command.isSupported() && command.isEnabled();
2141     }
2142
2143     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
2144 }
2145
2146 void WebPage::executeEditCommand(const String& commandName, const String& argument)
2147 {
2148     executeEditingCommand(commandName, argument);
2149 }
2150
2151 void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates)
2152 {
2153     for (const auto& itemState : itemStates)
2154         WebBackForwardListProxy::addItemFromUIProcess(itemState.identifier, toHistoryItem(itemState.pageState), m_pageID);
2155 }
2156
2157 #if ENABLE(TOUCH_EVENTS)
2158 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
2159 {
2160     if (!page->mainFrame().view())
2161         return false;
2162
2163     return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
2164 }
2165 #endif
2166
2167 #if ENABLE(IOS_TOUCH_EVENTS)
2168 void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled)
2169 {
2170     m_userIsInteracting = true;
2171
2172     m_lastInteractionLocation = touchEvent.position();
2173     CurrentEvent currentEvent(touchEvent);
2174     handled = handleTouchEvent(touchEvent, m_page.get());
2175
2176     m_userIsInteracting = false;
2177 }
2178
2179 void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled)
2180 {
2181     EventDispatcher::TouchEventQueue queuedEvents;
2182     WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents);
2183     dispatchAsynchronousTouchEvents(queuedEvents);
2184
2185     dispatchTouchEvent(touchEvent, handled);
2186 }
2187 #elif ENABLE(TOUCH_EVENTS)
2188 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
2189 {
2190
2191     bool handled = false;
2192     if (canHandleUserEvents()) {
2193         CurrentEvent currentEvent(touchEvent);
2194
2195         handled = handleTouchEvent(touchEvent, m_page.get());
2196     }
2197     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
2198 }
2199 #endif
2200
2201 #if ENABLE(MAC_GESTURE_EVENTS)
2202 static bool handleGestureEvent(const WebGestureEvent& event, Page* page)
2203 {
2204     if (!page->mainFrame().view())
2205         return false;
2206
2207     return page->mainFrame().eventHandler().handleGestureEvent(platform(event));
2208 }
2209
2210 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
2211 {
2212     bool handled = false;
2213     if (canHandleUserEvents()) {
2214         CurrentEvent currentEvent(gestureEvent);
2215         handled = handleGestureEvent(gestureEvent, m_page.get());
2216     }
2217     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
2218 }
2219
2220 #endif
2221
2222 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
2223 {
2224     return page->userInputBridge().scrollRecursively(direction, granularity);
2225 }
2226
2227 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
2228 {
2229     return page->userInputBridge().logicalScrollRecursively(direction, granularity);
2230 }
2231
2232 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
2233 {
2234     return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
2235 }
2236
2237 void WebPage::centerSelectionInVisibleArea()
2238 {
2239     Frame& frame = m_page->focusController().focusedOrMainFrame();
2240     frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
2241     m_findController.showFindIndicatorInSelection();
2242 }
2243
2244 #if ENABLE(REMOTE_INSPECTOR)
2245 void WebPage::setAllowsRemoteInspection(bool allow)
2246 {
2247     m_page->setRemoteInspectionAllowed(allow);
2248 }
2249 #endif
2250
2251 void WebPage::setDrawsBackground(bool drawsBackground)
2252 {
2253     if (m_drawsBackground == drawsBackground)
2254         return;
2255
2256     m_drawsBackground = drawsBackground;
2257
2258     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2259         if (FrameView* view = coreFrame->view())
2260             view->setTransparent(!drawsBackground);
2261     }
2262
2263     m_drawingArea->pageBackgroundTransparencyChanged();
2264     m_drawingArea->setNeedsDisplay();
2265 }
2266
2267 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
2268 {
2269     if (m_drawsTransparentBackground == drawsTransparentBackground)
2270         return;
2271
2272     m_drawsTransparentBackground = drawsTransparentBackground;
2273
2274     Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2275     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2276         if (FrameView* view = coreFrame->view())
2277             view->setBaseBackgroundColor(backgroundColor);
2278     }
2279
2280     m_drawingArea->pageBackgroundTransparencyChanged();
2281     m_drawingArea->setNeedsDisplay();
2282 }
2283
2284 void WebPage::setTopContentInset(float contentInset)
2285 {
2286     if (contentInset == m_page->topContentInset())
2287         return;
2288
2289     m_page->setTopContentInset(contentInset);
2290
2291     for (auto* pluginView : m_pluginViews)
2292         pluginView->topContentInsetDidChange();
2293 }
2294
2295 void WebPage::viewWillStartLiveResize()
2296 {
2297     if (!m_page)
2298         return;
2299
2300     // FIXME: This should propagate to all ScrollableAreas.
2301     Frame& frame = m_page->focusController().focusedOrMainFrame();
2302     if (FrameView* view = frame.view())
2303         view->willStartLiveResize();
2304 }
2305
2306 void WebPage::viewWillEndLiveResize()
2307 {
2308     if (!m_page)
2309         return;
2310
2311     // FIXME: This should propagate to all ScrollableAreas.
2312     Frame& frame = m_page->focusController().focusedOrMainFrame();
2313     if (FrameView* view = frame.view())
2314         view->willEndLiveResize();
2315 }
2316
2317 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, uint64_t callbackID)
2318 {
2319     if (!m_page)
2320         return;
2321
2322 #if PLATFORM(IOS)
2323     TemporaryChange<bool> userIsInteractingChange { m_userIsInteracting, true };
2324 #endif
2325
2326     Frame& frame = m_page->focusController().focusedOrMainFrame();
2327     frame.document()->setFocusedElement(0);
2328
2329     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2330         PlatformKeyboardEvent platformEvent(platform(event));
2331         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2332         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2333
2334         send(Messages::WebPageProxy::VoidCallback(callbackID));
2335         return;
2336     }
2337
2338     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2339     send(Messages::WebPageProxy::VoidCallback(callbackID));
2340 }
2341
2342 void WebPage::setCanStartMediaTimerFired()
2343 {
2344     if (m_page)
2345         m_page->setCanStartMedia(true);
2346 }
2347
2348 inline bool WebPage::canHandleUserEvents() const
2349 {
2350 #if USE(COORDINATED_GRAPHICS)
2351     // Should apply only if the area was frozen by didStartPageTransition().
2352     return !m_drawingArea->layerTreeStateIsFrozen();
2353 #endif
2354     return true;
2355 }
2356
2357 void WebPage::updateIsInWindow(bool isInitialState)
2358 {
2359     bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2360
2361     if (!isInWindow) {
2362         m_setCanStartMediaTimer.stop();
2363         m_page->setCanStartMedia(false);
2364         
2365         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2366         if (!isInitialState)
2367             WebProcess::singleton().pageWillLeaveWindow(m_pageID);
2368     } else {
2369         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2370         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2371         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2372         if (m_mayStartMediaWhenInWindow)
2373             m_setCanStartMediaTimer.startOneShot(0);
2374
2375         WebProcess::singleton().pageDidEnterWindow(m_pageID);
2376     }
2377
2378     if (isInWindow)
2379         layoutIfNeeded();
2380 }
2381
2382 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState, const Vector<uint64_t>& callbackIDs)
2383 {
2384     ViewState::Flags changed = m_viewState ^ viewState;
2385     m_viewState = viewState;
2386
2387     if (changed)
2388         updateUserActivity();
2389
2390     m_page->setViewState(viewState);
2391     for (auto* pluginView : m_pluginViews)
2392         pluginView->viewStateDidChange(changed);
2393
2394     m_drawingArea->viewStateDidChange(changed, wantsDidUpdateViewState, callbackIDs);
2395
2396     if (changed & ViewState::IsInWindow)
2397         updateIsInWindow();
2398 }
2399
2400 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2401 {
2402     m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2403
2404     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2405
2406     for (auto* pluginView : m_pluginViews)
2407         pluginView->setLayerHostingMode(m_layerHostingMode);
2408 }
2409
2410 void WebPage::setSessionID(SessionID sessionID)
2411 {
2412     if (sessionID.isEphemeral())
2413         WebProcess::singleton().ensurePrivateBrowsingSession(sessionID);
2414     m_page->setSessionID(sessionID);
2415 }
2416
2417 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, uint64_t downloadID)
2418 {
2419     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
2420     if (!frame)
2421         return;
2422     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID);
2423 }
2424
2425 void WebPage::didStartPageTransition()
2426 {
2427     m_drawingArea->setLayerTreeStateIsFrozen(true);
2428 #if PLATFORM(IOS)
2429     m_hasFocusedDueToUserInteraction = false;
2430 #endif
2431 }
2432
2433 void WebPage::didCompletePageTransition()
2434 {
2435 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
2436     // m_mainFrame can be null since r170163.
2437     if (m_mainFrame && m_mainFrame->coreFrame()->view()->delegatesScrolling()) {
2438         // Wait until the UI process sent us the visible rect it wants rendered.
2439         send(Messages::WebPageProxy::PageTransitionViewportReady());
2440     } else
2441 #endif
2442         
2443     m_drawingArea->setLayerTreeStateIsFrozen(false);
2444 }
2445
2446 void WebPage::show()
2447 {
2448     send(Messages::WebPageProxy::ShowPage());
2449 }
2450
2451 String WebPage::userAgent(const URL& webCoreURL) const
2452 {
2453     return userAgent(nullptr, webCoreURL);
2454 }
2455
2456 String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const
2457 {
2458     if (frame && m_loaderClient.client().userAgentForURL) {
2459         API::String* apiString = m_loaderClient.userAgentForURL(frame, API::URL::create(webcoreURL).ptr());
2460         if (apiString)
2461             return apiString->string();
2462     }
2463
2464     String userAgent = platformUserAgent(webcoreURL);
2465     if (!userAgent.isEmpty())
2466         return userAgent;
2467     return m_userAgent;
2468 }
2469     
2470 void WebPage::setUserAgent(const String& userAgent)
2471 {
2472     m_userAgent = userAgent;
2473 }
2474
2475 void WebPage::suspendActiveDOMObjectsAndAnimations()
2476 {
2477     m_page->suspendActiveDOMObjectsAndAnimations();
2478 }
2479
2480 void WebPage::resumeActiveDOMObjectsAndAnimations()
2481 {
2482     m_page->resumeActiveDOMObjectsAndAnimations();
2483 }
2484
2485 IntPoint WebPage::screenToRootView(const IntPoint& point)
2486 {
2487     IntPoint windowPoint;
2488     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2489     return windowPoint;
2490 }
2491     
2492 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2493 {
2494     IntRect screenRect;
2495     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2496     return screenRect;
2497 }
2498     
2499 #if PLATFORM(IOS)
2500 IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point)
2501 {
2502     IntPoint windowPoint;
2503     sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint));
2504     return windowPoint;
2505 }
2506
2507 IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect)
2508 {
2509     IntRect screenRect;
2510     sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect));
2511     return screenRect;
2512 }
2513 #endif
2514
2515 KeyboardUIMode WebPage::keyboardUIMode()
2516 {
2517     bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled();
2518     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2519 }
2520
2521 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2522 {
2523     // NOTE: We need to be careful when running scripts that the objects we depend on don't
2524     // disappear during script execution.
2525
2526     RefPtr<SerializedScriptValue> serializedResultValue;
2527     JSLockHolder lock(JSDOMWindow::commonVM());
2528     bool hadException = true;
2529     ExceptionDetails details;
2530     if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true, &details).jsValue()) {
2531         hadException = false;
2532         serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
2533             toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr);
2534     }
2535
2536     IPC::DataReference dataReference;
2537     if (serializedResultValue)
2538         dataReference = serializedResultValue->data();
2539     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID));
2540 }
2541
2542 void WebPage::getContentsAsString(uint64_t callbackID)
2543 {
2544     String resultString = m_mainFrame->contentsAsString();
2545     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2546 }
2547
2548 #if ENABLE(MHTML)
2549 void WebPage::getContentsAsMHTMLData(uint64_t callbackID)
2550 {
2551     RefPtr<SharedBuffer> buffer = MHTMLArchive::generateMHTMLData(m_page.get());
2552
2553     // FIXME: Use SharedBufferDataReference.
2554     IPC::DataReference dataReference;
2555     if (buffer)
2556         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2557     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2558 }
2559 #endif
2560
2561 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2562 {
2563     String resultString = renderTreeExternalRepresentation();
2564     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2565 }
2566
2567 static Frame* frameWithSelection(Page* page)
2568 {
2569     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2570         if (frame->selection().isRange())
2571             return frame;
2572     }
2573
2574     return 0;
2575 }
2576
2577 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2578 {
2579 #if PLATFORM(COCOA)
2580     RetainPtr<CFDataRef> data;
2581     if (Frame* frame = frameWithSelection(m_page.get()))
2582         data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
2583 #endif
2584
2585     IPC::DataReference dataReference;
2586 #if PLATFORM(COCOA)
2587     if (data)
2588         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2589 #endif
2590     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2591 }
2592
2593 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2594 {
2595     String resultString = m_mainFrame->selectionAsString();
2596     if (resultString.isEmpty())
2597         resultString = m_mainFrame->contentsAsString();
2598     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2599 }
2600
2601 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2602 {
2603     String resultString;
2604     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2605        resultString = frame->source();
2606
2607     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2608 }
2609
2610 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2611 {
2612     RefPtr<SharedBuffer> buffer;
2613     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2614         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
2615             buffer = pluginView->liveResourceData();
2616         if (!buffer) {
2617             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
2618                 buffer = loader->mainResourceData();
2619         }
2620     }
2621
2622     // FIXME: Use SharedBufferDataReference.
2623     IPC::DataReference dataReference;
2624     if (buffer)
2625         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2626     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2627 }
2628
2629 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2630 {
2631     DocumentLoader* loader = frame->loader().documentLoader();
2632     if (!loader)
2633         return 0;
2634
2635     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2636     if (!subresource)
2637         return 0;
2638
2639     return subresource->data();
2640 }
2641
2642 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2643 {
2644     RefPtr<SharedBuffer> buffer;
2645     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2646         URL resourceURL(URL(), resourceURLString);
2647         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2648         if (!buffer) {
2649             // Try to get the resource data from the cache.
2650             buffer = cachedResponseDataForURL(resourceURL);
2651         }
2652     }
2653
2654     // FIXME: Use SharedBufferDataReference.
2655     IPC::DataReference dataReference;
2656     if (buffer)
2657         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2658     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2659 }
2660
2661 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2662 {
2663 #if PLATFORM(COCOA)
2664     RetainPtr<CFDataRef> data;
2665     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2666         data = frame->webArchiveData(nullptr, nullptr);
2667 #else
2668     UNUSED_PARAM(frameID);
2669 #endif
2670
2671     IPC::DataReference dataReference;
2672 #if PLATFORM(COCOA)
2673     if (data)
2674         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2675 #endif
2676     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2677 }
2678
2679 void WebPage::forceRepaintWithoutCallback()
2680 {
2681     m_drawingArea->forceRepaint();
2682 }
2683
2684 void WebPage::forceRepaint(uint64_t callbackID)
2685 {
2686     if (m_drawingArea->forceRepaintAsync(callbackID))
2687         return;
2688
2689     forceRepaintWithoutCallback();
2690     send(Messages::WebPageProxy::VoidCallback(callbackID));
2691 }
2692
2693 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2694 {
2695     WebPreferencesStore::removeTestRunnerOverrides();
2696     updatePreferences(store);
2697 }
2698
2699 void WebPage::updatePreferences(const WebPreferencesStore& store)
2700 {
2701     Settings& settings = m_page->settings();
2702
2703     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2704     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2705     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2706     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2707
2708     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2709
2710 #if PLATFORM(COCOA)
2711     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2712 #endif
2713
2714     // FIXME: This should be generated from macro expansion for all preferences,
2715     // but we currently don't match the naming of WebCore exactly so we are
2716     // handrolling the boolean and integer preferences until that is fixed.
2717
2718 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2719
2720     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2721
2722 #undef INITIALIZE_SETTINGS
2723
2724     settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2725     settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2726     settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2727     settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2728     settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2729     settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2730     settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));    
2731     settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2732     settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2733     settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2734     settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2735     if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
2736         setSessionID(SessionID::legacyPrivateSessionID());
2737     else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
2738         setSessionID(SessionID::defaultSessionID());
2739     settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2740     settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
2741     settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2742     settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2743     settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2744     settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2745     settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2746     settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey()));
2747 #if ENABLE(WEB_ARCHIVE)
2748     settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2749 #endif
2750     settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2751     settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2752     settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2753     settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2754     settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2755     settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2756     settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2757     settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2758     settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2759     settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2760     settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2761
2762     settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2763     settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2764     settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2765     settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2766     settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2767     settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2768     settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2769     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2770     settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2771
2772     settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2773     settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
2774     settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
2775     settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
2776     settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2777     settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2778     settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2779     settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey()));
2780     settings.setUseGiantTiles(store.getBoolValueForKey(WebPreferencesKey::useGiantTilesKey()));
2781     
2782     settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2783     settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
2784 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
2785     RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey()));
2786 #endif
2787 #if ENABLE(WEB_ANIMATIONS)
2788     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled(store.getBoolValueForKey(WebPreferencesKey::webAnimationsEnabledKey()));
2789 #endif
2790     RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2791     RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2792     settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2793     settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2794     settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2795     settings.setRequiresUserGestureForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey()));
2796     settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey()));
2797     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute(store.getBoolValueForKey(WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey()));
2798     settings.setMediaDataLoadsAutomatically(store.getBoolValueForKey(WebPreferencesKey::mediaDataLoadsAutomaticallyKey()));
2799     settings.setAllowsPictureInPictureMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey()));
2800     settings.setMediaControlsScaleWithPageZoom(store.getBoolValueForKey(WebPreferencesKey::mediaControlsScaleWithPageZoomKey()));
2801     settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2802     settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2803     settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2804 #if ENABLE(SMOOTH_SCROLLING)
2805     settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2806 #endif
2807     settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
2808     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2809     settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2810
2811     settings.setHttpEquivEnabled(store.getBoolValueForKey(WebPreferencesKey::httpEquivEnabledKey()));
2812
2813     DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2814
2815 #if ENABLE(FULLSCREEN_API)
2816     settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2817 #endif
2818
2819 #if USE(AVFOUNDATION)
2820     settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2821 #endif
2822
2823 #if PLATFORM(COCOA)
2824     settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2825 #endif
2826
2827 #if PLATFORM(IOS) && HAVE(AVKIT)
2828     settings.setAVKitEnabled(true);
2829 #endif
2830
2831 #if ENABLE(IOS_TEXT_AUTOSIZING)
2832     settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2833 #endif
2834
2835 #if ENABLE(WEB_AUDIO)
2836     settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2837 #endif
2838
2839 #if ENABLE(MEDIA_STREAM)
2840     settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2841 #endif
2842
2843 #if ENABLE(SERVICE_CONTROLS)
2844     settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2845 #endif
2846
2847 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2848     settings.setAllowsAirPlayForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsAirPlayForMediaPlaybackKey()));
2849 #endif
2850
2851 #if ENABLE(RESOURCE_USAGE_OVERLAY)
2852     settings.setResourceUsageOverlayVisible(store.getBoolValueForKey(WebPreferencesKey::resourceUsageOverlayVisibleKey()));
2853 #endif
2854
2855     settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2856     settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2857     settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2858     settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2859     settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2860
2861 #if ENABLE(VIDEO_TRACK)
2862     settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2863     settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2864     settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2865 #endif
2866
2867 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2868     settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2869 #endif
2870
2871     settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2872     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2873     settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2874
2875     settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2876
2877     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2878
2879     settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2880     settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2881     settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2882     settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2883     settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2884
2885 #if ENABLE(TEXT_AUTOSIZING)
2886     settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2887 #endif
2888
2889     settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2890     settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2891
2892     settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2893     settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2894     settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2895
2896 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2897     settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2898 #endif
2899
2900     settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2901     settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2902     settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2903     settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2904     
2905     settings.setNewBlockInsideInlineModelEnabled(store.getBoolValueForKey(WebPreferencesKey::newBlockInsideInlineModelEnabledKey()));
2906     settings.setAntialiasedFontDilationEnabled(store.getBoolValueForKey(WebPreferencesKey::antialiasedFontDilationEnabledKey()));
2907     
2908     settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
2909
2910     settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2911
2912 #if ENABLE(MEDIA_SOURCE)
2913     settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2914 #endif
2915
2916     settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2917
2918     settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2919     settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2920     settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2921     settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2922
2923     settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2924     settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2925     
2926     settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2927     settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2928
2929     settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2930
2931     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
2932
2933 #if PLATFORM(IOS)
2934     settings.setUseImageDocumentForSubframePDF(true);
2935 #endif
2936
2937 #if ENABLE(GAMEPAD)
2938     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
2939 #endif
2940
2941 #if ENABLE(SERVICE_CONTROLS)
2942     settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
2943 #endif
2944
2945     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
2946     if (m_processSuppressionEnabled != processSuppressionEnabled) {
2947         m_processSuppressionEnabled = processSuppressionEnabled;
2948         updateUserActivity();
2949     }
2950
2951     platformPreferencesDidChange(store);
2952
2953     if (m_drawingArea)
2954         m_drawingArea->updatePreferences(store);
2955
2956 #if PLATFORM(IOS)
2957     m_viewportConfiguration.setCanIgnoreScalingConstraints(store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey()));
2958     m_viewportConfiguration.setForceAlwaysUserScalable(store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
2959 #endif
2960 }
2961
2962 #if PLATFORM(COCOA)
2963 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2964 {
2965     layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2966     layerTransaction.setScrollOrigin(corePage()->mainFrame().view()->scrollOrigin());
2967     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2968     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2969     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2970 #if PLATFORM(IOS)
2971     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2972     layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
2973     layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
2974     layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale());
2975     layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width);
2976     layerTransaction.setAllowsUserScaling(allowsUserScaling());
2977 #endif
2978 #if PLATFORM(MAC)
2979     layerTransaction.setScrollPosition(corePage()->mainFrame().view()->scrollPosition());
2980 #endif
2981 }
2982
2983 void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp)
2984 {
2985 #if PLATFORM(IOS)
2986     if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) {
2987         std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
2988         m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero();
2989
2990         m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20));
2991     }
2992 #else
2993     UNUSED_PARAM(timestamp);
2994 #endif
2995 }
2996 #endif
2997
2998 WebInspector* WebPage::inspector(LazyCreationPolicy behavior)
2999 {
3000     if (m_isClosed)
3001         return nullptr;
3002     if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded)
3003         m_inspector = WebInspector::create(this);
3004     return m_inspector.get();
3005 }
3006
3007 WebInspectorUI* WebPage::inspectorUI()
3008 {
3009     if (m_isClosed)
3010         return nullptr;
3011     if (!m_inspectorUI)
3012         m_inspectorUI = WebInspectorUI::create(*this);
3013     return m_inspectorUI.get();
3014 }
3015
3016 #if PLATFORM(IOS)
3017 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
3018 {
3019     if (!m_videoFullscreenManager)
3020         m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
3021     return m_videoFullscreenManager.get();
3022 }
3023
3024 void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows)
3025 {
3026     m_page->setAllowsMediaDocumentInlinePlayback(allows);
3027 }
3028 #endif
3029
3030 #if ENABLE(FULLSCREEN_API)
3031 WebFullScreenManager* WebPage::fullScreenManager()
3032 {
3033     if (!m_fullScreenManager)
3034         m_fullScreenManager = WebFullScreenManager::create(this);
3035     return m_fullScreenManager.get();
3036 }
3037 #endif
3038
3039 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3040 {
3041     if (m_notificationPermissionRequestManager)
3042         return m_notificationPermissionRequestManager.get();
3043
3044     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3045     return m_notificationPermissionRequestManager.get();
3046 }
3047
3048 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
3049 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
3050 {
3051     Node* node = evt->target()->toNode();
3052     ASSERT(node);
3053     Frame* frame = node->document().frame();
3054     ASSERT(frame);
3055
3056     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
3057     if (!keyEvent)
3058         return false;
3059
3060     Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
3061
3062     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
3063         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
3064         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
3065         // (e.g. Tab that inserts a Tab character, or Enter).
3066         return !command.isTextInsertion() && command.execute(evt);
3067     }
3068
3069     if (command.execute(evt))
3070         return true;
3071
3072     // Don't allow text insertion for nodes that cannot edit.
3073     if (!frame->editor().canEdit())
3074         return false;
3075
3076     // Don't insert null or control characters as they can result in unexpected behaviour
3077     if (evt->charCode() < ' ')
3078         return false;
3079
3080     return frame->editor().insertText(evt->keyEvent()->text(), evt);
3081 }
3082 #endif
3083
3084 #if ENABLE(DRAG_SUPPORT)
3085
3086 #if PLATFORM(GTK)
3087 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
3088 {
3089     if (!m_page) {
3090         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3091         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3092         data->deref();
3093         return;
3094     }
3095
3096     switch (action) {
3097     case DragControllerActionEntered: {
3098         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3099         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3100         break;
3101     }
3102     case DragControllerActionUpdated: {
3103         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3104         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3105         break;
3106     }
3107     case DragControllerActionExited:
3108         m_page->dragController().dragExited(dragData);
3109         break;
3110
3111     case DragControllerActionPerformDragOperation: {
3112         m_page->dragController().performDragOperation(dragData);
3113         break;
3114     }
3115
3116     default:
3117         ASSERT_NOT_REACHED();
3118     }
3119     // DragData does not delete its platformData so we need to do that here.
3120     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3121     data->deref();
3122 }
3123
3124 #else
3125 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)
3126 {
3127     if (!m_page) {
3128         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3129         return;
3130     }
3131
3132     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3133     switch (action) {
3134     case DragControllerActionEntered: {
3135         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3136         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3137         break;
3138
3139     }
3140     case DragControllerActionUpdated: {
3141         DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3142         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3143         break;
3144     }
3145     case DragControllerActionExited:
3146         m_page->dragController().dragExited(dragData);
3147         break;
3148         
3149     case DragControllerActionPerformDragOperation: {
3150         ASSERT(!m_pendingDropSandboxExtension);
3151
3152         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
3153         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3154             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
3155                 m_pendingDropExtensionsForFileUpload.append(extension);
3156         }
3157
3158         m_page->dragController().performDragOperation(dragData);
3159
3160         // If we started loading a local file, the sandbox extension tracker would have adopted this
3161         // pending drop sandbox extension. If not, we'll play it safe and clear it.
3162         m_pendingDropSandboxExtension = nullptr;
3163
3164         m_pendingDropExtensionsForFileUpload.clear();
3165         break;
3166     }
3167
3168     default:
3169         ASSERT_NOT_REACHED();
3170     }
3171 }
3172 #endif
3173
3174 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3175 {
3176     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3177     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3178
3179     m_page->dragController().dragEnded();
3180     FrameView* view = m_page->mainFrame().view();
3181     if (!view)
3182         return;
3183     // FIXME: These are fake modifier keys here, but they should be real ones instead.
3184     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime(), 0);
3185     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3186 }
3187
3188 void WebPage::willPerformLoadDragDestinationAction()
3189 {
3190     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
3191 }
3192
3193 void WebPage::mayPerformUploadDragDestinationAction()
3194 {
3195     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3196         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3197     m_pendingDropExtensionsForFileUpload.clear();
3198 }
3199     
3200 #endif // ENABLE(DRAG_SUPPORT)
3201
3202 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3203 {
3204     return m_undoStepMap.get(stepID);
3205 }
3206
3207 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3208 {
3209     m_undoStepMap.set(stepID, entry);
3210 }
3211
3212 void WebPage::removeWebEditCommand(uint64_t stepID)
3213 {
3214     m_undoStepMap.remove(stepID);
3215 }
3216
3217 void WebPage::unapplyEditCommand(uint64_t stepID)
3218 {
3219     WebUndoStep* step = webUndoStep(stepID);
3220     if (!step)
3221         return;
3222
3223     step->step()->unapply();
3224 }
3225
3226 void WebPage::reapplyEditCommand(uint64_t stepID)
3227 {
3228     WebUndoStep* step = webUndoStep(stepID);
3229     if (!step)
3230         return;
3231
3232     m_isInRedo = true;
3233     step->step()->reapply();
3234     m_isInRedo = false;
3235 }
3236
3237 void WebPage::didRemoveEditCommand(uint64_t commandID)
3238 {
3239     removeWebEditCommand(commandID);
3240 }
3241
3242 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3243 {
3244     m_activePopupMenu = menu;
3245 }
3246
3247 #if ENABLE(INPUT_TYPE_COLOR)
3248 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3249 {
3250     m_activeColorChooser = colorChooser;
3251 }
3252
3253 void WebPage::didEndColorPicker()
3254 {
3255     m_activeColorChooser->didEndChooser();
3256 }
3257
3258 void WebPage::didChooseColor(const WebCore::Color& color)
3259 {
3260     m_activeColorChooser->didChooseColor(color);
3261 }
3262 #endif
3263
3264 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
3265 {
3266     m_activeOpenPanelResultListener = openPanelResultListener;
3267 }
3268
3269 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3270 {
3271     return m_page->findString(target, options);
3272 }
3273
3274 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3275 {
3276     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
3277 }
3278
3279 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3280 {
3281     m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3282 }
3283
3284 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3285 {
3286     m_findController.getImageForFindMatch(matchIndex);
3287 }
3288
3289 void WebPage::selectFindMatch(uint32_t matchIndex)
3290 {
3291     m_findController.selectFindMatch(matchIndex);
3292 }
3293
3294 void WebPage::hideFindUI()
3295 {
3296     m_findController.hideFindUI();
3297 }
3298
3299 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3300 {
3301     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3302 }
3303
3304 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3305 {
3306     changeSelectedIndex(newIndex);
3307     m_activePopupMenu = nullptr;
3308 }
3309
3310 void WebPage::changeSelectedIndex(int32_t index)
3311 {
3312     if (!m_activePopupMenu)
3313         return;
3314
3315     m_activePopupMenu->didChangeSelectedIndex(index);
3316 }
3317
3318 #if PLATFORM(IOS)
3319 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3320 {
3321     if (!m_activeOpenPanelResultListener)
3322         return;
3323
3324     RefPtr<Icon> icon;
3325     if (!iconData.isEmpty()) {
3326         RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3327         RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3328         RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3329         icon = Icon::createIconForImage(imageRef.get());
3330     }
3331
3332     m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3333     m_activeOpenPanelResultListener = nullptr;
3334 }
3335 #endif
3336
3337 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3338 {
3339     if (!m_activeOpenPanelResultListener)
3340         return;
3341
3342     m_activeOpenPanelResultListener->didChooseFiles(files);
3343     m_activeOpenPanelResultListener = nullptr;
3344 }
3345
3346 void WebPage::didCancelForOpenPanel()
3347 {
3348     m_activeOpenPanelResultListener = nullptr;
3349 }
3350
3351 #if ENABLE(SANDBOX_EXTENSIONS)
3352 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3353 {
3354     bool result = SandboxExtension::consumePermanently(handle);
3355     if (!result) {
3356         // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3357         WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3358     }
3359 }
3360 #endif
3361
3362 #if ENABLE(GEOLOCATION)
3363 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3364 {
3365     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3366 }
3367 #endif
3368
3369 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3370 {
3371     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3372 }
3373
3374 #if ENABLE(MEDIA_STREAM)
3375 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed, const String& audioDeviceUID, const String& videoDeviceUID)
3376 {
3377     m_userMediaPermissionRequestManager.didReceiveUserMediaPermissionDecision(userMediaID, allowed, audioDeviceUID, videoDeviceUID);
3378 }
3379 #endif
3380
3381 #if !PLATFORM(IOS)
3382 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3383 {
3384     Frame& frame = m_page->focusController().focusedOrMainFrame();
3385     frame.editor().advanceToNextMisspelling(startBeforeSelection);
3386 }
3387 #endif
3388
3389 void WebPage::changeSpellingToWord(const String& word)
3390 {
3391     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3392 }
3393
3394 void WebPage::unmarkAllMisspellings()
3395 {
3396     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3397         if (Document* document = frame->document())
3398             document->markers().removeMarkers(DocumentMarker::Spelling);
3399     }
3400 }
3401
3402 void WebPage::unmarkAllBadGrammar()
3403 {
3404     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3405         if (Document* document = frame->document())
3406             document->markers().removeMarkers(DocumentMarker::Grammar);
3407     }
3408 }
3409
3410 #if USE(APPKIT)
3411 void WebPage::uppercaseWord()
3412 {
3413     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3414 }
3415
3416 void WebPage::lowercaseWord()
3417 {
3418     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3419 }
3420
3421 void WebPage::capitalizeWord()
3422 {
3423     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3424 }
3425 #endif
3426     
3427 void WebPage::setTextForActivePopupMenu(int32_t index)
3428 {
3429     if (!m_activePopupMenu)
3430         return;
3431
3432     m_activePopupMenu->setTextForIndex(index);
3433 }
3434
3435 #if PLATFORM(GTK)
3436 void WebPage::failedToShowPopupMenu()
3437 {
3438     if (!m_activePopupMenu)
3439         return;
3440
3441     m_activePopupMenu->client()->popupDidHide();
3442 }
3443 #endif
3444
3445 #if ENABLE(CONTEXT_MENUS)
3446 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3447 {
3448     if (!m_contextMenu)
3449         return;
3450
3451     m_contextMenu->itemSelected(item);
3452     m_contextMenu = nullptr;
3453 }
3454 #endif
3455
3456 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3457 {
3458     bool selectReplacement = true;
3459     bool smartReplace = false;
3460     return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3461 }
3462
3463 #if !PLATFORM(IOS)
3464 void WebPage::clearSelection()
3465 {
3466     m_page->focusController().focusedOrMainFrame().selection().clear();
3467 }
3468 #endif
3469
3470 void WebPage::restoreSelectionInFocusedEditableElement()
3471 {
3472     Frame& frame = m_page->focusController().focusedOrMainFrame();
3473     if (!frame.selection().isNone())
3474         return;
3475
3476     if (auto document = frame.document()) {
3477         if (auto element = document->focusedElement())
3478             element->updateFocusAppearance(SelectionRestorationMode::Restore, SelectionRevealMode::DoNotReveal);
3479     }
3480 }
3481
3482 bool WebPage::mainFrameHasCustomContentProvider() const
3483 {
3484     if (Frame* frame = mainFrame()) {
3485         WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3486         ASSERT(webFrameLoaderClient);
3487         return webFrameLoaderClient->frameHasCustomContentProvider();
3488     }
3489
3490     return false;
3491 }
3492
3493 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3494 {
3495     m_mimeTypesWithCustomContentProviders.add(mimeType);
3496 }
3497
3498 void WebPage::updateMainFrameScrollOffsetPinning()
3499 {
3500     Frame& frame = m_page->mainFrame();
3501     IntPoint scrollPosition = frame.view()->scrollPosition();
3502     IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3503     IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3504
3505     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3506     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3507     bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3508     bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3509
3510     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3511         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3512         
3513         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3514         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3515         m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3516         m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3517     }
3518 }
3519
3520 void WebPage::mainFrameDidLayout()
3521 {
3522     unsigned pageCount = m_page->pageCount();
3523     if (pageCount != m_cachedPageCount) {
3524         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3525         m_cachedPageCount = pageCount;
3526     }
3527
3528 #if PLATFORM(MAC)
3529     m_viewGestureGeometryCollector.mainFrameDidLayout();
3530 #endif
3531 #if PLATFORM(IOS)
3532     if (FrameView* frameView = mainFrameView()) {
3533         IntSize newContentSize = frameView->contentsSizeRespectingOverflow();
3534         if (m_viewportConfiguration.contentsSize() != newContentSize) {
3535             m_viewportConfiguration.setContentsSize(newContentSize);
3536             viewportConfigurationChanged();
3537         }
3538     }
3539     m_findController.redraw();
3540 #endif
3541 }
3542