bbcc65fe457c94caec1b26861a3dff255ae2e5e3
[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_hasWheelEventHandlers(false)
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     settings.setAntialiasedFontDilationEnabled(store.getBoolValueForKey(WebPreferencesKey::antialiasedFontDilationEnabledKey()));
2818     
2819     settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey()));
2820
2821     settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2822
2823 #if ENABLE(MEDIA_SOURCE)
2824     settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2825 #endif
2826
2827     settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2828
2829     settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2830     settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2831     settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2832     settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2833
2834     settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2835     settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2836     
2837     settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2838     settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2839
2840     settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2841
2842     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true);
2843
2844 #if PLATFORM(IOS)
2845     settings.setUseImageDocumentForSubframePDF(true);
2846 #endif
2847
2848     settings.setLongMousePressEnabled(store.getBoolValueForKey(WebPreferencesKey::longMousePressEnabledKey()));
2849
2850 #if ENABLE(GAMEPAD)
2851     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey()));
2852 #endif
2853
2854 #if ENABLE(SERVICE_CONTROLS)
2855     settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey()));
2856 #endif
2857
2858     bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey());
2859     if (m_processSuppressionEnabled != processSuppressionEnabled) {
2860         m_processSuppressionEnabled = processSuppressionEnabled;
2861         updateUserActivity();
2862     }
2863
2864     platformPreferencesDidChange(store);
2865
2866     if (m_drawingArea)
2867         m_drawingArea->updatePreferences(store);
2868
2869 #if PLATFORM(IOS)
2870     m_viewportConfiguration.setCanIgnoreScalingConstraints(store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey()));
2871     m_viewportConfiguration.setForceAlwaysUserScalable(store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey()));
2872 #endif
2873 }
2874
2875 #if PLATFORM(COCOA)
2876 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2877 {
2878     layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2879     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2880     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2881     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2882 #if PLATFORM(IOS)
2883     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2884     layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale());
2885     layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale());
2886     layerTransaction.setAllowsUserScaling(allowsUserScaling());
2887 #endif
2888 #if PLATFORM(MAC)
2889     layerTransaction.setScrollPosition(corePage()->mainFrame().view()->scrollPosition());
2890 #endif
2891 }
2892
2893 void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp)
2894 {
2895 #if PLATFORM(IOS)
2896     if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) {
2897         std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp;
2898         m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero();
2899
2900         m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20));
2901     }
2902 #else
2903     UNUSED_PARAM(timestamp);
2904 #endif
2905 }
2906 #endif
2907
2908 WebInspector* WebPage::inspector()
2909 {
2910     if (m_isClosed)
2911         return nullptr;
2912     if (!m_inspector)
2913         m_inspector = WebInspector::create(this);
2914     return m_inspector.get();
2915 }
2916
2917 WebInspectorUI* WebPage::inspectorUI()
2918 {
2919     if (m_isClosed)
2920         return nullptr;
2921     if (!m_inspectorUI)
2922         m_inspectorUI = WebInspectorUI::create(this);
2923     return m_inspectorUI.get();
2924 }
2925
2926 #if PLATFORM(IOS)
2927 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
2928 {
2929     if (!m_videoFullscreenManager)
2930         m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
2931     return m_videoFullscreenManager.get();
2932 }
2933 #endif
2934
2935 #if ENABLE(FULLSCREEN_API)
2936 WebFullScreenManager* WebPage::fullScreenManager()
2937 {
2938     if (!m_fullScreenManager)
2939         m_fullScreenManager = WebFullScreenManager::create(this);
2940     return m_fullScreenManager.get();
2941 }
2942 #endif
2943
2944 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2945 {
2946     if (m_notificationPermissionRequestManager)
2947         return m_notificationPermissionRequestManager.get();
2948
2949     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2950     return m_notificationPermissionRequestManager.get();
2951 }
2952
2953 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
2954 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2955 {
2956     Node* node = evt->target()->toNode();
2957     ASSERT(node);
2958     Frame* frame = node->document().frame();
2959     ASSERT(frame);
2960
2961     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2962     if (!keyEvent)
2963         return false;
2964
2965     Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
2966
2967     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2968         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2969         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2970         // (e.g. Tab that inserts a Tab character, or Enter).
2971         return !command.isTextInsertion() && command.execute(evt);
2972     }
2973
2974     if (command.execute(evt))
2975         return true;
2976
2977     // Don't allow text insertion for nodes that cannot edit.
2978     if (!frame->editor().canEdit())
2979         return false;
2980
2981     // Don't insert null or control characters as they can result in unexpected behaviour
2982     if (evt->charCode() < ' ')
2983         return false;
2984
2985     return frame->editor().insertText(evt->keyEvent()->text(), evt);
2986 }
2987 #endif
2988
2989 #if ENABLE(DRAG_SUPPORT)
2990
2991 #if PLATFORM(GTK)
2992 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2993 {
2994     if (!m_page) {
2995         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
2996         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2997         data->deref();
2998         return;
2999     }
3000
3001     switch (action) {
3002     case DragControllerActionEntered: {
3003         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3004         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3005         break;
3006     }
3007     case DragControllerActionUpdated: {
3008         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3009         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3010         break;
3011     }
3012     case DragControllerActionExited:
3013         m_page->dragController().dragExited(dragData);
3014         break;
3015
3016     case DragControllerActionPerformDragOperation: {
3017         m_page->dragController().performDragOperation(dragData);
3018         break;
3019     }
3020
3021     default:
3022         ASSERT_NOT_REACHED();
3023     }
3024     // DragData does not delete its platformData so we need to do that here.
3025     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
3026     data->deref();
3027 }
3028
3029 #else
3030 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)
3031 {
3032     if (!m_page) {
3033         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0));
3034         return;
3035     }
3036
3037     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
3038     switch (action) {
3039     case DragControllerActionEntered: {
3040         DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData);
3041         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3042         break;
3043
3044     }
3045     case DragControllerActionUpdated: {
3046         DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData);
3047         send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted()));
3048         break;
3049     }
3050     case DragControllerActionExited:
3051         m_page->dragController().dragExited(dragData);
3052         break;
3053         
3054     case DragControllerActionPerformDragOperation: {
3055         ASSERT(!m_pendingDropSandboxExtension);
3056
3057         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
3058         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
3059             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
3060                 m_pendingDropExtensionsForFileUpload.append(extension);
3061         }
3062
3063         m_page->dragController().performDragOperation(dragData);
3064
3065         // If we started loading a local file, the sandbox extension tracker would have adopted this
3066         // pending drop sandbox extension. If not, we'll play it safe and clear it.
3067         m_pendingDropSandboxExtension = nullptr;
3068
3069         m_pendingDropExtensionsForFileUpload.clear();
3070         break;
3071     }
3072
3073     default:
3074         ASSERT_NOT_REACHED();
3075     }
3076 }
3077 #endif
3078
3079 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
3080 {
3081     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
3082     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
3083
3084     m_page->dragController().dragEnded();
3085     FrameView* view = m_page->mainFrame().view();
3086     if (!view)
3087         return;
3088     // FIXME: These are fake modifier keys here, but they should be real ones instead.
3089     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
3090     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
3091 }
3092
3093 void WebPage::willPerformLoadDragDestinationAction()
3094 {
3095     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
3096 }
3097
3098 void WebPage::mayPerformUploadDragDestinationAction()
3099 {
3100     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
3101         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
3102     m_pendingDropExtensionsForFileUpload.clear();
3103 }
3104     
3105 #endif // ENABLE(DRAG_SUPPORT)
3106
3107 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
3108 {
3109     return m_undoStepMap.get(stepID);
3110 }
3111
3112 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
3113 {
3114     m_undoStepMap.set(stepID, entry);
3115 }
3116
3117 void WebPage::removeWebEditCommand(uint64_t stepID)
3118 {
3119     m_undoStepMap.remove(stepID);
3120 }
3121
3122 void WebPage::unapplyEditCommand(uint64_t stepID)
3123 {
3124     WebUndoStep* step = webUndoStep(stepID);
3125     if (!step)
3126         return;
3127
3128     step->step()->unapply();
3129 }
3130
3131 void WebPage::reapplyEditCommand(uint64_t stepID)
3132 {
3133     WebUndoStep* step = webUndoStep(stepID);
3134     if (!step)
3135         return;
3136
3137     m_isInRedo = true;
3138     step->step()->reapply();
3139     m_isInRedo = false;
3140 }
3141
3142 void WebPage::didRemoveEditCommand(uint64_t commandID)
3143 {
3144     removeWebEditCommand(commandID);
3145 }
3146
3147 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
3148 {
3149     m_activePopupMenu = menu;
3150 }
3151
3152 #if ENABLE(INPUT_TYPE_COLOR)
3153 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
3154 {
3155     m_activeColorChooser = colorChooser;
3156 }
3157
3158 void WebPage::didEndColorPicker()
3159 {
3160     m_activeColorChooser->didEndChooser();
3161 }
3162
3163 void WebPage::didChooseColor(const WebCore::Color& color)
3164 {
3165     m_activeColorChooser->didChooseColor(color);
3166 }
3167 #endif
3168
3169 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
3170 {
3171     m_activeOpenPanelResultListener = openPanelResultListener;
3172 }
3173
3174 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
3175 {
3176     return m_page->findString(target, options);
3177 }
3178
3179 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
3180 {
3181     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
3182 }
3183
3184 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3185 {
3186     m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3187 }
3188
3189 void WebPage::getImageForFindMatch(uint32_t matchIndex)
3190 {
3191     m_findController.getImageForFindMatch(matchIndex);
3192 }
3193
3194 void WebPage::selectFindMatch(uint32_t matchIndex)
3195 {
3196     m_findController.selectFindMatch(matchIndex);
3197 }
3198
3199 void WebPage::hideFindUI()
3200 {
3201     m_findController.hideFindUI();
3202 }
3203
3204 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
3205 {
3206     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
3207 }
3208
3209 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
3210 {
3211     changeSelectedIndex(newIndex);
3212     m_activePopupMenu = 0;
3213 }
3214
3215 void WebPage::changeSelectedIndex(int32_t index)
3216 {
3217     if (!m_activePopupMenu)
3218         return;
3219
3220     m_activePopupMenu->didChangeSelectedIndex(index);
3221 }
3222
3223 #if PLATFORM(IOS)
3224 void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData)
3225 {
3226     if (!m_activeOpenPanelResultListener)
3227         return;
3228
3229     RefPtr<Icon> icon;
3230     if (!iconData.isEmpty()) {
3231         RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size()));
3232         RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get()));
3233         RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault));
3234         icon = Icon::createIconForImage(imageRef.get());
3235     }
3236
3237     m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get());
3238     m_activeOpenPanelResultListener = nullptr;
3239 }
3240 #endif
3241
3242 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3243 {
3244     if (!m_activeOpenPanelResultListener)
3245         return;
3246
3247     m_activeOpenPanelResultListener->didChooseFiles(files);
3248     m_activeOpenPanelResultListener = 0;
3249 }
3250
3251 void WebPage::didCancelForOpenPanel()
3252 {
3253     m_activeOpenPanelResultListener = 0;
3254 }
3255
3256 #if ENABLE(SANDBOX_EXTENSIONS)
3257 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3258 {
3259     SandboxExtension::create(handle)->consumePermanently();
3260 }
3261 #endif
3262
3263 #if ENABLE(GEOLOCATION)
3264 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3265 {
3266     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3267 }
3268 #endif
3269
3270 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3271 {
3272     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3273 }
3274
3275 #if ENABLE(MEDIA_STREAM)
3276 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed)
3277 {
3278     m_userMediaPermissionRequestManager.didReceiveUserMediaPermissionDecision(userMediaID, allowed);
3279 }
3280 #endif
3281
3282 #if !PLATFORM(IOS)
3283 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3284 {
3285     Frame& frame = m_page->focusController().focusedOrMainFrame();
3286     frame.editor().advanceToNextMisspelling(startBeforeSelection);
3287 }
3288 #endif
3289
3290 void WebPage::changeSpellingToWord(const String& word)
3291 {
3292     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3293 }
3294
3295 void WebPage::unmarkAllMisspellings()
3296 {
3297     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3298         if (Document* document = frame->document())
3299             document->markers().removeMarkers(DocumentMarker::Spelling);
3300     }
3301 }
3302
3303 void WebPage::unmarkAllBadGrammar()
3304 {
3305     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3306         if (Document* document = frame->document())
3307             document->markers().removeMarkers(DocumentMarker::Grammar);
3308     }
3309 }
3310
3311 #if USE(APPKIT)
3312 void WebPage::uppercaseWord()
3313 {
3314     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3315 }
3316
3317 void WebPage::lowercaseWord()
3318 {
3319     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3320 }
3321
3322 void WebPage::capitalizeWord()
3323 {
3324     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3325 }
3326 #endif
3327     
3328 void WebPage::setTextForActivePopupMenu(int32_t index)
3329 {
3330     if (!m_activePopupMenu)
3331         return;
3332
3333     m_activePopupMenu->setTextForIndex(index);
3334 }
3335
3336 #if PLATFORM(GTK)
3337 void WebPage::failedToShowPopupMenu()
3338 {
3339     if (!m_activePopupMenu)
3340         return;
3341
3342     m_activePopupMenu->client()->popupDidHide();
3343 }
3344 #endif
3345
3346 #if ENABLE(CONTEXT_MENUS)
3347 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3348 {
3349     if (!m_contextMenu)
3350         return;
3351
3352     m_contextMenu->itemSelected(item);
3353     m_contextMenu = 0;
3354 }
3355 #endif
3356
3357 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3358 {
3359     bool selectReplacement = true;
3360     bool smartReplace = false;
3361     return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3362 }
3363
3364 #if !PLATFORM(IOS)
3365 void WebPage::clearSelection()
3366 {
3367     m_page->focusController().focusedOrMainFrame().selection().clear();
3368 }
3369 #endif
3370
3371 void WebPage::restoreSelectionInFocusedEditableElement()
3372 {
3373     Frame& frame = m_page->focusController().focusedOrMainFrame();
3374     if (!frame.selection().isNone())
3375         return;
3376
3377     if (auto document = frame.document()) {
3378         if (auto element = document->focusedElement())
3379             element->updateFocusAppearance(true /* restoreSelection */);
3380     }
3381 }
3382
3383 bool WebPage::mainFrameHasCustomContentProvider() const
3384 {
3385     if (Frame* frame = mainFrame()) {
3386         WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3387         ASSERT(webFrameLoaderClient);
3388         return webFrameLoaderClient->frameHasCustomContentProvider();
3389     }
3390
3391     return false;
3392 }
3393
3394 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3395 {
3396     m_mimeTypesWithCustomContentProviders.add(mimeType);
3397 }
3398
3399 void WebPage::updateMainFrameScrollOffsetPinning()
3400 {
3401     Frame& frame = m_page->mainFrame();
3402     IntPoint scrollPosition = frame.view()->scrollPosition();
3403     IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3404     IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3405
3406     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3407     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3408     bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3409     bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3410
3411     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3412         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3413         
3414         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3415         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3416         m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3417         m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3418     }
3419 }
3420
3421 void WebPage::mainFrameDidLayout()
3422 {
3423     unsigned pageCount = m_page->pageCount();
3424     if (pageCount != m_cachedPageCount) {
3425         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3426         m_cachedPageCount = pageCount;
3427     }
3428
3429 #if PLATFORM(MAC)
3430     m_viewGestureGeometryCollector.mainFrameDidLayout();
3431 #endif
3432 #if PLATFORM(IOS)
3433     if (FrameView* frameView = mainFrameView()) {
3434         IntSize newContentSize = frameView->contentsSize();
3435         if (m_viewportConfiguration.contentsSize() != newContentSize) {
3436             m_viewportConfiguration.setContentsSize(newContentSize);
3437             viewportConfigurationChanged();
3438         }
3439     }
3440     m_findController.redraw();
3441 #endif
3442 }
3443
3444 void WebPage::addPluginView(PluginView* pluginView)
3445 {
3446     ASSERT(!m_pluginViews.contains(pluginView));
3447
3448     m_pluginViews.add(pluginView);
3449     m_hasSeenPlugin = true;
3450 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3451     LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3452     m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3453 #endif
3454 }
3455
3456 void WebPage::removePluginView(PluginView* pluginView)
3457 {
3458     ASSERT(m_pluginViews.contains(pluginView));
3459
3460     m_pluginViews.remove(pluginView);
3461 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3462     LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3463 #endif
3464 }
3465
3466 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3467 {
3468 #if PLATFORM(COCOA)
3469     m_hasCachedWindowFrame = false;
3470 #endif
3471     send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3472 }
3473
3474 #if PLATFORM(COCOA)
3475 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3476 {
3477     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3478     m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3479     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3480     m_accessibilityPosition = accessibilityViewCoordinates;
3481     
3482     // Tell all our plug-in views that the window and view frames have changed.
3483     for (auto* pluginView : m_pluginViews)
3484         pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3485
3486     m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3487 }
3488 #endif
3489
3490 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3491 {
3492     m_mainFrameIsScrollable = isScrollable;
3493     m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3494
3495     if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3496         frameView->setCanHaveScrollbars(isScrollable);
3497         frameView->setProhibitsScrolling(!isScrollable);
3498     }
3499 }
3500
3501 bool WebPage::windowIsFocused() const
3502 {
3503     return m_page->focusController().isActive();
3504 }
3505
3506 bool WebPage::windowAndWebPageAreFocused() const
3507 {
3508     if (!isVisible())
3509         return false;
3510
3511     return m_page->focusController().isFocused() && m_page->focusController().isActive();
3512 }
3513
3514 void WebPage::didReceiveMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder)
3515 {
3516 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
3517     if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
3518         if (m_drawingArea)
3519             m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
3520         return;
3521     }
3522 #endif
3523
3524     if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
3525         if (WebInspector* inspector = this->inspector())
3526             inspector->didReceiveMessage(connection, decoder);
3527         return;
3528     }
3529
3530     if (decoder.messageReceiverName() == Messages::WebInspectorUI::messageReceiverName()) {
3531         if (WebInspectorUI* inspectorUI = this->inspectorUI())
3532             inspectorUI->didReceiveMessage(connection, decoder);
3533         return;
3534     }
3535
3536 #if ENABLE(FULLSCREEN_API)
3537     if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
3538         fullScreenManager()->didReceiveMessage(connection, decoder);
3539         return;
3540     }
3541 #endif
3542
3543     didReceiveWebPageMessage(connection, decoder);
3544 }
3545
3546 void WebPage::didReceiveSyncMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder)
3547 {   
3548     didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
3549 }
3550     
3551 InjectedBundleBackForwardList* WebPage::backForwardList()
3552 {
3553     if (!m_backForwardList)
3554         m_backForwardList = InjectedBundleBackForwardList::create(this);
3555     return m_backForwardList.get();
3556 }
3557
3558 #if ENABLE(ASYNC_SCROLLING)
3559 ScrollingCoordinator* WebPage::scrollingCoordinator() const
3560 {
3561     return m_page->scrollingCoordinator();
3562 }
3563 #endif
3564
3565 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3566 {
3567     invalidate();
3568 }
3569
3570 void WebPage::SandboxExtensionTracker::invalidate()
3571 {
3572     m_pendingProvisionalSandboxExtension = nullptr;
3573
3574     if (m_provisionalSandboxExtension) {
3575         m_provisionalSandboxExtension->revoke();
3576         m_provisionalSandboxExtension = nullptr;
3577     }
3578
3579     if (m_committedSandboxExtension) {
3580         m_committedSandboxExtension->revoke();
3581         m_committedSandboxExtension = nullptr;
3582     }
3583 }
3584
3585 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3586 {
3587     setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3588 }
3589
3590 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3591 {
3592     ASSERT_UNUSED(frame, frame->isMainFrame());
3593
3594     setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3595 }
3596
3597 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3598 {
3599     m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;    
3600 }
3601
3602 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3603 {
3604     ASSERT(frame->isMainFrame());
3605
3606     FrameLoader& frameLoader = frame->coreFrame()->loader();
3607     FrameLoadType frameLoadType = frameLoader.loadType();
3608
3609     // If the page is being reloaded, it should reuse whatever extension is committed.
3610     if (frameLoadType == FrameLoadType::Reload || frameLoadType == FrameLoadType::ReloadFromOrigin)
3611         return true;
3612
3613     DocumentLoader* documentLoader = frameLoader.documentLoader();
3614     DocumentLoader* provisionalDocumentLoader = frameLoader.provisionalDocumentLoader();
3615     if (!documentLoader || !provisionalDocumentLoader)
3616         return false;
3617
3618     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3619         return true;
3620
3621     return false;
3622 }
3623
3624 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3625 {
3626     if (!frame->isMainFrame())
3627         return;
3628
3629     // We should only reuse the commited sandbox extension if it is not null. It can be
3630     // null if the last load was for an error page.
3631     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame))
3632         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension;
3633
3634     ASSERT(!m_provisionalSandboxExtension);
3635
3636     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3637     if (!m_provisionalSandboxExtension)
3638         return;
3639
3640     ASSERT(!m_provisionalSandboxExtension || frame->coreFrame()->loader().provisionalDocumentLoader()->url().isLocalFile());
3641
3642     m_provisionalSandboxExtension->consume();
3643 }
3644
3645 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3646 {
3647     if (!frame->isMainFrame())
3648         return;
3649
3650     if (m_committedSandboxExtension)
3651         m_committedSandboxExtension->revoke();
3652
3653     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3654
3655     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started.
3656     // This extension is not cleared, because it does not pertain to the failed load, and will be needed.
3657 }
3658
3659 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3660 {
3661     if (!frame->isMainFrame())
3662         return;
3663
3664     if (!m_provisionalSandboxExtension)
3665         return;
3666
3667     m_provisionalSandboxExtension->revoke();
3668     m_provisionalSandboxExtension = nullptr;
3669
3670     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started
3671     // (notably, if the current one fails because the new one cancels it). This extension is not cleared,
3672     // because it does not pertain to the failed load, and will be needed.
3673 }
3674
3675 bool WebPage::hasLocalDataForURL(const URL& url)
3676 {
3677     if (url.isLocalFile())
3678         return true;
3679
3680     DocumentLoader* documentLoader = m_page->mainFrame().loader().documentLoader();
3681     if (documentLoader && documentLoader->subresource(url))
3682         return true;
3683
3684     return platformHasLocalDataForURL(url);
3685 }
3686
3687 void WebPage::setCustomTextEncodingName(const String& encoding)
3688 {
3689     m_page->mainFrame().loader().reloadWithOverrideEncoding(encoding);
3690 }
3691
3692 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3693 {
3694     WebBackForwardListProxy::removeItem(itemID);
3695 }
3696
3697 #if PLATFORM(COCOA)
3698
3699 bool WebPage::isSpeaking()
3700 {
3701     bool result;
3702     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3703 }
3704
3705 void WebPage::speak(const String& string)
3706 {
3707     send(Messages::WebPageProxy::Speak(string));
3708 }
3709
3710 void WebPage::stopSpeaking()
3711 {
3712     send(Messages::WebPageProxy::StopSpeaking());
3713 }
3714
3715 #endif
3716
3717 #if PLATFORM(MAC)
3718 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3719 {
3720     Document* document = coreFrame->document();
3721     if (!is<PluginDocument>(document))
3722         return nullptr;
3723
3724     PluginView* pluginView = static_cast<PluginView*>(downcast<PluginDocument>(*document).pluginWidget());
3725     if (!pluginView)
3726         return nullptr;
3727
3728     return pluginView->pdfDocumentForPrinting();
3729 }
3730 #endif // PLATFORM(MAC)
3731
3732 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3733 {
3734     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3735     if (!frame)
3736         return;
3737
3738     Frame* coreFrame = frame->coreFrame();
3739     if (!coreFrame)
3740         return;
3741
3742 #if PLATFORM(MAC)
3743     if (pdfDocumentForPrintingFrame(coreFrame))
3744         return;
3745 #endif // PLATFORM(MAC)
3746
3747     if (!m_printContext)
3748         m_printContext = std::make_unique<PrintContext>(coreFrame);
3749
3750     drawingArea()->setLayerTreeStateIsFrozen(true);
3751     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3752
3753     float fullPageHeight;
3754     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3755
3756 #if PLATFORM(GTK)
3757     if (!m_printOperation)
3758         m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3759 #endif
3760 }
3761
3762 void WebPage::endPrinting()
3763 {
3764     drawingArea()->setLayerTreeStateIsFrozen(false);
3765     m_printContext = nullptr;
3766 }
3767
3768 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3769 {
3770     Vector<IntRect> resultPageRects;
3771     double resultTotalScaleFactorForPrinting = 1;
3772     computePagesForPrintingImpl(frameID, printInfo, resultPageRects, resultTotalScaleFactorForPrinting);
3773     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3774 }
3775
3776 void WebPage::computePagesForPrintingImpl(uint64_t frameID, const PrintInfo& printInfo, Vector<WebCore::IntRect>& resultPageRects, double& resultTotalScaleFactorForPrinting)
3777 {
3778     ASSERT(resultPageRects.isEmpty());
3779
3780     beginPrinting(frameID, printInfo);
3781
3782     if (m_printContext) {
3783         resultPageRects = m_printContext->pageRects();
3784         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3785     }
3786 #if PLATFORM(COCOA)
3787     else
3788         computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3789 #endif // PLATFORM(COCOA)
3790
3791     // If we're asked to print, we should actually print at least a blank page.
3792     if (resultPageRects.isEmpty())
3793         resultPageRects.append(IntRect(0, 0, 1, 1));
3794 }
3795
3796 #if PLATFORM(COCOA)
3797 void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, uint64_t callbackID)
3798 {
3799     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3800     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3801
3802     RefPtr<WebImage> image;
3803
3804 #if USE(CG)
3805     if (coreFrame) {
3806 #if PLATFORM(MAC)
3807         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3808 #else
3809         ASSERT(coreFrame->document()->printing());
3810 #endif
3811
3812         RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(imageSize, ShareableBitmap::SupportsAlpha);
3813         auto graphicsContext = bitmap->createGraphicsContext();
3814
3815         float printingScale = static_cast<float>(imageSize.width()) / rect.width();
3816         graphicsContext->scale(FloatSize(printingScale, printingScale));
3817
3818 #if PLATFORM(MAC)
3819         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3820             ASSERT(!m_printContext);
3821             graphicsContext->scale(FloatSize(1, -1));
3822             graphicsContext->translate(0, -rect.height());
3823             drawPDFDocument(graphicsContext->platformContext(), pdfDocument.get(), printInfo, rect);
3824         } else
3825 #endif
3826         {
3827             m_printContext->spoolRect(*graphicsContext, rect);
3828         }
3829
3830         image = WebImage::create(bitmap.release());
3831     }
3832 #endif
3833
3834     ShareableBitmap::Handle handle;
3835
3836     if (image)
3837         image->bitmap()->createHandle(handle, SharedMemory::ReadOnly);
3838
3839     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
3840 }
3841
3842 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3843 {
3844     RetainPtr<CFMutableDataRef> pdfPageData;
3845     drawPagesToPDFImpl(frameID, printInfo, first, count, pdfPageData);
3846     send(Messages::WebPageProxy::DataCallback(IPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3847 }
3848
3849 void WebPage::drawPagesToPDFImpl(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, RetainPtr<CFMutableDataRef>& pdfPageData)
3850 {
3851     WebFrame* frame = WebProcess::singleton().webFrame(frameID);
3852     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3853
3854     pdfPageData = adoptCF(CFDataCreateMutable(0, 0));
3855
3856 #if USE(CG)
3857     if (coreFrame) {
3858
3859 #if PLATFORM(MAC)
3860         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3861 #else
3862         ASSERT(coreFrame->document()->printing());
3863 #endif
3864
3865         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3866         RetainPtr<CGDataConsumerRef> pdfDataConsumer = adoptCF(CGDataConsumerCreateWithCFData(pdfPageData.get()));
3867
3868         CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3869         RetainPtr<CGContextRef> context = adoptCF(CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3870
3871 #if PLATFORM(MAC)
3872         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3873             ASSERT(!m_printContext);
3874             drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3875         } else
3876 #endif
3877         {
3878             size_t pageCount = m_printContext->pageCount();
3879             for (uint32_t page = first; page < first + count; ++page) {
3880                 if (page >= pageCount)
3881                     break;
3882
3883                 RetainPtr<CFDictionaryRef> pageInfo = adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3884                 CGPDFContextBeginPage(context.get(), pageInfo.get());
3885
3886                 GraphicsContext ctx(context.get());
3887                 ctx.scale(FloatSize(1, -1));
3888                 ctx.translate(0, -m_printContext->pageRect(page).height());
3889                 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
3890
3891                 CGPDFContextEndPage(context.get());
3892             }
3893         }
3894         CGPDFContextClose(context.get());
3895     }
3896 #endif
3897 }
3898
3899 #elif PLATFORM(GTK)
3900 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3901 {
3902     beginPrinting(frameID, printInfo);
3903     if (m_printContext && m_printOperation) {
3904         m_printOperation->startPrint(m_printContext.get(), callbackID);
3905         return;
3906     }
3907
3908     send(Messages::WebPageProxy::VoidCallback(callbackID));
3909 }
3910
3911 void WebPage::didFinishPrintOperation(const WebCore::ResourceError& error, uint64_t callbackID)
3912 {
3913     send(Messages::WebPageProxy::PrintFinishedCallback(error, callbackID));
3914     m_printOperation = nullptr;
3915 }
3916 #endif
3917
3918 void WebPage::savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size)
3919 {
3920     send(Messages::WebPageProxy::SavePDFToFileInDownloadsFolder(suggestedFilename, originatingURLString, IPC::DataReference(data, size)));
3921 }
3922
3923 #if PLATFORM(COCOA)
3924 void WebPage::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID)
3925 {
3926     send(Messages::WebPageProxy::SavePDFToTemporaryFolderAndOpenWithNativeApplication(suggestedFilename, originatingURLString, IPC::DataReference(data, size), pdfUUID));
3927 }
3928 #endif
3929
3930 void WebPage::addResourceRequest(unsigned long identifier, const WebCore::ResourceRequest& request)
3931 {
3932     if (!request.url().protocolIsInHTTPFamily())
3933         return;
3934
3935     if (m_mainFrameProgressCompleted && !ScriptController::processingUserGesture())
3936         return;
3937
3938     ASSERT(!m_trackedNetworkResourceRequestIdentifiers.contains(identifier));
3939     bool wasEmpty = m_trackedNetworkResourceRequestIdentifiers.isEmpty();
3940     m_trackedNetworkResourceRequestIdentifiers.add(identifier);
3941     if (wasEmpty)
3942         send(Messages::WebPageProxy::SetNetworkRequestsInProgress(true));
3943 }
3944
3945 void WebPage::removeResourceRequest(unsigned long identifier)
3946 {
3947     if (!m_trackedNetworkResourceRequestIdentifiers.remove(identifier))
3948         return;
3949
3950     if (m_trackedNetworkResourceRequestIdentifiers.isEmpty())
3951         send(Messages::WebPageProxy::SetNetworkRequestsInProgress(false));
3952 }
3953
3954 void WebPage::setMediaVolume(float volume)
3955 {
3956     m_page->setMediaVolume(volume);
3957 }
3958
3959 void WebPage::setMuted(bool muted)
3960 {
3961     m_page->setMuted(muted);
3962 }
3963
3964 void WebPage::setMayStartMediaWhenInWindow(bool mayStartMedia)
3965 {
3966     if (mayStartMedia == m_mayStartMediaWhenInWindow)
3967         return;
3968
3969     m_mayStartMediaWhenInWindow = mayStartMedia;
3970     if (m_mayStartMediaWhenInWindow && m_page->isInWindow())
3971         m_setCanStartMediaTimer.startOneShot(0);
3972 }
3973
3974 void WebPage::runModal()
3975 {
3976     if (m_isClosed)
3977         return;
3978     if (m_isRunningModal)
3979         return;
3980
3981     m_isRunningModal = true;
3982     send(Messages::WebPageProxy::RunModal());
3983 #if !ASSERT_DISABLED
3984     Ref<WebPage> protector(*this);
3985 #endif
3986     RunLoop::run();
3987     ASSERT(!m_isRunningModal);
3988 }
3989
3990 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
3991 {
3992     if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
3993         return true;
3994
3995     if (request.url().protocolIs("blob"))
3996         return true;
3997
3998     return platformCanHandleRequest(request);
3999 }
4000
4001 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
4002 void WebPage::commitPageTransitionViewport()
4003 {
4004     m_drawingArea->setLayerTreeStateIsFrozen(false);
4005 }
4006 #endif
4007
4008 #if PLATFORM(COCOA)
4009 void WebPage::handleAlternativeTextUIResult(const String& result)
4010 {
4011     Frame& frame = m_page->focusController().focusedOrMainFrame();
4012     frame.editor().handleAlternativeTextUIResult(result);
4013 }
4014 #endif
4015
4016 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
4017 {
4018     mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
4019 }
4020
4021 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
4022 {
4023     mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
4024 }
4025
4026 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
4027 {
4028     mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
4029 }
4030
4031 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
4032 {
4033     Frame& frame = m_page->focusController().focusedOrMainFrame();
4034     if (!frame.editor().canEdit())
4035         return;
4036
4037     Vector<CompositionUnderline> underlines;
4038     underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
4039     frame.editor().setComposition(compositionString, underlines, from, from + length);
4040 }
4041
4042 bool WebPage::hasCompositionForTesting()
4043 {
4044     Frame& frame = m_page->focusController().focusedOrMainFrame();
4045     return frame.editor().hasComposition();
4046 }
4047
4048 void WebPage::confirmCompositionForTesting(const String& compositionString)
4049 {
4050     Frame& frame = m_page->focusController().focusedOrMainFrame();
4051     if (!frame.editor().canEdit())
4052         return;
4053
4054     if (compositionString.isNull())
4055         frame.editor().confirmComposition();
4056     frame.editor().confirmComposition(compositionString);
4057 }
4058
4059 void WebPage::wheelEventHandlersChanged(bool hasHandlers)
4060 {
4061     if (m_hasWheelEventHandlers == hasHandlers)
4062         return;
4063
4064     m_hasWheelEventHandlers = hasHandlers;
4065     recomputeShortCircuitHorizontalWheelEventsState();
4066 }
4067
4068 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
4069 {
4070     if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
4071         return scrollbar->enabled();
4072
4073     return false;
4074 }
4075
4076 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
4077 {
4078     if (FrameView* frameView = mainFrame->view()) {
4079         if (hasEnabledHorizontalScrollbar(frameView))
4080             return true;
4081     }
4082
4083     for (Frame* frame = mainFrame; frame; frame = frame->tree().traverseNext()) {
4084         FrameView* frameView = frame->view();
4085         if (!frameView)
4086             continue;
4087
4088         const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
4089         if (!scrollableAreas)
4090             continue;
4091
4092         for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
4093             ScrollableArea* scrollableArea = *it;
4094             if (!scrollableArea->scrollbarsCanBeActive())
4095                 continue;
4096
4097             if (hasEnabledHorizontalScrollbar(scrollableArea))
4098                 return true;
4099         }
4100     }
4101
4102     return false;
4103 }
4104
4105 void WebPage::recomputeShortCircuitHorizontalWheelEventsState()
4106 {
4107     bool canShortCircuitHorizontalWheelEvents = !m_hasWheelEventHandlers;
4108
4109     if (canShortCircuitHorizontalWheelEvents) {
4110         // Check if we have any horizontal scroll bars on the page.
4111         if (pageContainsAnyHorizontalScrollbars(mainFrame()))
4112             canShortCircuitHorizontalWheelEvents = false;
4113     }
4114
4115     if (m_canShortCircuitHorizontalWheelEvents == canShortCircuitHorizontalWheelEvents)
4116         return;
4117
4118     m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents;
4119     send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents));
4120 }
4121
4122 MainFrame* WebPage::mainFrame() const
4123 {
4124     return m_page ? &m_page->mainFrame() : nullptr;
4125 }
4126
4127 FrameView* WebPage::mainFrameView() const
4128 {
4129     if (Frame* frame = mainFrame())
4130         return frame->view();
4131     
4132     return nullptr;
4133 }
4134
4135 void WebPage::setScrollingPerformanceLoggingEnabled(bool enabled)
4136 {
4137     m_scrollingPerformanceLoggingEnabled = enabled;
4138
4139     FrameView* frameView = m_mainFrame->coreFrame()->view();
4140     if (!frameView)
4141         return;
4142
4143     frameView->setScrollingPerformanceLoggingEnabled(enabled);
4144 }
4145
4146 bool WebPage::canPluginHandleResponse(const ResourceResponse& response)
4147 {
4148 #if ENABLE(NETSCAPE_PLUGIN_API)
4149     uint32_t pluginLoadPolicy;
4150     bool allowOnlyApplicationPlugins = !m_mainFrame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin);
4151
4152     uint64_t pluginProcessToken;
4153     String newMIMEType;
4154     String unavailabilityDescription;
4155     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)))
4156         return false;
4157
4158     return pluginLoadPolicy != PluginModuleBlocked && pluginProcessToken;
4159 #else
4160     UNUSED_PARAM(response);
4161     return false;
4162 #endif
4163 }
4164
4165 bool WebPage::shouldUseCustomContentProviderForResponse(const ResourceResponse& response)
4166 {
4167     // If a plug-in exists that claims to support this response, it should take precedence over the custom content provider.
4168     return m_mimeTypesWithCustomContentProviders.contains(response.mimeType()) && !canPluginHandleResponse(response);
4169 }
4170
4171 #if PLATFORM(COCOA)
4172
4173 void WebPage::insertTextAsync(const String& text, const EditingRange& replacementEditingRange, bool registerUndoGroup)
4174 {
4175     Frame& frame = m_page->focusController().focusedOrMainFrame();
4176
4177     if (replacementEditingRange.location != notFound) {