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