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