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