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