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