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