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