358e1c08b1ea1c10a89b3461bcbd37cc890faed4
[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     if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) {
2533         serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
2534             toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr);
2535     }
2536
2537     IPC::DataReference dataReference;
2538     if (serializedResultValue)
2539         dataReference = serializedResultValue->data();
2540     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2541 }
2542
2543 void WebPage::getContentsAsString(uint64_t callbackID)
2544 {
2545     String resultString = m_mainFrame->contentsAsString();
2546     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2547 }
2548
2549 #if ENABLE(MHTML)
2550 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2551 {
2552     RefPtr<SharedBuffer> buffer = useBinaryEncoding
2553         ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2554         : MHTMLArchive::generateMHTMLData(m_page.get());
2555
2556     // FIXME: Use SharedBufferDataReference.
2557     IPC::DataReference dataReference;
2558     if (buffer)
2559         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2560     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2561 }
2562 #endif
2563
2564 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2565 {
2566     String resultString = renderTreeExternalRepresentation();
2567     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2568 }
2569
2570 static Frame* frameWithSelection(Page* page)
2571 {
2572     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2573         if (frame->selection().isRange())
2574             return frame;
2575     }
2576
2577     return 0;
2578 }
2579
2580 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2581 {
2582 #if PLATFORM(COCOA)
2583     RetainPtr<CFDataRef> data;
2584     if (Frame* frame = frameWithSelection(m_page.get()))
2585         data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation();
2586 #endif
2587
2588     IPC::DataReference dataReference;
2589 #if PLATFORM(COCOA)
2590     if (data)
2591         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2592 #endif
2593     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2594 }
2595
2596 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2597 {
2598     String resultString = m_mainFrame->selectionAsString();
2599     if (resultString.isEmpty())
2600         resultString = m_mainFrame->contentsAsString();
2601     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2602 }
2603
2604 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2605 {
2606     String resultString;
2607     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2608        resultString = frame->source();
2609
2610     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2611 }
2612
2613 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2614 {
2615     RefPtr<SharedBuffer> buffer;
2616     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2617         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
2618             buffer = pluginView->liveResourceData();
2619         if (!buffer) {
2620             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader())
2621                 buffer = loader->mainResourceData();
2622         }
2623     }
2624
2625     // FIXME: Use SharedBufferDataReference.
2626     IPC::DataReference dataReference;
2627     if (buffer)
2628         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2629     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2630 }
2631
2632 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2633 {
2634     DocumentLoader* loader = frame->loader().documentLoader();
2635     if (!loader)
2636         return 0;
2637
2638     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2639     if (!subresource)
2640         return 0;
2641
2642     return subresource->data();
2643 }
2644
2645 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2646 {
2647     RefPtr<SharedBuffer> buffer;
2648     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
2649         URL resourceURL(URL(), resourceURLString);
2650         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2651         if (!buffer) {
2652             // Try to get the resource data from the cache.
2653             buffer = cachedResponseDataForURL(resourceURL);
2654         }
2655     }
2656
2657     // FIXME: Use SharedBufferDataReference.
2658     IPC::DataReference dataReference;
2659     if (buffer)
2660         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2661     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2662 }
2663
2664 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2665 {
2666 #if PLATFORM(COCOA)
2667     RetainPtr<CFDataRef> data;
2668     if (WebFrame* frame = WebProcess::singleton().webFrame(frameID))
2669         data = frame->webArchiveData(nullptr, nullptr);
2670 #else
2671     UNUSED_PARAM(frameID);
2672 #endif
2673
2674     IPC::DataReference dataReference;
2675 #if PLATFORM(COCOA)
2676     if (data)
2677         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2678 #endif
2679     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2680 }
2681
2682 void WebPage::forceRepaintWithoutCallback()
2683 {
2684     m_drawingArea->forceRepaint();
2685 }
2686
2687 void WebPage::forceRepaint(uint64_t callbackID)
2688 {
2689     if (m_drawingArea->forceRepaintAsync(callbackID))
2690         return;
2691
2692     forceRepaintWithoutCallback();
2693     send(Messages::WebPageProxy::VoidCallback(callbackID));
2694 }
2695
2696 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2697 {
2698     WebPreferencesStore::removeTestRunnerOverrides();
2699     updatePreferences(store);
2700 }
2701
2702 void WebPage::updatePreferences(const WebPreferencesStore& store)
2703 {
2704     Settings& settings = m_page->settings();
2705
2706     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2707     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2708     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2709     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2710
2711     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2712
2713 #if PLATFORM(COCOA)
2714     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2715 #endif
2716
2717     // FIXME: This should be generated from macro expansion for all preferences,
2718     // but we currently don't match the naming of WebCore exactly so we are
2719     // handrolling the boolean and integer preferences until that is fixed.
2720
2721 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2722
2723     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2724
2725 #undef INITIALIZE_SETTINGS
2726
2727     settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2728     settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2729     settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2730     settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2731     settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2732     settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2733     settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));    
2734     settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2735     settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2736     settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2737     settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2738     if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession())
2739         setSessionID(SessionID::legacyPrivateSessionID());
2740     else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID())
2741         setSessionID(SessionID::defaultSessionID());
2742     settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2743     settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey())));
2744     settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2745     settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2746     settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2747     settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2748     settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2749     settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey()));
2750 #if ENABLE(WEB_ARCHIVE)
2751     settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2752 #endif
2753     settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2754     settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2755     settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2756     settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2757     settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2758     settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2759     settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2760     settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2761     settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2762     settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2763     settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2764
2765     settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2766     settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2767     settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2768     settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2769     settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2770     settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2771     settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2772     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2773     settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2774
2775     settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2776     settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
2777     settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
2778     settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()));
2779     settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2780     settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2781     settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2782     settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey()));
2783     
2784     settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2785     settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey()));
2786 #if ENABLE(CSS_ANIMATIONS_LEVEL_2)
2787     RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey()));
2788 #endif
2789     RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2790     RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2791     settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2792     settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2793     settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2794     settings.setRequiresUserGestureForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey()));
2795     settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey()));
2796     settings.setAllowsAlternateFullscreen(store.getBoolValueForKey(WebPreferencesKey::allowsAlternateFullscreenKey()));
2797     settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2798     settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2799     settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2800 #if ENABLE(SMOOTH_SCROLLING)
2801     settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2802 #endif
2803     settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey()));
2804     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2805     settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2806
2807     settings.setMetaRefreshEnabled(store.getBoolValueForKey(WebPreferencesKey::metaRefreshEnabledKey()));
2808
2809     DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2810
2811 #if ENABLE(FULLSCREEN_API)
2812     settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2813 #endif
2814
2815 #if USE(AVFOUNDATION)
2816     settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2817 #endif
2818
2819 #if PLATFORM(COCOA)
2820     settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2821 #endif
2822
2823 #if PLATFORM(IOS) && HAVE(AVKIT)
2824     settings.setAVKitEnabled(true);
2825 #endif
2826
2827 #if ENABLE(IOS_TEXT_AUTOSIZING)
2828     settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2829 #endif
2830
2831 #if ENABLE(WEB_AUDIO)
2832     settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2833 #endif
2834
2835 #if ENABLE(MEDIA_STREAM)
2836     settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2837 #endif
2838
2839 #if ENABLE(SERVICE_CONTROLS)
2840     settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2841 #endif
2842
2843 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2844     settings.setAllowsAirPlayForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsAirPlayForMediaPlaybackKey()));
2845 #endif
2846
2847     settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2848     settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2849     settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2850     settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2851     settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2852
2853 #if ENABLE(VIDEO_TRACK)
2854     settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2855     settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2856     settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2857 #endif
2858
2859 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2860     settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2861 #endif
2862
2863     settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2864     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2865     settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2866
2867     settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2868
2869     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2870
2871     settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2872     settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2873     settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2874     settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2875     settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2876
2877 #if ENABLE(TEXT_AUTOSIZING)
2878     settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2879 #endif
2880
2881     settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2882     settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2883
2884     settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2885     settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2886     settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2887
2888 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2889     settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2890 #endif
2891
2892     settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2893     settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2894     settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2895     settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2896     
2897     settings.setNewBlockInsideInlineModelEnabled(store.getBoolValueForKey(WebPreferencesKey::newBlockInsideInlineModelEnabledKey()));
2898     settings.setAntialiasedFontDilationEnabled(store.getBoolValueForKey(WebPreferencesKey::antialiasedFontDilationEnabledKey()));
2899     
2900     settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
2901
2902     settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2903
2904 #if ENABLE(MEDIA_SOURCE)
2905     settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2906 #endif
2907
2908     settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2909
2910     settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2911     settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2912     settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2913     settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2914
2915     settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2916     settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2917     
2918     settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2919     settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2920
2921     settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2922
2923     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
2924
2925 #if PLATFORM(IOS)
2926     settings.setUseImageDocumentForSubframePDF(true);
2927 #endif
2928
2929     settings.setLongMousePressEnabled(store.getBoolValueForKey(WebPreferencesKey::longMousePressEnabledKey()));
2930
2931 #if ENABLE(GAMEPAD)
2932     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
2933 #endif
2934
2935 #if ENABLE(SERVICE_CONTROLS)
2936     settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
2937 #endif
2938
2939     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
2940     if (m_processSuppressionEnabled != processSuppressionEnabled) {
2941         m_processSuppressionEnabled = processSuppressionEnabled;
2942         updateUserActivity();
2943     }
2944
2945     platformPreferencesDidChange(store);
2946
2947     if (m_drawingArea)
2948         m_drawingArea->updatePreferences(store);
2949
2950 #if PLATFORM(IOS)
2951     m_viewportConfiguration.setCanIgnoreScalingConstraints(store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey()));
2952     m_viewportConfiguration.setForceAlwaysUserScalable(store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
2953 #endif
2954 }
2955
2956 #if PLATFORM(COCOA)
2957 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2958 {
2959     layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2960     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2961     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2962     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2963 #if PLATFORM(IOS)
2964     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2965     layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
2966     layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
2967     layerTransaction.setAllowsUserScaling(allowsUserScaling());
2968 #endif
2969 #if PLATFORM(MAC)
2970     layerTransaction.setScrollPosition(corePage()->mainFrame().view()->scrollPosition());
2971 #endif
2972 }
2973
2974 void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp)
2975 {
2976 #if PLATFORM(IOS)
2977     if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) {
2978         std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
2979         m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero();
2980
2981         m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20));
2982     }
2983 #else
2984     UNUSED_PARAM(timestamp);
2985 #endif
2986 }
2987 #endif
2988
2989 WebInspector* WebPage::inspector()
2990 {
2991     if (m_isClosed)
2992         return nullptr;
2993     if (!m_inspector)
2994         m_inspector = WebInspector::create(this);
2995     return m_inspector.get();
2996 }
2997
2998 WebInspectorUI* WebPage::inspectorUI()
2999 {
3000     if (m_isClosed)
3001         return nullptr;
3002     if (!m_inspectorUI)
3003         m_inspectorUI = WebInspectorUI::create(this);
3004     return m_inspectorUI.get();
3005 }
3006
3007 #if PLATFORM(IOS)
3008 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
3009 {
3010     if (!m_videoFullscreenManager)
3011         m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
3012     return m_videoFullscreenManager.get();
3013 }
3014 #endif
3015
3016 #if ENABLE(FULLSCREEN_API)
3017 WebFullScreenManager* WebPage::fullScreenManager()
3018 {
3019     if (!m_fullScreenManager)
3020         m_fullScreenManager = WebFullScreenManager::create(this);
3021     return m_fullScreenManager.get();
3022 }
3023 #endif
3024
3025 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
3026 {
3027     if (m_notificationPermissionRequestManager)
3028         return m_notificationPermissionRequestManager.get();
3029
3030     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
3031     return m_notificationPermissionRequestManager.get();
3032 }
3033
3034 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
3035 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
3036 {
3037     Node* node = evt->target()->toNode();
3038     ASSERT(node);
3039     Frame* frame = node->document().frame();
3040     ASSERT(frame);
3041
3042     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
3043     if (!keyEvent)
3044         return false;
3045
3046     Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
3047
3048     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
3049         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
3050         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
3051         // (e.g. Tab that inserts a Tab character, or Enter).
3052         return !command.isTextInsertion() && command.execute(evt);
3053     }
3054
3055     if (command.execute(evt))
3056         return true;
3057
3058     // Don't allow text insertion for nodes that cannot edit.
3059     if (!frame->editor().canEdit())
3060         return false;
3061
3062     // Don't insert null or control characters as they can result in unexpected behaviour
3063     if (evt->charCode() < ' ')
3064         return false;
3065
3066     return frame->editor().insertText(evt->keyEvent()->text(), evt);
3067 }
3068 #endif
3069
3070 #if ENABLE(DRAG_SUPPORT)
3071
3072 #if PLATFORM(GTK)
3073 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
3074 {
3075     if (!m_page) {
3076         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3077         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3078         data->deref();
3079         return;
3080     }
3081
3082     switch (action) {
3083     case DragControllerActionEntered: {
3084         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3085         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3086         break;
3087     }
3088     case DragControllerActionUpdated: {
3089         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3090         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3091         break;
3092     }
3093     case DragControllerActionExited:
3094         m_page->dragController().dragExited(dragData);
3095         break;
3096
3097     case DragControllerActionPerformDragOperation: {
3098         m_page->dragController().performDragOperation(dragData);
3099         break;
3100     }
3101
3102     default:
3103         ASSERT_NOT_REACHED();
3104     }
3105     // DragData does not delete its platformData so we need to do that here.
3106     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3107     data->deref();
3108 }
3109
3110 #else
3111 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)
3112 {
3113     if (!m_page) {
3114         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3115         return;
3116     }
3117
3118     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3119     switch (action) {
3120     case DragControllerActionEntered: {
3121         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3122         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3123         break;
3124
3125     }
3126     case DragControllerActionUpdated: {
3127         DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3128         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3129         break;
3130     }
3131     case DragControllerActionExited:
3132         m_page->dragController().dragExited(dragData);
3133         break;
3134         
3135     case DragControllerActionPerformDragOperation: {
3136         ASSERT(!m_pendingDropSandboxExtension);
3137
3138         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
3139         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3140             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
3141                 m_pendingDropExtensionsForFileUpload.append(extension);
3142         }
3143
3144         m_page->dragController().performDragOperation(dragData);
3145
3146         // If we started loading a local file, the sandbox extension tracker would have adopted this
3147         // pending drop sandbox extension. If not, we'll play it safe and clear it.
3148         m_pendingDropSandboxExtension = nullptr;
3149
3150         m_pendingDropExtensionsForFileUpload.clear();
3151         break;
3152     }
3153
3154     default:
3155         ASSERT_NOT_REACHED();
3156     }
3157 }
3158 #endif
3159
3160 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3161 {
3162     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3163     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3164
3165     m_page->dragController().dragEnded();
3166     FrameView* view = m_page->mainFrame().view();
3167     if (!view)
3168         return;
3169     // FIXME: These are fake modifier keys here, but they should be real ones instead.
3170     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime(), 0);
3171     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3172 }
3173
3174 void WebPage::willPerformLoadDragDestinationAction()
3175 {
3176     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
3177 }
3178
3179 void WebPage::mayPerformUploadDragDestinationAction()
3180 {
3181     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3182         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3183     m_pendingDropExtensionsForFileUpload.clear();
3184 }
3185     
3186 #endif // ENABLE(DRAG_SUPPORT)
3187
3188 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3189 {
3190     return m_undoStepMap.get(stepID);
3191 }
3192
3193 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3194 {
3195     m_undoStepMap.set(stepID, entry);
3196 }
3197
3198 void WebPage::removeWebEditCommand(uint64_t stepID)
3199 {
3200     m_undoStepMap.remove(stepID);
3201 }
3202
3203 void WebPage::unapplyEditCommand(uint64_t stepID)
3204 {
3205     WebUndoStep* step = webUndoStep(stepID);
3206     if (!step)
3207         return;
3208
3209     step->step()->unapply();
3210 }
3211
3212 void WebPage::reapplyEditCommand(uint64_t stepID)
3213 {
3214     WebUndoStep* step = webUndoStep(stepID);
3215     if (!step)
3216         return;
3217
3218     m_isInRedo = true;
3219     step->step()->reapply();
3220     m_isInRedo = false;
3221 }
3222
3223 void WebPage::didRemoveEditCommand(uint64_t commandID)
3224 {
3225     removeWebEditCommand(commandID);
3226 }
3227
3228 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3229 {
3230     m_activePopupMenu = menu;
3231 }
3232
3233 #if ENABLE(INPUT_TYPE_COLOR)
3234 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3235 {
3236     m_activeColorChooser = colorChooser;
3237 }
3238
3239 void WebPage::didEndColorPicker()
3240 {
3241     m_activeColorChooser->didEndChooser();
3242 }
3243
3244 void WebPage::didChooseColor(const WebCore::Color& color)
3245 {
3246     m_activeColorChooser->didChooseColor(color);
3247 }
3248 #endif
3249
3250 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
3251 {
3252     m_activeOpenPanelResultListener = openPanelResultListener;
3253 }
3254
3255 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3256 {
3257     return m_page->findString(target, options);
3258 }
3259
3260 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3261 {
3262     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
3263 }
3264
3265 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3266 {
3267     m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3268 }
3269
3270 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3271 {
3272     m_findController.getImageForFindMatch(matchIndex);
3273 }
3274
3275 void WebPage::selectFindMatch(uint32_t matchIndex)
3276 {
3277     m_findController.selectFindMatch(matchIndex);
3278 }
3279
3280 void WebPage::hideFindUI()
3281 {
3282     m_findController.hideFindUI();
3283 }
3284
3285 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3286 {
3287     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3288 }
3289
3290 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3291 {
3292     changeSelectedIndex(newIndex);
3293     m_activePopupMenu = 0;
3294 }
3295
3296 void WebPage::changeSelectedIndex(int32_t index)
3297 {
3298     if (!m_activePopupMenu)
3299         return;
3300
3301     m_activePopupMenu->didChangeSelectedIndex(index);
3302 }
3303
3304 #if PLATFORM(IOS)
3305 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3306 {
3307     if (!m_activeOpenPanelResultListener)
3308         return;
3309
3310     RefPtr<Icon> icon;
3311     if (!iconData.isEmpty()) {
3312         RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3313         RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3314         RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3315         icon = Icon::createIconForImage(imageRef.get());
3316     }
3317
3318     m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3319     m_activeOpenPanelResultListener = nullptr;
3320 }
3321 #endif
3322
3323 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3324 {
3325     if (!m_activeOpenPanelResultListener)
3326         return;
3327
3328     m_activeOpenPanelResultListener->didChooseFiles(files);
3329     m_activeOpenPanelResultListener = 0;
3330 }
3331
3332 void WebPage::didCancelForOpenPanel()
3333 {
3334     m_activeOpenPanelResultListener = 0;
3335 }
3336
3337 #if ENABLE(SANDBOX_EXTENSIONS)
3338 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3339 {
3340     bool result = SandboxExtension::consumePermanently(handle);
3341     if (!result) {
3342         // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>.
3343         WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension");
3344     }
3345 }
3346 #endif
3347
3348 #if ENABLE(GEOLOCATION)
3349 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3350 {
3351     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3352 }
3353 #endif
3354
3355 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3356 {
3357     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3358 }
3359
3360 #if ENABLE(MEDIA_STREAM)
3361 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed)
3362 {
3363     m_userMediaPermissionRequestManager.didReceiveUserMediaPermissionDecision(userMediaID, allowed);
3364 }
3365 #endif
3366
3367 #if !PLATFORM(IOS)
3368 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3369 {
3370     Frame& frame = m_page->focusController().focusedOrMainFrame();
3371     frame.editor().advanceToNextMisspelling(startBeforeSelection);
3372 }
3373 #endif
3374
3375 void WebPage::changeSpellingToWord(const String& word)
3376 {
3377     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3378 }
3379
3380 void WebPage::unmarkAllMisspellings()
3381 {
3382     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3383         if (Document* document = frame->document())
3384             document->markers().removeMarkers(DocumentMarker::Spelling);
3385     }
3386 }
3387
3388 void WebPage::unmarkAllBadGrammar()
3389 {
3390     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3391         if (Document* document = frame->document())
3392             document->markers().removeMarkers(DocumentMarker::Grammar);
3393     }
3394 }
3395
3396 #if USE(APPKIT)
3397 void WebPage::uppercaseWord()
3398 {
3399     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3400 }
3401
3402 void WebPage::lowercaseWord()
3403 {
3404     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3405 }
3406
3407 void WebPage::capitalizeWord()
3408 {
3409     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3410 }
3411 #endif
3412     
3413 void WebPage::setTextForActivePopupMenu(int32_t index)
3414 {
3415     if (!m_activePopupMenu)
3416         return;
3417
3418     m_activePopupMenu->setTextForIndex(index);
3419 }
3420
3421 #if PLATFORM(GTK)
3422 void WebPage::failedToShowPopupMenu()
3423 {
3424     if (!m_activePopupMenu)
3425         return;
3426
3427     m_activePopupMenu->client()->popupDidHide();
3428 }
3429 #endif
3430
3431 #if ENABLE(CONTEXT_MENUS)
3432 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3433 {
3434     if (!m_contextMenu)
3435         return;
3436
3437     m_contextMenu->itemSelected(item);
3438     m_contextMenu = 0;
3439 }
3440 #endif
3441
3442 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3443 {
3444     bool selectReplacement = true;
3445     bool smartReplace = false;
3446     return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3447 }
3448
3449 #if !PLATFORM(IOS)
3450 void WebPage::clearSelection()
3451 {
3452     m_page->focusController().focusedOrMainFrame().selection().clear();
3453 }
3454 #endif
3455
3456 void WebPage::restoreSelectionInFocusedEditableElement()
3457 {
3458     Frame& frame = m_page->focusController().focusedOrMainFrame();
3459     if (!frame.selection().isNone())
3460         return;
3461
3462     if (auto document = frame.document()) {
3463         if (auto element = document->focusedElement())
3464             element->updateFocusAppearance(true /* restoreSelection */);
3465     }
3466 }
3467
3468 bool WebPage::mainFrameHasCustomContentProvider() const
3469 {
3470     if (Frame* frame = mainFrame()) {
3471         WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3472         ASSERT(webFrameLoaderClient);
3473         return webFrameLoaderClient->frameHasCustomContentProvider();
3474     }
3475
3476     return false;
3477 }
3478
3479 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3480 {
3481     m_mimeTypesWithCustomContentProviders.add(mimeType);
3482 }
3483
3484 void WebPage::updateMainFrameScrollOffsetPinning()
3485 {
3486     Frame& frame = m_page->mainFrame();
3487     IntPoint scrollPosition = frame.view()->scrollPosition();
3488     IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3489     IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3490
3491     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3492     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3493     bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3494     bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3495
3496     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3497         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3498         
3499         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3500         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3501         m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3502         m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3503     }
3504 }
3505
3506 void WebPage::mainFrameDidLayout()
3507 {
3508     unsigned pageCount = m_page->pageCount();
3509     if (pageCount != m_cachedPageCount) {
3510         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3511         m_cachedPageCount = pageCount;
3512     }
3513
3514 #if PLATFORM(MAC)
3515     m_viewGestureGeometryCollector.mainFrameDidLayout();
3516 #endif
3517 #if PLATFORM(IOS)
3518     if (FrameView* frameView = mainFrameView()) {
3519         IntSize newContentSize = frameView->contentsSize();
3520         if (m_viewportConfiguration.contentsSize() != newContentSize) {
3521             m_viewportConfiguration.setContentsSize(newContentSize);
3522             viewportConfigurationChanged();
3523         }
3524     }
3525     m_findController.redraw();
3526 #endif
3527 }
3528
3529 void WebPage::addPluginView(PluginView* pluginView)
3530 {
3531     ASSERT(!m_pluginViews.contains(pluginView));
3532
3533     m_pluginViews.add(pluginView);
3534     m_hasSeenPlugin = true;
3535 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3536     LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3537     m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3538 #endif
3539 }
3540
3541 void WebPage::removePluginView(PluginView* pluginView)
3542 {
3543     ASSERT(m_pluginViews.contains(pluginView));
3544
3545     m_pluginViews.remove(pluginView);
3546 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3547     LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3548 #endif
3549 }
3550
3551 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3552 {
3553 #if PLATFORM(COCOA)
3554     m_hasCachedWindowFrame = false;
3555 #endif
3556     send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3557 }
3558
3559 #if PLATFORM(COCOA)
3560 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3561 {
3562     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3563     m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3564     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3565     m_accessibilityPosition = accessibilityViewCoordinates;
3566     
3567     // Tell all our plug-in views that the window and view frames have changed.
3568     for (auto* pluginView : m_pluginViews)
3569         pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3570
3571     m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3572 }
3573 #endif
3574
3575 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3576 {
3577     m_mainFrameIsScrollable = isScrollable;
3578     m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3579
3580     if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3581         frameView->setCanHaveScrollbars(isScrollable);
3582         frameView->setProhibitsScrolling(!isScrollable);
3583     }
3584 }
3585
3586 bool WebPage::windowIsFocused() const
3587 {
3588     return m_page->focusController().isActive();
3589 }
3590
3591 bool WebPage::windowAndWebPageAreFocused() const
3592 {
3593     if (!isVisible())
3594         return false;
3595
3596     return m_page->focusController().isFocused() && m_page->focusController().isActive();
3597 }
3598
3599 void WebPage::didReceiveMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder)
3600 {
3601 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
3602     if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
3603         if (m_drawingArea)
3604             m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
3605         return;
3606     }
3607 #endif
3608
3609     if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
3610         if (WebInspector* inspector = this->inspector())
3611             inspector->didReceiveMessage(connection, decoder);
3612         return;
3613     }
3614
3615     if (decoder.messageReceiverName() == Messages::WebInspectorUI::messageReceiverName()) {
3616         if (WebInspectorUI* inspectorUI = this->inspectorUI())
3617             inspectorUI->didReceiveMessage(connection, decoder);
3618         return;
3619     }
3620
3621 #if ENABLE(FULLSCREEN_API)
3622     if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
3623         fullScreenManager()->didReceiveMessage(connection, decoder);
3624         return;
3625     }
3626 #endif
3627
3628     didReceiveWebPageMessage(connection, decoder);
3629 }
3630
3631 void WebPage::didReceiveSyncMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder)
3632 {   
3633     didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
3634 }
3635     
3636 InjectedBundleBackForwardList* WebPage::backForwardList()
3637 {
3638     if (!m_backForwardList)
3639         m_backForwardList = InjectedBundleBackForwardList::create(this);
3640     return m_backForwardList.get();
3641 }
3642
3643 #if ENABLE(ASYNC_SCROLLING)
3644 ScrollingCoordinator* WebPage::scrollingCoordinator() const
3645 {
3646     return m_page->scrollingCoordinator();
3647 }
3648 #endif
3649
3650 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3651 {
3652     invalidate();
3653 }
3654
3655 void WebPage::SandboxExtensionTracker::invalidate()
3656 {
3657     m_pendingProvisionalSandboxExtension = nullptr;
3658
3659     if (m_provisionalSandboxExtension) {
3660         m_provisionalSandboxExtension->revoke();
3661         m_provisionalSandboxExtension = nullptr;
3662     }
3663
3664     if (m_committedSandboxExtension) {
3665         m_committedSandboxExtension->revoke();
3666         m_committedSandboxExtension = nullptr;
3667     }
3668 }
3669
3670 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3671 {
3672     setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3673 }
3674
3675 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3676 {
3677     ASSERT_UNUSED(frame, frame->isMainFrame());
3678
3679     setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3680 }
3681
3682 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3683 {
3684     m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;    
3685 }
3686
3687 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3688 {
3689     ASSERT(frame->isMainFrame());
3690
3691     FrameLoader& frameLoader = frame->coreFrame()->loader();
3692     FrameLoadType frameLoadType = frameLoader.loadType();
3693
3694     // If the page is being reloaded, it should reuse whatever extension is committed.
3695     if (frameLoadType == FrameLoadType::Reload || frameLoadType == FrameLoadType::ReloadFromOrigin)
3696         return true;
3697
3698     DocumentLoader* documentLoader = frameLoader.documentLoader();
3699     DocumentLoader* provisionalDocumentLoader = frameLoader.provisionalDocumentLoader();
3700     if (!documentLoader || !provisionalDocumentLoader)
3701         return false;
3702
3703     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3704         return true;
3705
3706     return false;
3707 }
3708
3709 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3710 {
3711     if (!frame->isMainFrame())
3712         return;
3713
3714     // We should only reuse the commited sandbox extension if it is not null. It can be
3715     // null if the last load was for an error page.
3716     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame))
3717         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension;
3718
3719     ASSERT(!m_provisionalSandboxExtension);
3720
3721     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3722     if (!m_provisionalSandboxExtension)
3723         return;
3724
3725     ASSERT(!m_provisionalSandboxExtension || frame->coreFrame()->loader().provisionalDocumentLoader()->url().isLocalFile());
3726
3727     m_provisionalSandboxExtension->consume();
3728 }
3729
3730 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3731 {
3732     if (!frame->isMainFrame())
3733         return;
3734
3735     if (m_committedSandboxExtension)
3736         m_committedSandboxExtension->revoke();
3737
3738     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3739
3740     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started.
3741     // This extension is not cleared, because it does not pertain to the failed load, and will be needed.
3742 }
3743
3744 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3745 {
3746     if (!frame->isMainFrame())
3747         return;
3748
3749     if (!m_provisionalSandboxExtension)
3750         return;
3751
3752     m_provisionalSandboxExtension->revoke();
3753     m_provisionalSandboxExtension = nullptr;
3754
3755     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started
3756     // (notably, if the current one fails because the new one cancels it). This extension is not cleared,
3757     // because it does not pertain to the failed load, and will be needed.
3758 }
3759
3760 bool WebPage::hasLocalDataForURL(const URL& url)
3761 {
3762     if (url.isLocalFile())
3763         return true;
3764
3765     DocumentLoader* documentLoader = m_page->mainFrame().loader().documentLoader();
3766     if (documentLoader && documentLoader->subresource(url))
3767         return true;
3768
3769     return platformHasLocalDataForURL(url);
3770 }
3771
3772 void WebPage::setCustomTextEncodingName(const String& encoding)
3773 {
3774     m_page->mainFrame().loader().reloadWithOverrideEncoding(encoding);
3775 }
3776
3777 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3778 {
3779     WebBackForwardListProxy::removeItem(itemID);
3780 }
3781
3782 #if PLATFORM(COCOA)
3783
3784 bool WebPage::isSpeaking()
3785 {
3786     bool result;
3787     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3788 }
3789
3790 void WebPage::speak(const String& string)
3791 {
3792     send(Messages::WebPageProxy::Speak(string));
3793 }
3794
3795 void WebPage::stopSpeaking()
3796 {
3797     send(Messages::WebPageProxy::StopSpeaking());
3798 }
3799
3800 #endif
3801
3802 #if PLATFORM(MAC)
3803 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3804 {
3805     Document* document = coreFrame->document();
3806     if (!is<PluginDocument>(document))
3807         return nullptr;
3808
3809     PluginView* pluginView = static_cast<PluginView*>(downcast<PluginDocument>(*document).pluginWidget());
3810     if (!pluginView)
3811         return nullptr;
3812
3813     return pluginView->pdfDocumentForPrinting();
3814 }
3815 #endif // PLATFORM(MAC)
3816
3817 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3818 {
3819     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3820     if (!frame)
3821         return;
3822
3823     Frame* coreFrame = frame->coreFrame();
3824     if (!coreFrame)
3825         return;
3826
3827 #if PLATFORM(MAC)
3828     if (pdfDocumentForPrintingFrame(coreFrame))
3829         return;
3830 #endif // PLATFORM(MAC)
3831
3832     if (!m_printContext)
3833         m_printContext = std::make_unique<PrintContext>(coreFrame);
3834
3835     drawingArea()->setLayerTreeStateIsFrozen(true);
3836     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3837
3838     float fullPageHeight;
3839     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3840
3841 #if PLATFORM(GTK)
3842     if (!m_printOperation)
3843         m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3844 #endif
3845 }
3846
3847 void WebPage::endPrinting()
3848 {
3849     drawingArea()->setLayerTreeStateIsFrozen(false);
3850     m_printContext = nullptr;
3851 }
3852
3853 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3854 {
3855     Vector<IntRect> resultPageRects;
3856     double resultTotalScaleFactorForPrinting = 1;
3857     computePagesForPrintingImpl(frameID, printInfo, resultPageRects, resultTotalScaleFactorForPrinting);
3858     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3859 }
3860
3861 void WebPage::computePagesForPrintingImpl(uint64_t frameID, const PrintInfo& printInfo, Vector<WebCore::IntRect>& resultPageRects, double& resultTotalScaleFactorForPrinting)
3862 {
3863     ASSERT(resultPageRects.isEmpty());
3864
3865     beginPrinting(frameID, printInfo);
3866
3867     if (m_printContext) {
3868         resultPageRects = m_printContext->pageRects();
3869         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3870     }
3871 #if PLATFORM(COCOA)
3872     else
3873         computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3874 #endif // PLATFORM(COCOA)
3875
3876     // If we're asked to print, we should actually print at least a blank page.
3877     if (resultPageRects.isEmpty())
3878         resultPageRects.append(IntRect(0, 0, 1, 1));
3879 }
3880
3881 #if PLATFORM(COCOA)
3882 void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, uint64_t callbackID)
3883 {
3884     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3885     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3886
3887     RefPtr<WebImage> image;
3888
3889 #if USE(CG)
3890     if (coreFrame) {
3891 #if PLATFORM(MAC)
3892         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3893 #else
3894         ASSERT(coreFrame->document()->printing());
3895 #endif
3896
3897         RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(imageSize, ShareableBitmap::SupportsAlpha);
3898         auto graphicsContext = bitmap->createGraphicsContext();
3899
3900         float printingScale = static_cast<float>(imageSize.width()) / rect.width();
3901         graphicsContext->scale(FloatSize(printingScale, printingScale));
3902
3903 #if PLATFORM(MAC)
3904         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3905             ASSERT(!m_printContext);
3906             graphicsContext->scale(FloatSize(1, -1));
3907             graphicsContext->translate(0, -rect.height());
3908             drawPDFDocument(graphicsContext->platformContext(), pdfDocument.get(), printInfo, rect);
3909         } else
3910 #endif
3911         {
3912             m_printContext->spoolRect(*graphicsContext, rect);
3913         }
3914
3915         image = WebImage::create(bitmap.release());
3916     }
3917 #endif
3918
3919     ShareableBitmap::Handle handle;
3920
3921     if (image)
3922         image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly);
3923
3924     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
3925 }
3926
3927 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3928 {
3929     RetainPtr<CFMutableDataRef> pdfPageData;
3930     drawPagesToPDFImpl(frameID, printInfo, first, count, pdfPageData);
3931     send(Messages::WebPageProxy::DataCallback(IPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3932 }
3933
3934 void WebPage::drawPagesToPDFImpl(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, RetainPtr<CFMutableDataRef>& pdfPageData)
3935 {
3936     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3937     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3938
3939     pdfPageData = adoptCF(CFDataCreateMutable(0, 0));
3940
3941 #if USE(CG)
3942     if (coreFrame) {
3943
3944 #if PLATFORM(MAC)
3945         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3946 #else
3947         ASSERT(coreFrame->document()->printing());
3948 #endif
3949
3950         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3951         RetainPtr<CGDataConsumerRef> pdfDataConsumer = adoptCF(CGDataConsumerCreateWithCFData(pdfPageData.get()));
3952
3953         CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3954         RetainPtr<CGContextRef> context = adoptCF(CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3955
3956 #if PLATFORM(MAC)
3957         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3958             ASSERT(!m_printContext);
3959             drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3960         } else
3961 #endif
3962         {
3963             size_t pageCount = m_printContext->pageCount();
3964             for (uint32_t page = first; page < first + count; ++page) {
3965                 if (page >= pageCount)
3966                     break;
3967
3968                 RetainPtr<CFDictionaryRef> pageInfo = adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3969                 CGPDFContextBeginPage(context.get(), pageInfo.get());
3970
3971                 GraphicsContext ctx(context.get());
3972                 ctx.scale(FloatSize(1, -1));
3973                 ctx.translate(0, -m_printContext->pageRect(page).height());
3974                 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
3975
3976                 CGPDFContextEndPage(context.get());
3977             }
3978         }
3979         CGPDFContextClose(context.get());
3980     }
3981 #endif
3982 }
3983
3984 #elif PLATFORM(GTK)
3985 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3986 {
3987     beginPrinting(frameID, printInfo);
3988     if (m_printContext && m_printOperation) {
3989         m_printOperation->startPrint(m_printContext.get(), callbackID);
3990         return;
3991     }
3992
3993     send(Messages::WebPageProxy::VoidCallback(callbackID));
3994 }
3995
3996 void WebPage::didFinishPrintOperation(const WebCore::ResourceError& error, uint64_t callbackID)
3997 {
3998     send(Messages::WebPageProxy::PrintFinishedCallback(error, callbackID));
3999     m_printOperation = nullptr;
4000 }
4001 #endif
4002
4003 void WebPage::savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size)
4004 {
4005     send(Messages::WebPageProxy::SavePDFToFileInDownloadsFolder(suggestedFilename, originatingURLString, IPC::DataReference(data, size)));
4006 }
4007
4008 #if PLATFORM(COCOA)
4009 void WebPage::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID)
4010 {
4011     send(Messages::WebPageProxy::SavePDFToTemporaryFolderAndOpenWithNativeApplication(suggestedFilename, originatingURLString, IPC::DataReference(data, size), pdfUUID));
4012 }
4013 #endif
4014
4015 void WebPage::addResourceRequest(unsigned long identifier, const WebCore::ResourceRequest& request)
4016 {
4017     if (!request.url().protocolIsInHTTPFamily())
4018         return;
4019
4020     if (m_mainFrameProgressCompleted && !ScriptController::processingUserGesture())
4021         return;
4022
4023     ASSERT(!m_trackedNetworkResourceRequestIdentifiers.contains(identifier));
4024     bool wasEmpty = m_trackedNetworkResourceRequestIdentifiers.isEmpty();
4025     m_trackedNetworkResourceRequestIdentifiers.add(identifier);
4026     if (wasEmpty)
4027         send(Messages::WebPageProxy::SetNetworkRequestsInProgress(true));
4028 }
4029
4030 void WebPage::removeResourceRequest(unsigned long identifier)
4031 {
4032     if (!m_trackedNetworkResourceRequestIdentifiers.remove(identifier))
4033         return;
4034
4035     if (m_trackedNetworkResourceRequestIdentifiers.isEmpty())
4036         send(Messages::WebPageProxy::SetNetworkRequestsInProgress(false));
4037 }
4038
4039 void WebPage::setMediaVolume(float volume)
4040 {
4041     m_page->setMediaVolume(volume);
4042 }
4043
4044 void WebPage::setMuted(bool muted)
4045 {
4046     m_page->setMuted(muted);
4047 }
4048
4049 #if ENABLE(MEDIA_SESSION)
4050 void WebPage::handleMediaEvent(uint32_t eventType)
4051 {
4052     m_page->handleMediaEvent(static_cast<MediaEventType>(eventType));
4053 }
4054 #endif
4055
4056 void WebPage::setMayStartMediaWhenInWindow(bool mayStartMedia)
4057 {
4058     if (mayStartMedia == m_mayStartMediaWhenInWindow)
4059         return;
4060
4061     m_mayStartMediaWhenInWindow = mayStartMedia;
4062     if (m_mayStartMediaWhenInWindow && m_page->isInWindow())
4063         m_setCanStartMediaTimer.startOneShot(0);
4064 }
4065
4066 void WebPage::runModal()
4067 {
4068     if (m_isClosed)
4069         return;
4070     if (m_isRunningModal)
4071         return;
4072
4073     m_isRunningModal = true;
4074     send(Messages::WebPageProxy::RunModal());
4075 #if !ASSERT_DISABLED
4076     Ref<WebPage> protector(*this);
4077 #endif
4078     RunLoop::run();
4079     ASSERT(!m_isRunningModal);
4080 }
4081
4082 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
4083 {
4084     if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
4085         return true;
4086
4087     if (request.url().protocolIs("blob"))
4088         return true;
4089
4090     return platformCanHandleRequest(request);
4091 }
4092
4093 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
4094 void WebPage::commitPageTransitionViewport()
4095 {
4096     m_drawingArea->setLayerTreeStateIsFrozen(false);
4097 }
4098 #endif
4099
4100 #if PLATFORM(COCOA)
4101 void WebPage::handleAlternativeTextUIResult(const String& result)
4102 {
4103     Frame& frame = m_page->focusController().focusedOrMainFrame();
4104     frame.editor().handleAlternativeTextUIResult(result);
4105 }
4106 #endif
4107
4108 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
4109 {
4110     mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time, WebCore::ForceAtClick));
4111 }
4112
4113 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
4114 {
4115     mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time, WebCore::ForceAtClick));
4116 }
4117
4118 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
4119 {
4120     mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time, 0));
4121 }
4122
4123 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
4124 {
4125     Frame& frame = m_page->focusController().focusedOrMainFrame();
4126     if (!frame.editor().canEdit())
4127         return;
4128
4129     Vector<CompositionUnderline> underlines;
4130     underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
4131     frame.editor().setComposition(compositionString, underlines, from, from + length);
4132 }
4133
4134 bool WebPage::hasCompositionForTesting()
4135 {
4136     Frame& frame = m_page->focusController().focusedOrMainFrame();
4137     return frame.editor().hasComposition();
4138 }
4139
4140 void WebPage::confirmCompositionForTesting(const String& compositionString)
4141 {
4142     Frame& frame = m_page->focusController().focusedOrMainFrame();
4143     if (!frame.editor().canEdit())
4144         return;
4145
4146     if (compositionString.isNull())
4147         frame.editor().confirmComposition();
4148     frame.editor().confirmComposition(compositionString);
4149 }
4150
4151 void WebPage::wheelEventHandlersChanged(bool hasHandlers)
4152 {
4153     if (m_hasWheelEventHandlers == hasHandlers)
4154         return;
4155
4156     m_hasWheelEventHandlers = hasHandlers;
4157     recomputeShortCircuitHorizontalWheelEventsState();
4158 }
4159
4160 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
4161 {
4162     if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
4163         return scrollbar->enabled();
4164
4165     return false;
4166 }
4167
4168 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
4169 {
4170     if (FrameView* frameView = mainFrame->view()) {
4171         if (hasEnabledHorizontalScrollbar(frameView))
4172             return true;
4173     }
4174
4175     for (Frame* frame = mainFrame; frame; frame = frame->tree().traverseNext()) {
4176         FrameView* frameView = frame->view();