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