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