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