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