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