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