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