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