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