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