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