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