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