232586b48c192bdfb622f67993df109e01dbb104
[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 "DecoderAdapter.h"
34 #include "DragControllerAction.h"
35 #include "DrawingArea.h"
36 #include "DrawingAreaMessages.h"
37 #include "EditingRange.h"
38 #include "EditorState.h"
39 #include "EventDispatcher.h"
40 #include "InjectedBundle.h"
41 #include "InjectedBundleBackForwardList.h"
42 #include "InjectedBundleUserMessageCoders.h"
43 #include "LayerTreeHost.h"
44 #include "Logging.h"
45 #include "NetscapePlugin.h"
46 #include "NotificationPermissionRequestManager.h"
47 #include "PageBanner.h"
48 #include "PageOverlay.h"
49 #include "PluginProcessAttributes.h"
50 #include "PluginProxy.h"
51 #include "PluginView.h"
52 #include "PrintInfo.h"
53 #include "SessionState.h"
54 #include "ShareableBitmap.h"
55 #include "VisitedLinkTableController.h"
56 #include "WKSharedAPICast.h"
57 #include "WebAlternativeTextClient.h"
58 #include "WebBackForwardListItem.h"
59 #include "WebBackForwardListProxy.h"
60 #include "WebChromeClient.h"
61 #include "WebColorChooser.h"
62 #include "WebContextMenu.h"
63 #include "WebContextMenuClient.h"
64 #include "WebContextMessages.h"
65 #include "WebCoreArgumentCoders.h"
66 #include "WebDocumentLoader.h"
67 #include "WebDragClient.h"
68 #include "WebEditorClient.h"
69 #include "WebEvent.h"
70 #include "WebEventConversion.h"
71 #include "WebFrame.h"
72 #include "WebFrameLoaderClient.h"
73 #include "WebFullScreenManager.h"
74 #include "WebFullScreenManagerMessages.h"
75 #include "WebGeolocationClient.h"
76 #include "WebImage.h"
77 #include "WebInspector.h"
78 #include "WebInspectorClient.h"
79 #include "WebInspectorMessages.h"
80 #include "WebNotificationClient.h"
81 #include "WebOpenPanelResultListener.h"
82 #include "WebPageCreationParameters.h"
83 #include "WebPageGroupProxy.h"
84 #include "WebPageMessages.h"
85 #include "WebPageProxyMessages.h"
86 #include "WebPlugInClient.h"
87 #include "WebPopupMenu.h"
88 #include "WebPreferencesStore.h"
89 #include "WebProcess.h"
90 #include "WebProcessProxyMessages.h"
91 #include "WebProgressTrackerClient.h"
92 #include <JavaScriptCore/APICast.h>
93 #include <WebCore/ArchiveResource.h>
94 #include <WebCore/Chrome.h>
95 #include <WebCore/ContextMenuController.h>
96 #include <WebCore/DatabaseManager.h>
97 #include <WebCore/DocumentFragment.h>
98 #include <WebCore/DocumentLoader.h>
99 #include <WebCore/DocumentMarkerController.h>
100 #include <WebCore/DragController.h>
101 #include <WebCore/DragData.h>
102 #include <WebCore/DragSession.h>
103 #include <WebCore/ElementIterator.h>
104 #include <WebCore/EventHandler.h>
105 #include <WebCore/FocusController.h>
106 #include <WebCore/FormState.h>
107 #include <WebCore/FrameLoadRequest.h>
108 #include <WebCore/FrameLoaderTypes.h>
109 #include <WebCore/FrameView.h>
110 #include <WebCore/HTMLFormElement.h>
111 #include <WebCore/HTMLInputElement.h>
112 #include <WebCore/HTMLPlugInElement.h>
113 #include <WebCore/HTMLPlugInImageElement.h>
114 #include <WebCore/HistoryController.h>
115 #include <WebCore/HistoryItem.h>
116 #include <WebCore/HitTestResult.h>
117 #include <WebCore/JSDOMWindow.h>
118 #include <WebCore/KeyboardEvent.h>
119 #include <WebCore/MIMETypeRegistry.h>
120 #include <WebCore/MainFrame.h>
121 #include <WebCore/MouseEvent.h>
122 #include <WebCore/Page.h>
123 #include <WebCore/PageThrottler.h>
124 #include <WebCore/PlatformKeyboardEvent.h>
125 #include <WebCore/PluginDocument.h>
126 #include <WebCore/PrintContext.h>
127 #include <WebCore/Range.h>
128 #include <WebCore/RenderLayer.h>
129 #include <WebCore/RenderTreeAsText.h>
130 #include <WebCore/RenderView.h>
131 #include <WebCore/ResourceBuffer.h>
132 #include <WebCore/ResourceRequest.h>
133 #include <WebCore/ResourceResponse.h>
134 #include <WebCore/RuntimeEnabledFeatures.h>
135 #include <WebCore/SchemeRegistry.h>
136 #include <WebCore/ScriptController.h>
137 #include <WebCore/SerializedScriptValue.h>
138 #include <WebCore/SessionID.h>
139 #include <WebCore/Settings.h>
140 #include <WebCore/ShadowRoot.h>
141 #include <WebCore/SharedBuffer.h>
142 #include <WebCore/SubframeLoader.h>
143 #include <WebCore/SubstituteData.h>
144 #include <WebCore/TextIterator.h>
145 #include <WebCore/UserInputBridge.h>
146 #include <WebCore/VisiblePosition.h>
147 #include <WebCore/VisibleUnits.h>
148 #include <WebCore/markup.h>
149 #include <bindings/ScriptValue.h>
150 #include <runtime/JSCInlines.h>
151 #include <runtime/JSCJSValue.h>
152 #include <runtime/JSLock.h>
153 #include <wtf/RunLoop.h>
154
155 #if ENABLE(MHTML)
156 #include <WebCore/MHTMLArchive.h>
157 #endif
158
159 #if ENABLE(BATTERY_STATUS)
160 #include "WebBatteryClient.h"
161 #endif
162
163 #if ENABLE(NETWORK_INFO)
164 #include "WebNetworkInfoClient.h"
165 #endif
166
167 #if ENABLE(VIBRATION)
168 #include "WebVibrationClient.h"
169 #endif
170
171 #if ENABLE(PROXIMITY_EVENTS)
172 #include "WebDeviceProximityClient.h"
173 #endif
174
175 #if PLATFORM(COCOA)
176 #include "PDFPlugin.h"
177 #include "RemoteLayerTreeTransaction.h"
178 #include <WebCore/LegacyWebArchive.h>
179 #endif
180
181 #if PLATFORM(GTK)
182 #include <gtk/gtk.h>
183 #include "DataObjectGtk.h"
184 #include "WebPrintOperationGtk.h"
185 #endif
186
187 #if PLATFORM(IOS)
188 #include "WebVideoFullscreenManager.h"
189 #endif
190
191 #ifndef NDEBUG
192 #include <wtf/RefCountedLeakCounter.h>
193 #endif
194
195 #if USE(COORDINATED_GRAPHICS)
196 #include "CoordinatedLayerTreeHostMessages.h"
197 #endif
198
199 using namespace JSC;
200 using namespace WebCore;
201
202 namespace WebKit {
203
204 class SendStopResponsivenessTimer {
205 public:
206     SendStopResponsivenessTimer(WebPage* page)
207         : m_page(page)
208     {
209     }
210     
211     ~SendStopResponsivenessTimer()
212     {
213         m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
214     }
215
216 private:
217     WebPage* m_page;
218 };
219
220 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
221
222 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
223 {
224     RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
225
226     if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
227         WebProcess::shared().injectedBundle()->didCreatePage(page.get());
228
229     return page.release();
230 }
231
232 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
233     : m_pageID(pageID)
234     , m_viewSize(parameters.viewSize)
235     , m_hasSeenPlugin(false)
236     , m_useFixedLayout(false)
237     , m_drawsBackground(true)
238     , m_drawsTransparentBackground(false)
239     , m_isInRedo(false)
240     , m_isClosed(false)
241     , m_tabToLinks(false)
242     , m_asynchronousPluginInitializationEnabled(false)
243     , m_asynchronousPluginInitializationEnabledForAllPlugins(false)
244     , m_artificialPluginInitializationDelayEnabled(false)
245     , m_scrollingPerformanceLoggingEnabled(false)
246     , m_mainFrameIsScrollable(true)
247 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
248     , m_readyToFindPrimarySnapshottedPlugin(false)
249     , m_didFindPrimarySnapshottedPlugin(false)
250     , m_numberOfPrimarySnapshotDetectionAttempts(0)
251     , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired)
252 #endif
253     , m_layerHostingMode(parameters.layerHostingMode)
254 #if PLATFORM(COCOA)
255     , m_pdfPluginEnabled(false)
256     , m_hasCachedWindowFrame(false)
257     , m_viewGestureGeometryCollector(*this)
258 #elif PLATFORM(GTK) && HAVE(ACCESSIBILITY)
259     , m_accessibilityObject(0)
260 #endif
261     , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired)
262     , m_sendDidUpdateViewStateTimer(RunLoop::main(), this, &WebPage::didUpdateViewStateTimerFired)
263     , m_findController(this)
264 #if ENABLE(INPUT_TYPE_COLOR)
265     , m_activeColorChooser(0)
266 #endif
267 #if ENABLE(GEOLOCATION)
268     , m_geolocationPermissionRequestManager(this)
269 #endif
270     , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
271     , m_canRunModal(parameters.canRunModal)
272     , m_isRunningModal(false)
273     , m_cachedMainFrameIsPinnedToLeftSide(false)
274     , m_cachedMainFrameIsPinnedToRightSide(false)
275     , m_cachedMainFrameIsPinnedToTopSide(false)
276     , m_cachedMainFrameIsPinnedToBottomSide(false)
277     , m_canShortCircuitHorizontalWheelEvents(false)
278     , m_numWheelEventHandlers(0)
279     , m_cachedPageCount(0)
280     , m_autoSizingShouldExpandToViewHeight(false)
281 #if ENABLE(CONTEXT_MENUS)
282     , m_isShowingContextMenu(false)
283 #endif
284 #if PLATFORM(IOS)
285     , m_shouldReturnWordAtSelection(false)
286     , m_lastVisibleContentRectUpdateID(0)
287     , m_scaleWasSetByUIProcess(false)
288     , m_userHasChangedPageScaleFactor(false)
289     , m_viewportScreenSize(parameters.viewportScreenSize)
290 #endif
291     , m_inspectorClient(0)
292     , m_backgroundColor(Color::white)
293     , m_maximumRenderingSuppressionToken(0)
294     , m_scrollPinningBehavior(DoNotPin)
295     , m_useAsyncScrolling(false)
296     , m_viewState(parameters.viewState)
297     , m_processSuppressionDisabledByWebPreference("Process suppression is disabled.")
298     , m_pendingNavigationID(0)
299     , m_pageScaleWithoutThumbnailScale(1)
300     , m_thumbnailScale(1)
301 #if ENABLE(WEBGL)
302     , m_systemWebGLPolicy(WebGLAllowCreation)
303 #endif
304 {
305     ASSERT(m_pageID);
306     // FIXME: This is a non-ideal location for this Setting and
307     // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
308     Settings::setDefaultMinDOMTimerInterval(0.004);
309
310     Page::PageClients pageClients;
311     pageClients.chromeClient = new WebChromeClient(this);
312 #if ENABLE(CONTEXT_MENUS)
313     pageClients.contextMenuClient = new WebContextMenuClient(this);
314 #endif
315     pageClients.editorClient = new WebEditorClient(this);
316 #if ENABLE(DRAG_SUPPORT)
317     pageClients.dragClient = new WebDragClient(this);
318 #endif
319     pageClients.backForwardClient = WebBackForwardListProxy::create(this);
320 #if ENABLE(INSPECTOR)
321     m_inspectorClient = new WebInspectorClient(this);
322     pageClients.inspectorClient = m_inspectorClient;
323 #endif
324 #if USE(AUTOCORRECTION_PANEL)
325     pageClients.alternativeTextClient = new WebAlternativeTextClient(this);
326 #endif
327     pageClients.plugInClient = new WebPlugInClient(this);
328     pageClients.loaderClientForMainFrame = new WebFrameLoaderClient;
329     pageClients.progressTrackerClient = new WebProgressTrackerClient(*this);
330
331     pageClients.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID);
332
333     m_page = adoptPtr(new Page(pageClients));
334
335     m_drawingArea = DrawingArea::create(this, parameters);
336     m_drawingArea->setPaintingEnabled(false);
337
338 #if ENABLE(ASYNC_SCROLLING)
339     m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey());
340     if (!m_drawingArea->supportsAsyncScrolling())
341         m_useAsyncScrolling = false;
342     m_page->settings().setScrollingCoordinatorEnabled(m_useAsyncScrolling);
343 #endif
344
345     m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame());
346
347 #if ENABLE(BATTERY_STATUS)
348     WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
349 #endif
350 #if ENABLE(GEOLOCATION)
351     WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
352 #endif
353 #if ENABLE(NETWORK_INFO)
354     WebCore::provideNetworkInfoTo(m_page.get(), new WebNetworkInfoClient(this));
355 #endif
356 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
357     WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
358 #endif
359 #if ENABLE(VIBRATION)
360     WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
361 #endif
362 #if ENABLE(PROXIMITY_EVENTS)
363     WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this));
364 #endif
365
366 #if ENABLE(REMOTE_INSPECTOR)
367     m_page->setRemoteInspectionAllowed(true);
368 #endif
369
370     m_page->setCanStartMedia(false);
371     m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow;
372
373     m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
374     m_page->setGroupName(m_pageGroup->identifier());
375     m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
376
377     updatePreferences(parameters.store);
378     platformInitialize();
379
380     setUseFixedLayout(parameters.useFixedLayout);
381
382     setDrawsBackground(parameters.drawsBackground);
383     setDrawsTransparentBackground(parameters.drawsTransparentBackground);
384
385     setUnderlayColor(parameters.underlayColor);
386
387     setPaginationMode(parameters.paginationMode);
388     setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
389     setPageLength(parameters.pageLength);
390     setGapBetweenPages(parameters.gapBetweenPages);
391
392     setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
393
394     // If the page is created off-screen, its visibilityState should be prerender.
395     m_page->setViewState(m_viewState);
396     if (!isVisible())
397         m_page->setIsPrerender();
398
399     updateIsInWindow(true);
400
401     setMinimumLayoutSize(parameters.minimumLayoutSize);
402     setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight);
403     
404     setScrollPinningBehavior(parameters.scrollPinningBehavior);
405     setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage);
406
407     m_userAgent = parameters.userAgent;
408
409     WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
410     
411     if (!parameters.sessionState.isEmpty())
412         restoreSession(parameters.sessionState);
413
414     m_drawingArea->setPaintingEnabled(true);
415     
416     setMediaVolume(parameters.mediaVolume);
417
418     // We use the DidFirstLayout milestone to determine when to unfreeze the layer tree.
419     m_page->addLayoutMilestones(DidFirstLayout);
420
421     WebProcess::shared().addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this);
422
423     // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers.
424     WebProcess::shared().addMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID, *this);
425 #if USE(COORDINATED_GRAPHICS)
426     WebProcess::shared().addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this);
427 #endif
428 #if ENABLE(INSPECTOR)
429     WebProcess::shared().addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this);
430 #endif
431 #if ENABLE(FULLSCREEN_API)
432     WebProcess::shared().addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this);
433 #endif
434
435 #ifndef NDEBUG
436     webPageCounter.increment();
437 #endif
438
439 #if ENABLE(ASYNC_SCROLLING)
440     if (m_useAsyncScrolling)
441         WebProcess::shared().eventDispatcher().addScrollingTreeForPage(this);
442 #endif
443 }
444
445 void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters)
446 {
447     if (m_viewState != parameters.viewState)
448         setViewState(parameters.viewState);
449     if (m_layerHostingMode != parameters.layerHostingMode)
450         setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode));
451 }
452
453 WebPage::~WebPage()
454 {
455     if (m_backForwardList)
456         m_backForwardList->detach();
457
458     ASSERT(!m_page);
459
460 #if ENABLE(ASYNC_SCROLLING)
461     if (m_useAsyncScrolling)
462         WebProcess::shared().eventDispatcher().removeScrollingTreeForPage(this);
463 #endif
464
465     m_sandboxExtensionTracker.invalidate();
466
467     for (auto* pluginView : m_pluginViews)
468         pluginView->webPageDestroyed();
469
470 #if !PLATFORM(IOS)
471     if (m_headerBanner)
472         m_headerBanner->detachFromPage();
473     if (m_footerBanner)
474         m_footerBanner->detachFromPage();
475 #endif // !PLATFORM(IOS)
476
477     WebProcess::shared().removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID);
478
479     // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers.
480     WebProcess::shared().removeMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID);
481 #if USE(COORDINATED_GRAPHICS)
482     WebProcess::shared().removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID);
483 #endif
484 #if ENABLE(INSPECTOR)
485     WebProcess::shared().removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID);
486 #endif
487 #if ENABLE(FULLSCREEN_API)
488     WebProcess::shared().removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID);
489 #endif
490
491 #ifndef NDEBUG
492     webPageCounter.decrement();
493 #endif
494 }
495
496 void WebPage::dummy(bool&)
497 {
498 }
499
500 IPC::Connection* WebPage::messageSenderConnection()
501 {
502     return WebProcess::shared().parentProcessConnection();
503 }
504
505 uint64_t WebPage::messageSenderDestinationID()
506 {
507     return pageID();
508 }
509
510 #if ENABLE(CONTEXT_MENUS)
511 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClientBase* client)
512 {
513     m_contextMenuClient.initialize(client);
514 }
515 #endif
516
517 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* client)
518 {
519     m_editorClient.initialize(client);
520 }
521
522 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClientBase* client)
523 {
524     m_formClient.initialize(client);
525 }
526
527 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client)
528 {
529     m_loaderClient.initialize(client);
530
531     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
532     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
533     // for backwards compatibility.
534     LayoutMilestones milestones = 0;
535     if (client) {
536         if (m_loaderClient.client().didFirstLayoutForFrame)
537             milestones |= WebCore::DidFirstLayout;
538         if (m_loaderClient.client().didFirstVisuallyNonEmptyLayoutForFrame)
539             milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
540     }
541
542     if (milestones)
543         listenForLayoutMilestones(milestones);
544 }
545
546 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase* client)
547 {
548     m_policyClient.initialize(client);
549 }
550
551 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase* client)
552 {
553     m_resourceLoadClient.initialize(client);
554 }
555
556 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClientBase* client)
557 {
558     m_uiClient.initialize(client);
559 }
560
561 #if ENABLE(FULLSCREEN_API)
562 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase* client)
563 {
564     m_fullScreenClient.initialize(client);
565 }
566 #endif
567
568 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase* client)
569 {
570     m_logDiagnosticMessageClient.initialize(client);
571 }
572
573 #if ENABLE(NETSCAPE_PLUGIN_API)
574 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters, String& newMIMEType)
575 {
576     String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string();
577     String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string();
578     PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal;
579
580     bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin);
581
582     uint64_t pluginProcessToken;
583     uint32_t pluginLoadPolicy;
584     String unavailabilityDescription;
585     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)))
586         return nullptr;
587
588     bool isBlockedPlugin = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy) == PluginModuleBlocked;
589
590     if (isBlockedPlugin || !pluginProcessToken) {
591 #if ENABLE(PDFKIT_PLUGIN)
592         String path = parameters.url.path();
593         if (shouldUsePDFPlugin() && (MIMETypeRegistry::isPDFOrPostScriptMIMEType(parameters.mimeType) || (parameters.mimeType.isEmpty() && (path.endsWith(".pdf", false) || path.endsWith(".ps", false))))) {
594             RefPtr<PDFPlugin> pdfPlugin = PDFPlugin::create(frame);
595             return pdfPlugin.release();
596         }
597 #else
598         UNUSED_PARAM(frame);
599 #endif
600     }
601
602     if (isBlockedPlugin) {
603         bool replacementObscured = false;
604         if (pluginElement->renderer()->isEmbeddedObject()) {
605             RenderEmbeddedObject* renderObject = toRenderEmbeddedObject(pluginElement->renderer());
606             renderObject->setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription);
607             replacementObscured = renderObject->isReplacementObscured();
608             renderObject->setUnavailablePluginIndicatorIsHidden(replacementObscured);
609         }
610
611         send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured));
612         return nullptr;
613     }
614
615     if (!pluginProcessToken)
616         return nullptr;
617
618     bool isRestartedProcess = (pluginElement->displayState() == HTMLPlugInElement::Restarting || pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick);
619     return PluginProxy::create(pluginProcessToken, isRestartedProcess);
620 }
621
622 #endif // ENABLE(NETSCAPE_PLUGIN_API)
623
624 #if ENABLE(WEBGL) && !PLATFORM(COCOA)
625 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */)
626 {
627     return WebGLAllowCreation;
628 }
629
630 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */)
631 {
632     return WebGLAllowCreation;
633 }
634 #endif
635
636 EditorState WebPage::editorState() const
637 {
638     Frame& frame = m_page->focusController().focusedOrMainFrame();
639
640     EditorState result;
641
642     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
643         if (!pluginView->getSelectionString().isNull()) {
644             result.selectionIsNone = false;
645             result.selectionIsRange = true;
646             result.isInPlugin = true;
647             return result;
648         }
649     }
650
651     const VisibleSelection& selection = frame.selection().selection();
652
653     result.selectionIsNone = selection.isNone();
654     result.selectionIsRange = selection.isRange();
655     result.isContentEditable = selection.isContentEditable();
656     result.isContentRichlyEditable = selection.isContentRichlyEditable();
657     result.isInPasswordField = selection.isInPasswordField();
658     result.hasComposition = frame.editor().hasComposition();
659     result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange();
660
661 #if PLATFORM(IOS)
662     if (frame.editor().hasComposition()) {
663         RefPtr<Range> compositionRange = frame.editor().compositionRange();
664         Vector<WebCore::SelectionRect> compositionRects;
665         compositionRange->collectSelectionRects(compositionRects);
666         if (compositionRects.size())
667             result.firstMarkedRect = compositionRects[0].rect();
668         if (compositionRects.size() > 1)
669             result.lastMarkedRect = compositionRects.last().rect();
670         else
671             result.lastMarkedRect = result.firstMarkedRect;
672         result.markedText = plainText(compositionRange.get());
673     }
674     FrameView* view = frame.view();
675     if (selection.isCaret()) {
676         result.caretRectAtStart = view->contentsToRootView(frame.selection().absoluteCaretBounds());
677         result.caretRectAtEnd = result.caretRectAtStart;
678         if (m_shouldReturnWordAtSelection)
679             result.wordAtSelection = plainText(wordRangeFromPosition(selection.start()).get());
680     } else if (selection.isRange()) {
681         result.caretRectAtStart = view->contentsToRootView(VisiblePosition(selection.start()).absoluteCaretBounds());
682         result.caretRectAtEnd = view->contentsToRootView(VisiblePosition(selection.end()).absoluteCaretBounds());
683         RefPtr<Range> selectedRange = selection.toNormalizedRange();
684         selectedRange->collectSelectionRects(result.selectionRects);
685         convertSelectionRectsToRootView(view, result.selectionRects);
686         result.selectedTextLength = plainText(selectedRange.get(), TextIteratorDefaultBehavior, true).length();
687     }
688 #endif
689
690 #if PLATFORM(GTK)
691     result.cursorRect = frame.selection().absoluteCaretBounds();
692 #endif
693
694     return result;
695 }
696
697 String WebPage::renderTreeExternalRepresentation() const
698 {
699     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
700 }
701
702 String WebPage::renderTreeExternalRepresentationForPrinting() const
703 {
704     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextPrintingMode);
705 }
706
707 uint64_t WebPage::renderTreeSize() const
708 {
709     if (!m_page)
710         return 0;
711     return m_page->renderTreeSize();
712 }
713
714 void WebPage::setTracksRepaints(bool trackRepaints)
715 {
716     if (FrameView* view = mainFrameView())
717         view->setTracksRepaints(trackRepaints);
718 }
719
720 bool WebPage::isTrackingRepaints() const
721 {
722     if (FrameView* view = mainFrameView())
723         return view->isTrackingRepaints();
724
725     return false;
726 }
727
728 void WebPage::resetTrackedRepaints()
729 {
730     if (FrameView* view = mainFrameView())
731         view->resetTrackedRepaints();
732 }
733
734 PassRefPtr<API::Array> WebPage::trackedRepaintRects()
735 {
736     FrameView* view = mainFrameView();
737     if (!view)
738         return API::Array::create();
739
740     Vector<RefPtr<API::Object>> repaintRects;
741     repaintRects.reserveInitialCapacity(view->trackedRepaintRects().size());
742
743     for (const auto& repaintRect : view->trackedRepaintRects())
744         repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect)));
745
746     return API::Array::create(std::move(repaintRects));
747 }
748
749 PluginView* WebPage::focusedPluginViewForFrame(Frame& frame)
750 {
751     if (!frame.document()->isPluginDocument())
752         return 0;
753
754     PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame.document());
755
756     if (pluginDocument->focusedElement() != pluginDocument->pluginElement())
757         return 0;
758
759     PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
760     return pluginView;
761 }
762
763 PluginView* WebPage::pluginViewForFrame(Frame* frame)
764 {
765     if (!frame->document()->isPluginDocument())
766         return 0;
767
768     PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
769     PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget());
770     return pluginView;
771 }
772
773 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
774 {
775     Frame& frame = m_page->focusController().focusedOrMainFrame();
776
777     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
778         pluginView->handleEditingCommand(commandName, argument);
779         return;
780     }
781     
782     frame.editor().command(commandName).execute(argument);
783 }
784
785 bool WebPage::isEditingCommandEnabled(const String& commandName)
786 {
787     Frame& frame = m_page->focusController().focusedOrMainFrame();
788
789     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
790         return pluginView->isEditingCommandEnabled(commandName);
791     
792     Editor::Command command = frame.editor().command(commandName);
793     return command.isSupported() && command.isEnabled();
794 }
795     
796 void WebPage::clearMainFrameName()
797 {
798     if (Frame* frame = mainFrame())
799         frame->tree().clearName();
800 }
801
802 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
803 {
804     m_drawingArea->setRootCompositingLayer(layer);
805 }
806
807 void WebPage::exitAcceleratedCompositingMode()
808 {
809     m_drawingArea->setRootCompositingLayer(0);
810 }
811
812 void WebPage::close()
813 {
814     if (m_isClosed)
815         return;
816
817     m_isClosed = true;
818
819     // If there is still no URL, then we never loaded anything in this page, so nothing to report.
820     if (!mainWebFrame()->url().isEmpty())
821         reportUsedFeatures();
822
823     if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
824         WebProcess::shared().injectedBundle()->willDestroyPage(this);
825
826 #if ENABLE(INSPECTOR)
827     m_inspector = 0;
828 #endif
829 #if ENABLE(FULLSCREEN_API)
830     m_fullScreenManager = 0;
831 #endif
832
833     if (m_activePopupMenu) {
834         m_activePopupMenu->disconnectFromPage();
835         m_activePopupMenu = 0;
836     }
837
838     if (m_activeOpenPanelResultListener) {
839         m_activeOpenPanelResultListener->disconnectFromPage();
840         m_activeOpenPanelResultListener = 0;
841     }
842
843 #if ENABLE(INPUT_TYPE_COLOR)
844     if (m_activeColorChooser) {
845         m_activeColorChooser->disconnectFromPage();
846         m_activeColorChooser = 0;
847     }
848 #endif
849
850 #if PLATFORM(GTK)
851     if (m_printOperation) {
852         m_printOperation->disconnectFromPage();
853         m_printOperation = nullptr;
854     }
855 #endif
856
857     m_sandboxExtensionTracker.invalidate();
858
859 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
860     m_determinePrimarySnapshottedPlugInTimer.stop();
861 #endif
862
863 #if ENABLE(CONTEXT_MENUS)
864     m_contextMenuClient.initialize(0);
865 #endif
866     m_editorClient.initialize(0);
867     m_formClient.initialize(0);
868     m_loaderClient.initialize(0);
869     m_policyClient.initialize(0);
870     m_resourceLoadClient.initialize(0);
871     m_uiClient.initialize(0);
872 #if ENABLE(FULLSCREEN_API)
873     m_fullScreenClient.initialize(0);
874 #endif
875     m_logDiagnosticMessageClient.initialize(0);
876
877     m_printContext = nullptr;
878     m_mainFrame->coreFrame()->loader().detachFromParent();
879     m_page = nullptr;
880     m_drawingArea = nullptr;
881
882     bool isRunningModal = m_isRunningModal;
883     m_isRunningModal = false;
884
885     // The WebPage can be destroyed by this call.
886     WebProcess::shared().removeWebPage(m_pageID);
887
888     if (isRunningModal)
889         RunLoop::main().stop();
890 }
891
892 void WebPage::tryClose()
893 {
894     SendStopResponsivenessTimer stopper(this);
895
896     if (!corePage()->userInputBridge().tryClosePage()) {
897         send(Messages::WebPageProxy::StopResponsivenessTimer());
898         return;
899     }
900
901     send(Messages::WebPageProxy::ClosePage(true));
902 }
903
904 void WebPage::sendClose()
905 {
906     send(Messages::WebPageProxy::ClosePage(false));
907 }
908
909 void WebPage::loadURLInFrame(const String& url, uint64_t frameID)
910 {
911     WebFrame* frame = WebProcess::shared().webFrame(frameID);
912     if (!frame)
913         return;
914
915     frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url))));
916 }
917
918 void WebPage::loadRequest(uint64_t navigationID, const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, IPC::MessageDecoder& decoder)
919 {
920     SendStopResponsivenessTimer stopper(this);
921
922     RefPtr<API::Object> userData;
923     InjectedBundleUserMessageDecoder userMessageDecoder(userData);
924     if (!decoder.decode(userMessageDecoder))
925         return;
926
927     ASSERT(!m_pendingNavigationID);
928     m_pendingNavigationID = navigationID;
929
930     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
931
932     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
933     // to all the client to set up any needed state.
934     m_loaderClient.willLoadURLRequest(this, request, userData.get());
935
936     // Initate the load in WebCore.
937     corePage()->userInputBridge().loadRequest(FrameLoadRequest(m_mainFrame->coreFrame(), request));
938
939     ASSERT(!m_pendingNavigationID);
940 }
941
942 void WebPage::loadDataImpl(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder)
943 {
944     SendStopResponsivenessTimer stopper(this);
945
946     RefPtr<API::Object> userData;
947     InjectedBundleUserMessageDecoder userMessageDecoder(userData);
948     if (!decoder.decode(userMessageDecoder))
949         return;
950
951     ResourceRequest request(baseURL);
952     SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
953
954     // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
955     // to all the client to set up any needed state.
956     m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), userData.get());
957
958     // Initate the load in WebCore.
959     m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, substituteData));
960 }
961
962 void WebPage::loadString(const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder)
963 {
964     if (!htmlString.isNull() && htmlString.is8Bit()) {
965         RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar));
966         loadDataImpl(sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, decoder);
967     } else {
968         RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar));
969         loadDataImpl(sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, decoder);
970     }
971 }
972
973 void WebPage::loadData(const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, IPC::MessageDecoder& decoder)
974 {
975     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size());
976     URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
977     loadDataImpl(sharedBuffer, MIMEType, encodingName, baseURL, URL(), decoder);
978 }
979
980 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString, IPC::MessageDecoder& decoder)
981 {
982     URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
983     loadString(htmlString, ASCIILiteral("text/html"), baseURL, URL(), decoder);
984 }
985
986 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, IPC::MessageDecoder& decoder)
987 {
988     URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString);
989     URL unreachableURL = unreachableURLString.isEmpty() ? URL() : URL(URL(), unreachableURLString);
990     loadString(htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, decoder);
991 }
992
993 void WebPage::loadPlainTextString(const String& string, IPC::MessageDecoder& decoder)
994 {
995     loadString(string, ASCIILiteral("text/plain"), blankURL(), URL(), decoder);
996 }
997
998 void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, IPC::MessageDecoder& decoder)
999 {
1000     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
1001     loadDataImpl(sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), decoder);
1002 }
1003
1004 void WebPage::stopLoadingFrame(uint64_t frameID)
1005 {
1006     WebFrame* frame = WebProcess::shared().webFrame(frameID);
1007     if (!frame)
1008         return;
1009
1010     corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame());
1011 }
1012
1013 void WebPage::stopLoading()
1014 {
1015     SendStopResponsivenessTimer stopper(this);
1016
1017     corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame());
1018 }
1019
1020 void WebPage::setDefersLoading(bool defersLoading)
1021 {
1022     m_page->setDefersLoading(defersLoading);
1023 }
1024
1025 void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
1026 {
1027     SendStopResponsivenessTimer stopper(this);
1028
1029     ASSERT(!m_pendingNavigationID);
1030     m_pendingNavigationID = navigationID;
1031
1032     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
1033     corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin);
1034 }
1035
1036 void WebPage::goForward(uint64_t backForwardItemID)
1037 {
1038     SendStopResponsivenessTimer stopper(this);
1039
1040     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1041     ASSERT(item);
1042     if (!item)
1043         return;
1044
1045     m_page->goToItem(item, FrameLoadTypeForward);
1046 }
1047
1048 void WebPage::goBack(uint64_t backForwardItemID)
1049 {
1050     SendStopResponsivenessTimer stopper(this);
1051
1052     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1053     ASSERT(item);
1054     if (!item)
1055         return;
1056
1057     m_page->goToItem(item, FrameLoadTypeBack);
1058 }
1059
1060 void WebPage::goToBackForwardItem(uint64_t backForwardItemID)
1061 {
1062     SendStopResponsivenessTimer stopper(this);
1063
1064     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
1065     ASSERT(item);
1066     if (!item)
1067         return;
1068
1069     m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
1070 }
1071
1072 void WebPage::tryRestoreScrollPosition()
1073 {
1074     m_page->mainFrame().loader().history().restoreScrollPositionAndViewState();
1075 }
1076
1077 void WebPage::layoutIfNeeded()
1078 {
1079     if (m_mainFrame->coreFrame()->view())
1080         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1081 }
1082
1083 WebPage* WebPage::fromCorePage(Page* page)
1084 {
1085     return static_cast<WebChromeClient&>(page->chrome().client()).page();
1086 }
1087
1088 void WebPage::setSize(const WebCore::IntSize& viewSize)
1089 {
1090     if (m_viewSize == viewSize)
1091         return;
1092
1093     FrameView* view = m_page->mainFrame().view();
1094     view->resize(viewSize);
1095     m_drawingArea->setNeedsDisplay();
1096     
1097     m_viewSize = viewSize;
1098
1099 #if USE(TILED_BACKING_STORE)
1100     if (view->useFixedLayout())
1101         sendViewportAttributesChanged();
1102 #endif
1103 }
1104
1105 #if USE(TILED_BACKING_STORE)
1106 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1107 {
1108     ASSERT(m_useFixedLayout);
1109
1110     m_page->mainFrame().view()->setFixedVisibleContentRect(rect);
1111 }
1112
1113 void WebPage::sendViewportAttributesChanged()
1114 {
1115     ASSERT(m_useFixedLayout);
1116
1117     // Viewport properties have no impact on zero sized fixed viewports.
1118     if (m_viewSize.isEmpty())
1119         return;
1120
1121     // Recalculate the recommended layout size, when the available size (device pixel) changes.
1122     Settings& settings = m_page->settings();
1123
1124     int minimumLayoutFallbackWidth = std::max(settings.layoutFallbackWidth(), m_viewSize.width());
1125
1126     // If unset  we use the viewport dimensions. This fits with the behavior of desktop browsers.
1127     int deviceWidth = (settings.deviceWidth() > 0) ? settings.deviceWidth() : m_viewSize.width();
1128     int deviceHeight = (settings.deviceHeight() > 0) ? settings.deviceHeight() : m_viewSize.height();
1129
1130     ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, 1, m_viewSize);
1131
1132     FrameView* view = m_page->mainFrame().view();
1133
1134     // If no layout was done yet set contentFixedOrigin to (0,0).
1135     IntPoint contentFixedOrigin = view->didFirstLayout() ? view->fixedVisibleContentRect().location() : IntPoint();
1136
1137     // Put the width and height to the viewport width and height. In css units however.
1138     // Use FloatSize to avoid truncated values during scale.
1139     FloatSize contentFixedSize = m_viewSize;
1140
1141 #if ENABLE(CSS_DEVICE_ADAPTATION)
1142     // CSS viewport descriptors might be applied to already affected viewport size
1143     // if the page enables/disables stylesheets, so need to keep initial viewport size.
1144     view->setInitialViewportSize(roundedIntSize(contentFixedSize));
1145 #endif
1146
1147     contentFixedSize.scale(1 / attr.initialScale);
1148     setFixedVisibleContentRect(IntRect(contentFixedOrigin, roundedIntSize(contentFixedSize)));
1149
1150     attr.initialScale = m_page->viewportArguments().zoom; // Resets auto (-1) if no value was set by user.
1151
1152     // This also takes care of the relayout.
1153     setFixedLayoutSize(roundedIntSize(attr.layoutSize));
1154
1155     send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1156 }
1157 #endif
1158
1159 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1160 {
1161     FrameView* frameView = m_page->mainFrame().view();
1162
1163     IntPoint scrollPosition = frameView->scrollPosition();
1164     IntPoint maximumScrollPosition = frameView->maximumScrollPosition();
1165
1166     // If the current scroll position in a direction is the max scroll position 
1167     // we don't want to scroll at all.
1168     IntSize newScrollOffset;
1169     if (scrollPosition.x() < maximumScrollPosition.x())
1170         newScrollOffset.setWidth(scrollOffset.width());
1171     if (scrollPosition.y() < maximumScrollPosition.y())
1172         newScrollOffset.setHeight(scrollOffset.height());
1173
1174     if (newScrollOffset.isZero())
1175         return;
1176
1177     frameView->setScrollPosition(frameView->scrollPosition() + newScrollOffset);
1178 }
1179
1180 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1181 {
1182     GraphicsContextStateSaver stateSaver(graphicsContext);
1183     graphicsContext.clip(rect);
1184
1185     m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1186 }
1187
1188 void WebPage::drawPageOverlay(PageOverlay* pageOverlay, GraphicsContext& graphicsContext, const IntRect& rect)
1189 {
1190     ASSERT(pageOverlay);
1191
1192     GraphicsContextStateSaver stateSaver(graphicsContext);
1193     graphicsContext.clip(rect);
1194     pageOverlay->drawRect(graphicsContext, rect);
1195 }
1196
1197 double WebPage::textZoomFactor() const
1198 {
1199     Frame* frame = m_mainFrame->coreFrame();
1200     if (!frame)
1201         return 1;
1202     return frame->textZoomFactor();
1203 }
1204
1205 void WebPage::setTextZoomFactor(double zoomFactor)
1206 {
1207     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1208     if (pluginView && pluginView->handlesPageScaleFactor())
1209         return;
1210
1211     Frame* frame = m_mainFrame->coreFrame();
1212     if (!frame)
1213         return;
1214     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1215 }
1216
1217 double WebPage::pageZoomFactor() const
1218 {
1219     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1220     if (pluginView && pluginView->handlesPageScaleFactor())
1221         return pluginView->pageScaleFactor();
1222
1223     Frame* frame = m_mainFrame->coreFrame();
1224     if (!frame)
1225         return 1;
1226     return frame->pageZoomFactor();
1227 }
1228
1229 void WebPage::setPageZoomFactor(double zoomFactor)
1230 {
1231     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1232     if (pluginView && pluginView->handlesPageScaleFactor()) {
1233         pluginView->setPageScaleFactor(zoomFactor, IntPoint());
1234         return;
1235     }
1236
1237     Frame* frame = m_mainFrame->coreFrame();
1238     if (!frame)
1239         return;
1240     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1241 }
1242
1243 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1244 {
1245     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1246     if (pluginView && pluginView->handlesPageScaleFactor()) {
1247         pluginView->setPageScaleFactor(pageZoomFactor, IntPoint());
1248         return;
1249     }
1250
1251     Frame* frame = m_mainFrame->coreFrame();
1252     if (!frame)
1253         return;
1254     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1255 }
1256
1257 void WebPage::windowScreenDidChange(uint64_t displayID)
1258 {
1259     m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1260 }
1261
1262 void WebPage::scalePage(double scale, const IntPoint& origin)
1263 {
1264     if (scale == pageScaleFactor())
1265         return;
1266
1267 #if PLATFORM(IOS)
1268     m_scaleWasSetByUIProcess = false;
1269 #endif
1270     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1271     if (pluginView && pluginView->handlesPageScaleFactor()) {
1272         pluginView->setPageScaleFactor(scale, origin);
1273         return;
1274     }
1275
1276     m_page->setPageScaleFactor(scale, origin);
1277
1278     for (auto* pluginView : m_pluginViews)
1279         pluginView->pageScaleFactorDidChange();
1280
1281     if (m_drawingArea->layerTreeHost())
1282         m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1283
1284     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1285 }
1286
1287 double WebPage::pageScaleFactor() const
1288 {
1289     PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame());
1290     if (pluginView && pluginView->handlesPageScaleFactor())
1291         return pluginView->pageScaleFactor();
1292     
1293     return m_page->pageScaleFactor();
1294 }
1295
1296 void WebPage::setDeviceScaleFactor(float scaleFactor)
1297 {
1298     if (scaleFactor == m_page->deviceScaleFactor())
1299         return;
1300
1301     m_page->setDeviceScaleFactor(scaleFactor);
1302
1303     // Tell all our plug-in views that the device scale factor changed.
1304 #if PLATFORM(MAC)
1305     for (auto* pluginView : m_pluginViews)
1306         pluginView->setDeviceScaleFactor(scaleFactor);
1307
1308     updateHeaderAndFooterLayersForDeviceScaleChange(scaleFactor);
1309 #endif
1310
1311     if (m_findController.isShowingOverlay()) {
1312         // We must have updated layout to get the selection rects right.
1313         layoutIfNeeded();
1314         m_findController.deviceScaleFactorDidChange();
1315     }
1316
1317     if (m_drawingArea->layerTreeHost())
1318         m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged();
1319 }
1320
1321 float WebPage::deviceScaleFactor() const
1322 {
1323     return m_page->deviceScaleFactor();
1324 }
1325
1326 void WebPage::setUseFixedLayout(bool fixed)
1327 {
1328     // Do not overwrite current settings if initially setting it to false.
1329     if (m_useFixedLayout == fixed)
1330         return;
1331     m_useFixedLayout = fixed;
1332
1333 #if !PLATFORM(IOS)
1334     m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed);
1335 #endif
1336 #if USE(COORDINATED_GRAPHICS)
1337     m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed);
1338     m_page->settings().setFixedPositionCreatesStackingContext(fixed);
1339     m_page->settings().setDelegatesPageScaling(fixed);
1340     m_page->settings().setScrollingCoordinatorEnabled(fixed);
1341 #endif
1342
1343 #if USE(TILED_BACKING_STORE) && ENABLE(SMOOTH_SCROLLING)
1344     // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled.
1345     // Ensure we don't do animated scrolling in the WebProcess in that case.
1346     m_page->settings().setScrollAnimatorEnabled(!fixed);
1347 #endif
1348
1349     FrameView* view = mainFrameView();
1350     if (!view)
1351         return;
1352
1353 #if USE(TILED_BACKING_STORE)
1354     view->setDelegatesScrolling(fixed);
1355     view->setPaintsEntireContents(fixed);
1356 #endif
1357     view->setUseFixedLayout(fixed);
1358     if (!fixed)
1359         setFixedLayoutSize(IntSize());
1360 }
1361
1362 void WebPage::setFixedLayoutSize(const IntSize& size)
1363 {
1364     FrameView* view = mainFrameView();
1365     if (!view || view->fixedLayoutSize() == size)
1366         return;
1367
1368     view->setFixedLayoutSize(size);
1369     // Do not force it until the first layout, this would then become our first layout prematurely.
1370     if (view->didFirstLayout())
1371         view->forceLayout();
1372 }
1373
1374 void WebPage::listenForLayoutMilestones(uint32_t milestones)
1375 {
1376     if (!m_page)
1377         return;
1378     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
1379 }
1380
1381 void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations)
1382 {
1383     m_page->setShouldSuppressScrollbarAnimations(suppressAnimations);
1384 }
1385
1386 void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
1387 {
1388     if (m_page->settings().backgroundShouldExtendBeyondPage() != backgroundExtendsBeyondPage)
1389         m_page->settings().setBackgroundShouldExtendBeyondPage(backgroundExtendsBeyondPage);
1390 }
1391
1392 void WebPage::setPaginationMode(uint32_t mode)
1393 {
1394     Pagination pagination = m_page->pagination();
1395     pagination.mode = static_cast<Pagination::Mode>(mode);
1396     m_page->setPagination(pagination);
1397 }
1398
1399 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1400 {
1401     Pagination pagination = m_page->pagination();
1402     pagination.behavesLikeColumns = behavesLikeColumns;
1403     m_page->setPagination(pagination);
1404 }
1405
1406 void WebPage::setPageLength(double pageLength)
1407 {
1408     Pagination pagination = m_page->pagination();
1409     pagination.pageLength = pageLength;
1410     m_page->setPagination(pagination);
1411 }
1412
1413 void WebPage::setGapBetweenPages(double gap)
1414 {
1415     Pagination pagination = m_page->pagination();
1416     pagination.gap = gap;
1417     m_page->setPagination(pagination);
1418 }
1419
1420 void WebPage::postInjectedBundleMessage(const String& messageName, IPC::MessageDecoder& decoder)
1421 {
1422     InjectedBundle* injectedBundle = WebProcess::shared().injectedBundle();
1423     if (!injectedBundle)
1424         return;
1425
1426     RefPtr<API::Object> messageBody;
1427     InjectedBundleUserMessageDecoder messageBodyDecoder(messageBody);
1428     if (!decoder.decode(messageBodyDecoder))
1429         return;
1430
1431     injectedBundle->didReceiveMessageToPage(this, messageName, messageBody.get());
1432 }
1433
1434 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay, bool shouldFadeIn)
1435 {
1436     RefPtr<PageOverlay> overlay = pageOverlay;
1437     
1438     if (m_pageOverlays.contains(overlay.get()))
1439         return;
1440
1441     m_pageOverlays.append(overlay);
1442     overlay->setPage(this);
1443
1444     if (shouldFadeIn)
1445         overlay->startFadeInAnimation();
1446
1447     m_drawingArea->didInstallPageOverlay(overlay.get());
1448 }
1449
1450 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool shouldFadeOut)
1451 {
1452     size_t existingOverlayIndex = m_pageOverlays.find(pageOverlay);
1453     if (existingOverlayIndex == notFound)
1454         return;
1455
1456     if (shouldFadeOut) {
1457         pageOverlay->startFadeOutAnimation();
1458         return;
1459     }
1460
1461     pageOverlay->setPage(0);
1462     m_pageOverlays.remove(existingOverlayIndex);
1463
1464     m_drawingArea->didUninstallPageOverlay(pageOverlay);
1465 }
1466
1467 #if !PLATFORM(IOS)
1468 void WebPage::setHeaderPageBanner(PassRefPtr<PageBanner> pageBanner)
1469 {
1470     if (m_headerBanner)
1471         m_headerBanner->detachFromPage();
1472
1473     m_headerBanner = pageBanner;
1474
1475     if (m_headerBanner)
1476         m_headerBanner->addToPage(PageBanner::Header, this);
1477 }
1478
1479 PageBanner* WebPage::headerPageBanner()
1480 {
1481     return m_headerBanner.get();
1482 }
1483
1484 void WebPage::setFooterPageBanner(PassRefPtr<PageBanner> pageBanner)
1485 {
1486     if (m_footerBanner)
1487         m_footerBanner->detachFromPage();
1488
1489     m_footerBanner = pageBanner;
1490
1491     if (m_footerBanner)
1492         m_footerBanner->addToPage(PageBanner::Footer, this);
1493 }
1494
1495 PageBanner* WebPage::footerPageBanner()
1496 {
1497     return m_footerBanner.get();
1498 }
1499
1500 void WebPage::hidePageBanners()
1501 {
1502     if (m_headerBanner)
1503         m_headerBanner->hide();
1504     if (m_footerBanner)
1505         m_footerBanner->hide();
1506 }
1507
1508 void WebPage::showPageBanners()
1509 {
1510     if (m_headerBanner)
1511         m_headerBanner->showIfHidden();
1512     if (m_footerBanner)
1513         m_footerBanner->showIfHidden();
1514 }
1515 #endif // !PLATFORM(IOS)
1516
1517 void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID)
1518 {
1519     SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options);
1520     snapshotOptions |= SnapshotOptionsShareable;
1521
1522     RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions);
1523
1524     ShareableBitmap::Handle handle;
1525     if (image)
1526         image->bitmap()->createHandle(handle, SharedMemory::ReadOnly);
1527
1528     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
1529 }
1530
1531 PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double scaleFactor, SnapshotOptions options)
1532 {
1533     IntRect snapshotRect = rect;
1534     if (options & SnapshotOptionsRespectDrawingAreaTransform)
1535         snapshotRect = m_drawingArea->rootLayerTransform().inverse().mapRect(snapshotRect);
1536
1537     IntSize bitmapSize = snapshotRect.size();
1538     bitmapSize.scale(scaleFactor * corePage()->deviceScaleFactor());
1539
1540     return snapshotAtSize(rect, bitmapSize, options);
1541 }
1542
1543 PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options)
1544 {
1545     Frame* coreFrame = m_mainFrame->coreFrame();
1546     if (!coreFrame)
1547         return nullptr;
1548
1549     FrameView* frameView = coreFrame->view();
1550     if (!frameView)
1551         return nullptr;
1552
1553     IntRect snapshotRect = rect;
1554     if (options & SnapshotOptionsRespectDrawingAreaTransform)
1555         snapshotRect = m_drawingArea->rootLayerTransform().inverse().mapRect(snapshotRect);
1556
1557     float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width();
1558     float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height();
1559     float scaleFactor = std::min(horizontalScaleFactor, verticalScaleFactor);
1560
1561     RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options));
1562     if (!snapshot->bitmap())
1563         return nullptr;
1564
1565     auto graphicsContext = snapshot->bitmap()->createGraphicsContext();
1566
1567     graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), frameView->baseBackgroundColor(), ColorSpaceDeviceRGB);
1568
1569     if (!(options & SnapshotOptionsExcludeDeviceScaleFactor))
1570         graphicsContext->applyDeviceScaleFactor(corePage()->deviceScaleFactor());
1571
1572     graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1573     graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y());
1574
1575     FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection;
1576     if (options & SnapshotOptionsExcludeSelectionHighlighting)
1577         shouldPaintSelection = FrameView::ExcludeSelection;
1578
1579     FrameView::CoordinateSpaceForSnapshot coordinateSpace = FrameView::DocumentCoordinates;
1580     if (options & SnapshotOptionsInViewCoordinates)
1581         coordinateSpace = FrameView::ViewCoordinates;
1582
1583     frameView->paintContentsForSnapshot(graphicsContext.get(), snapshotRect, shouldPaintSelection, coordinateSpace);
1584
1585     if (options & SnapshotOptionsPaintSelectionRectangle) {
1586         FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds();
1587         graphicsContext->setStrokeColor(Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
1588         graphicsContext->strokeRect(selectionRectangle, 1);
1589     }
1590     
1591     return snapshot.release();
1592 }
1593
1594 void WebPage::pageDidScroll()
1595 {
1596     m_uiClient.pageDidScroll(this);
1597
1598     send(Messages::WebPageProxy::PageDidScroll());
1599 }
1600
1601 #if USE(TILED_BACKING_STORE)
1602 void WebPage::pageDidRequestScroll(const IntPoint& point)
1603 {
1604     send(Messages::WebPageProxy::PageDidRequestScroll(point));
1605 }
1606 #endif
1607
1608 #if ENABLE(CONTEXT_MENUS)
1609 WebContextMenu* WebPage::contextMenu()
1610 {
1611     if (!m_contextMenu)
1612         m_contextMenu = WebContextMenu::create(this);
1613     return m_contextMenu.get();
1614 }
1615
1616 WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point)
1617 {
1618     corePage()->contextMenuController().clearContextMenu();
1619     
1620     // Simulate a mouse click to generate the correct menu.
1621     PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime());
1622     bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame());
1623     if (!handled)
1624         return 0;
1625
1626     return contextMenu();
1627 }
1628 #endif
1629
1630 // Events 
1631
1632 static const WebEvent* g_currentEvent = 0;
1633
1634 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1635 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1636 // platform events passed to the event handler code.
1637 const WebEvent* WebPage::currentEvent()
1638 {
1639     return g_currentEvent;
1640 }
1641
1642 class CurrentEvent {
1643 public:
1644     explicit CurrentEvent(const WebEvent& event)
1645         : m_previousCurrentEvent(g_currentEvent)
1646     {
1647         g_currentEvent = &event;
1648     }
1649
1650     ~CurrentEvent()
1651     {
1652         g_currentEvent = m_previousCurrentEvent;
1653     }
1654
1655 private:
1656     const WebEvent* m_previousCurrentEvent;
1657 };
1658
1659 #if ENABLE(CONTEXT_MENUS)
1660 static bool isContextClick(const PlatformMouseEvent& event)
1661 {
1662     if (event.button() == WebCore::RightButton)
1663         return true;
1664
1665 #if PLATFORM(COCOA)
1666     // FIXME: this really should be about OSX-style UI, not about the Mac port
1667     if (event.button() == WebCore::LeftButton && event.ctrlKey())
1668         return true;
1669 #endif
1670
1671     return false;
1672 }
1673
1674 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1675 {
1676     IntPoint point = page->corePage()->mainFrame().view()->windowToContents(platformMouseEvent.position());
1677     HitTestResult result = page->corePage()->mainFrame().eventHandler().hitTestResultAtPoint(point);
1678
1679     Frame* frame = &page->corePage()->mainFrame();
1680     if (result.innerNonSharedNode())
1681         frame = result.innerNonSharedNode()->document().frame();
1682
1683     bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame);
1684     if (handled)
1685         page->contextMenu()->show();
1686
1687     return handled;
1688 }
1689 #endif
1690
1691 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1692 {
1693     Frame& frame = page->corePage()->mainFrame();
1694     if (!frame.view())
1695         return false;
1696
1697     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1698
1699     switch (platformMouseEvent.type()) {
1700         case PlatformEvent::MousePressed: {
1701 #if ENABLE(CONTEXT_MENUS)
1702             if (isContextClick(platformMouseEvent))
1703                 page->corePage()->contextMenuController().clearContextMenu();
1704 #endif
1705
1706             bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent);
1707 #if ENABLE(CONTEXT_MENUS)
1708             if (isContextClick(platformMouseEvent))
1709                 handled = handleContextMenuEvent(platformMouseEvent, page);
1710 #endif
1711             return handled;
1712         }
1713         case PlatformEvent::MouseReleased:
1714             return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent);
1715
1716         case PlatformEvent::MouseMoved:
1717             if (onlyUpdateScrollbars)
1718                 return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent);
1719             return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent);
1720         default:
1721             ASSERT_NOT_REACHED();
1722             return false;
1723     }
1724 }
1725
1726 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1727 {
1728     m_page->pageThrottler().didReceiveUserInput();
1729
1730 #if ENABLE(CONTEXT_MENUS)
1731     // Don't try to handle any pending mouse events if a context menu is showing.
1732     if (m_isShowingContextMenu) {
1733         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1734         return;
1735     }
1736 #endif
1737     bool handled = false;
1738     if (m_pageOverlays.size()) {
1739         // Let the page overlay handle the event.
1740         PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1741         for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it)
1742             if ((handled = (*it)->mouseEvent(mouseEvent)))
1743                 break;
1744     }
1745
1746 #if !PLATFORM(IOS)
1747     if (!handled && m_headerBanner)
1748         handled = m_headerBanner->mouseEvent(mouseEvent);
1749     if (!handled && m_footerBanner)
1750         handled = m_footerBanner->mouseEvent(mouseEvent);
1751 #endif // !PLATFORM(IOS)
1752
1753     if (!handled && canHandleUserEvents()) {
1754         CurrentEvent currentEvent(mouseEvent);
1755
1756         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1757         // button is currently pressed. It is possible that neither of those things will be true since on
1758         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1759         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1760         // efficient scrollbars-only version of the event.
1761         bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1762         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1763     }
1764
1765     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1766 }
1767
1768 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1769 {
1770     handled = false;
1771
1772     if (m_pageOverlays.size()) {
1773         PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1774         for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it)
1775             if ((handled = (*it)->mouseEvent(mouseEvent)))
1776                 break;
1777     }
1778 #if !PLATFORM(IOS)
1779     if (!handled && m_headerBanner)
1780         handled = m_headerBanner->mouseEvent(mouseEvent);
1781     if (!handled && m_footerBanner)
1782         handled = m_footerBanner->mouseEvent(mouseEvent);
1783 #endif // !PLATFORM(IOS)
1784
1785     if (!handled) {
1786         CurrentEvent currentEvent(mouseEvent);
1787
1788         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1789         // button is currently pressed. It is possible that neither of those things will be true since on 
1790         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one 
1791         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1792         // efficient scrollbars-only version of the event.
1793         bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1794         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1795     }
1796 }
1797
1798 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1799 {
1800     Frame& frame = page->mainFrame();
1801     if (!frame.view())
1802         return false;
1803
1804     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1805     return page->userInputBridge().handleWheelEvent(platformWheelEvent);
1806 }
1807
1808 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1809 {
1810     m_page->pageThrottler().didReceiveUserInput();
1811
1812     bool handled = false;
1813
1814     if (canHandleUserEvents()) {
1815         CurrentEvent currentEvent(wheelEvent);
1816
1817         handled = handleWheelEvent(wheelEvent, m_page.get());
1818     }
1819     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1820 }
1821
1822 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1823 {
1824     CurrentEvent currentEvent(wheelEvent);
1825
1826     handled = handleWheelEvent(wheelEvent, m_page.get());
1827 }
1828
1829 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1830 {
1831     if (!page->mainFrame().view())
1832         return false;
1833
1834     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1835         return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent));
1836     return page->userInputBridge().handleKeyEvent(platform(keyboardEvent));
1837 }
1838
1839 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1840 {
1841     m_page->pageThrottler().didReceiveUserInput();
1842
1843     bool handled = false;
1844
1845     if (canHandleUserEvents()) {
1846         CurrentEvent currentEvent(keyboardEvent);
1847
1848         handled = handleKeyEvent(keyboardEvent, m_page.get());
1849         // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1850         if (!handled)
1851             handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1852     }
1853     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1854 }
1855
1856 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
1857 {
1858     CurrentEvent currentEvent(keyboardEvent);
1859
1860     Frame& frame = m_page->focusController().focusedOrMainFrame();
1861     frame.document()->updateStyleIfNeeded();
1862
1863     handled = handleKeyEvent(keyboardEvent, m_page.get());
1864     if (!handled)
1865         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1866 }
1867
1868 WKTypeRef WebPage::pageOverlayCopyAccessibilityAttributeValue(WKStringRef attribute, WKTypeRef parameter)
1869 {
1870     if (!m_pageOverlays.size())
1871         return 0;
1872     PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1873     for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) {
1874         WKTypeRef value = (*it)->copyAccessibilityAttributeValue(attribute, parameter);
1875         if (value)
1876             return value;
1877     }
1878     return 0;
1879 }
1880
1881 WKArrayRef WebPage::pageOverlayCopyAccessibilityAttributesNames(bool parameterizedNames)
1882 {
1883     if (!m_pageOverlays.size())
1884         return 0;
1885     PageOverlayList::reverse_iterator end = m_pageOverlays.rend();
1886     for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) {
1887         WKArrayRef value = (*it)->copyAccessibilityAttributeNames(parameterizedNames);
1888         if (value)
1889             return value;
1890     }
1891     return 0;
1892 }
1893
1894 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1895 {
1896     bool isEnabled = false;
1897     int32_t state = 0;
1898     Frame& frame = m_page->focusController().focusedOrMainFrame();
1899     if (PluginView* pluginView = focusedPluginViewForFrame(frame))
1900         isEnabled = pluginView->isEditingCommandEnabled(commandName);
1901     else {
1902         Editor::Command command = frame.editor().command(commandName);
1903         state = command.state();
1904         isEnabled = command.isSupported() && command.isEnabled();
1905     }
1906
1907     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1908 }
1909
1910 void WebPage::executeEditCommand(const String& commandName)
1911 {
1912     executeEditingCommand(commandName, String());
1913 }
1914
1915 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1916 {
1917     const BackForwardListItemVector& list = sessionState.list();
1918     size_t size = list.size();
1919     uint64_t currentItemID = 0;
1920     for (size_t i = 0; i < size; ++i) {
1921         WebBackForwardListItem* webItem = list[i].get();
1922         DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1923         
1924         RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1925         if (!item) {
1926             LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1927             return 0;
1928         }
1929         
1930         if (i == sessionState.currentIndex())
1931             currentItemID = webItem->itemID();
1932         
1933         WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1934     }    
1935     ASSERT(currentItemID);
1936     return currentItemID;
1937 }
1938
1939 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState)
1940 {
1941     if (uint64_t currentItemID = restoreSession(sessionState))
1942         goToBackForwardItem(currentItemID);
1943 }
1944
1945 #if ENABLE(TOUCH_EVENTS)
1946 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1947 {
1948     if (!page->mainFrame().view())
1949         return false;
1950
1951     return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent));
1952 }
1953
1954 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1955 {
1956     bool handled = false;
1957
1958     if (canHandleUserEvents()) {
1959         CurrentEvent currentEvent(touchEvent);
1960
1961         handled = handleTouchEvent(touchEvent, m_page.get());
1962     }
1963     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1964 }
1965
1966 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
1967 {
1968     CurrentEvent currentEvent(touchEvent);
1969     handled = handleTouchEvent(touchEvent, m_page.get());
1970 }
1971 #endif
1972
1973 bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1974 {
1975     return page->userInputBridge().scrollRecursively(direction, granularity);
1976 }
1977
1978 bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1979 {
1980     return page->userInputBridge().logicalScrollRecursively(direction, granularity);
1981 }
1982
1983 bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1984 {
1985     return scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1986 }
1987
1988 void WebPage::centerSelectionInVisibleArea()
1989 {
1990     Frame& frame = m_page->focusController().focusedOrMainFrame();
1991     frame.selection().revealSelection(ScrollAlignment::alignCenterAlways);
1992     m_findController.showFindIndicatorInSelection();
1993 }
1994
1995 #if ENABLE(REMOTE_INSPECTOR)
1996 void WebPage::setAllowsRemoteInspection(bool allow)
1997 {
1998     m_page->setRemoteInspectionAllowed(allow);
1999 }
2000 #endif
2001
2002 void WebPage::setDrawsBackground(bool drawsBackground)
2003 {
2004     if (m_drawsBackground == drawsBackground)
2005         return;
2006
2007     m_drawsBackground = drawsBackground;
2008
2009     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2010         if (FrameView* view = coreFrame->view())
2011             view->setTransparent(!drawsBackground);
2012     }
2013
2014     m_drawingArea->pageBackgroundTransparencyChanged();
2015     m_drawingArea->setNeedsDisplay();
2016 }
2017
2018 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
2019 {
2020     if (m_drawsTransparentBackground == drawsTransparentBackground)
2021         return;
2022
2023     m_drawsTransparentBackground = drawsTransparentBackground;
2024
2025     Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2026     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2027         if (FrameView* view = coreFrame->view())
2028             view->setBaseBackgroundColor(backgroundColor);
2029     }
2030
2031     m_drawingArea->pageBackgroundTransparencyChanged();
2032     m_drawingArea->setNeedsDisplay();
2033 }
2034
2035 void WebPage::viewWillStartLiveResize()
2036 {
2037     if (!m_page)
2038         return;
2039
2040     // FIXME: This should propagate to all ScrollableAreas.
2041     Frame& frame = m_page->focusController().focusedOrMainFrame();
2042     if (FrameView* view = frame.view())
2043         view->willStartLiveResize();
2044 }
2045
2046 void WebPage::viewWillEndLiveResize()
2047 {
2048     if (!m_page)
2049         return;
2050
2051     // FIXME: This should propagate to all ScrollableAreas.
2052     Frame& frame = m_page->focusController().focusedOrMainFrame();
2053     if (FrameView* view = frame.view())
2054         view->willEndLiveResize();
2055 }
2056
2057 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
2058 {
2059     if (!m_page)
2060         return;
2061
2062     Frame& frame = m_page->focusController().focusedOrMainFrame();
2063     frame.document()->setFocusedElement(0);
2064
2065     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2066         PlatformKeyboardEvent platformEvent(platform(event));
2067         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2068         m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get());
2069         return;
2070     }
2071
2072     m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2073 }
2074
2075 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
2076 {
2077     if (m_windowResizerSize == windowResizerSize)
2078         return;
2079
2080     m_windowResizerSize = windowResizerSize;
2081
2082     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) {
2083         FrameView* view = coreFrame->view();
2084         if (view)
2085             view->windowResizerRectChanged();
2086     }
2087 }
2088
2089 void WebPage::setCanStartMediaTimerFired()
2090 {
2091     if (m_page)
2092         m_page->setCanStartMedia(true);
2093 }
2094
2095 #if !PLATFORM(MAC)
2096 void WebPage::didUpdateViewStateTimerFired()
2097 {
2098     send(Messages::WebPageProxy::DidUpdateViewState());
2099 }
2100 #endif
2101
2102 inline bool WebPage::canHandleUserEvents() const
2103 {
2104 #if USE(TILED_BACKING_STORE)
2105     // Should apply only if the area was frozen by didStartPageTransition().
2106     return !m_drawingArea->layerTreeStateIsFrozen();
2107 #endif
2108     return true;
2109 }
2110
2111 void WebPage::updateIsInWindow(bool isInitialState)
2112 {
2113     bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow;
2114
2115     if (!isInWindow) {
2116         m_setCanStartMediaTimer.stop();
2117         m_page->setCanStartMedia(false);
2118         
2119         // The WebProcess does not yet know about this page; no need to tell it we're leaving the window.
2120         if (!isInitialState)
2121             WebProcess::shared().pageWillLeaveWindow(m_pageID);
2122     } else {
2123         // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process
2124         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2125         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2126         if (m_mayStartMediaWhenInWindow)
2127             m_setCanStartMediaTimer.startOneShot(0);
2128
2129         WebProcess::shared().pageDidEnterWindow(m_pageID);
2130     }
2131
2132     if (isInWindow)
2133         layoutIfNeeded();
2134 }
2135
2136 void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState)
2137 {
2138     ViewState::Flags changed = m_viewState ^ viewState;
2139     m_viewState = viewState;
2140
2141     m_drawingArea->viewStateDidChange(changed);
2142     m_page->setViewState(viewState);
2143     for (auto* pluginView : m_pluginViews)
2144         pluginView->viewStateDidChange(changed);
2145
2146     if (changed & ViewState::IsInWindow)
2147         updateIsInWindow();
2148
2149     if (wantsDidUpdateViewState)
2150         m_sendDidUpdateViewStateTimer.startOneShot(0);
2151 }
2152
2153 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2154 {
2155     m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2156
2157     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2158
2159     for (auto* pluginView : m_pluginViews)
2160         pluginView->setLayerHostingMode(m_layerHostingMode);
2161 }
2162
2163 SessionID WebPage::sessionID() const
2164 {
2165     if (m_page->isSessionIDSet())
2166         return m_page->sessionID();
2167
2168     return m_page->settings().privateBrowsingEnabled() ? SessionID::legacyPrivateSessionID() : SessionID::defaultSessionID();
2169 }
2170
2171 bool WebPage::isUsingEphemeralSession() const
2172 {
2173     return sessionID().isEphemeral();
2174 }
2175
2176 void WebPage::setSessionID(SessionID sessionID)
2177 {
2178     m_page->setSessionID(sessionID);
2179     if (sessionID.isEphemeral())
2180         WebProcess::shared().ensurePrivateBrowsingSession(sessionID);
2181 }
2182
2183 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
2184 {
2185     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2186     if (!frame)
2187         return;
2188     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
2189 }
2190
2191 void WebPage::didStartPageTransition()
2192 {
2193     m_drawingArea->setLayerTreeStateIsFrozen(true);
2194 }
2195
2196 void WebPage::didCompletePageTransition()
2197 {
2198 #if USE(TILED_BACKING_STORE)
2199     if (m_mainFrame->coreFrame()->view()->delegatesScrolling())
2200         // Wait until the UI process sent us the visible rect it wants rendered.
2201         send(Messages::WebPageProxy::PageTransitionViewportReady());
2202     else
2203 #endif
2204         
2205     m_drawingArea->setLayerTreeStateIsFrozen(false);
2206 }
2207
2208 void WebPage::show()
2209 {
2210     send(Messages::WebPageProxy::ShowPage());
2211 }
2212
2213 void WebPage::setUserAgent(const String& userAgent)
2214 {
2215     m_userAgent = userAgent;
2216 }
2217
2218 void WebPage::suspendActiveDOMObjectsAndAnimations()
2219 {
2220     m_page->suspendActiveDOMObjectsAndAnimations();
2221 }
2222
2223 void WebPage::resumeActiveDOMObjectsAndAnimations()
2224 {
2225     m_page->resumeActiveDOMObjectsAndAnimations();
2226 }
2227
2228 IntPoint WebPage::screenToRootView(const IntPoint& point)
2229 {
2230     IntPoint windowPoint;
2231     sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint));
2232     return windowPoint;
2233 }
2234     
2235 IntRect WebPage::rootViewToScreen(const IntRect& rect)
2236 {
2237     IntRect screenRect;
2238     sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect));
2239     return screenRect;
2240 }
2241
2242 IntRect WebPage::windowResizerRect() const
2243 {
2244     if (m_windowResizerSize.isEmpty())
2245         return IntRect();
2246
2247     IntSize frameViewSize;
2248     if (Frame* coreFrame = m_mainFrame->coreFrame()) {
2249         if (FrameView* view = coreFrame->view())
2250             frameViewSize = view->size();
2251     }
2252
2253     return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(), 
2254                    m_windowResizerSize.width(), m_windowResizerSize.height());
2255 }
2256
2257 KeyboardUIMode WebPage::keyboardUIMode()
2258 {
2259     bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
2260     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2261 }
2262
2263 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2264 {
2265     // NOTE: We need to be careful when running scripts that the objects we depend on don't
2266     // disappear during script execution.
2267
2268     // Retain the SerializedScriptValue at this level so it (and the internal data) lives
2269     // long enough for the DataReference to be encoded by the sent message.
2270     RefPtr<SerializedScriptValue> serializedResultValue;
2271     IPC::DataReference dataReference;
2272
2273     JSLockHolder lock(JSDOMWindow::commonVM());
2274     if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) {
2275         if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
2276             dataReference = serializedResultValue->data();
2277     }
2278
2279     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2280 }
2281
2282 void WebPage::getContentsAsString(uint64_t callbackID)
2283 {
2284     String resultString = m_mainFrame->contentsAsString();
2285     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2286 }
2287
2288 #if ENABLE(MHTML)
2289 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2290 {
2291     IPC::DataReference dataReference;
2292
2293     RefPtr<SharedBuffer> buffer = useBinaryEncoding
2294         ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2295         : MHTMLArchive::generateMHTMLData(m_page.get());
2296
2297     if (buffer)
2298         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2299
2300     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2301 }
2302 #endif
2303
2304 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2305 {
2306     String resultString = renderTreeExternalRepresentation();
2307     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2308 }
2309
2310 static Frame* frameWithSelection(Page* page)
2311 {
2312     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2313         if (frame->selection().isRange())
2314             return frame;
2315     }
2316
2317     return 0;
2318 }
2319
2320 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2321 {
2322     IPC::DataReference dataReference;
2323
2324 #if PLATFORM(COCOA)
2325     RefPtr<LegacyWebArchive> archive;
2326     RetainPtr<CFDataRef> data;
2327
2328     Frame* frame = frameWithSelection(m_page.get());
2329     if (frame) {
2330         archive = LegacyWebArchive::createFromSelection(frame);
2331         data = archive->rawDataRepresentation();
2332         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2333     }
2334 #endif
2335
2336     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2337 }
2338
2339 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2340 {
2341     String resultString = m_mainFrame->selectionAsString();
2342     if (resultString.isEmpty())
2343         resultString = m_mainFrame->contentsAsString();
2344     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2345 }
2346
2347 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2348 {
2349     String resultString;
2350     if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
2351        resultString = frame->source();
2352
2353     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2354 }
2355
2356 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2357 {
2358     IPC::DataReference dataReference;
2359
2360     RefPtr<ResourceBuffer> buffer;
2361     RefPtr<SharedBuffer> pdfResource;
2362     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2363         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame())) {
2364             if ((pdfResource = pluginView->liveResourceData()))
2365                 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(pdfResource->data()), pdfResource->size());
2366         }
2367
2368         if (dataReference.isEmpty()) {
2369             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader()) {
2370                 if ((buffer = loader->mainResourceData()))
2371                     dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2372             }
2373         }
2374     }
2375
2376     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2377 }
2378
2379 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2380 {
2381     DocumentLoader* loader = frame->loader().documentLoader();
2382     if (!loader)
2383         return 0;
2384
2385     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2386     if (!subresource)
2387         return 0;
2388
2389     return subresource->data();
2390 }
2391
2392 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2393 {
2394     IPC::DataReference dataReference;
2395     URL resourceURL(URL(), resourceURLString);
2396
2397     RefPtr<SharedBuffer> buffer;
2398     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2399         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2400         if (!buffer) {
2401             // Try to get the resource data from the cache.
2402             buffer = cachedResponseDataForURL(resourceURL);
2403         }
2404
2405         if (buffer)
2406             dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2407     }
2408
2409     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2410 }
2411
2412 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2413 {
2414     IPC::DataReference dataReference;
2415
2416 #if PLATFORM(COCOA)
2417     RetainPtr<CFDataRef> data;
2418     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2419         if ((data = frame->webArchiveData(0, 0)))
2420             dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2421     }
2422 #else
2423     UNUSED_PARAM(frameID);
2424 #endif
2425
2426     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2427 }
2428
2429 void WebPage::forceRepaintWithoutCallback()
2430 {
2431     m_drawingArea->forceRepaint();
2432 }
2433
2434 void WebPage::forceRepaint(uint64_t callbackID)
2435 {
2436     if (m_drawingArea->forceRepaintAsync(callbackID))
2437         return;
2438
2439     forceRepaintWithoutCallback();
2440     send(Messages::WebPageProxy::VoidCallback(callbackID));
2441 }
2442
2443 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2444 {
2445     WebPreferencesStore::removeTestRunnerOverrides();
2446     updatePreferences(store);
2447 }
2448
2449 void WebPage::updatePreferences(const WebPreferencesStore& store)
2450 {
2451     Settings& settings = m_page->settings();
2452
2453     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2454     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2455     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2456     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2457
2458     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2459
2460 #if PLATFORM(COCOA)
2461     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2462 #endif
2463
2464     // FIXME: This should be generated from macro expansion for all preferences,
2465     // but we currently don't match the naming of WebCore exactly so we are
2466     // handrolling the boolean and integer preferences until that is fixed.
2467
2468 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2469
2470     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2471
2472 #undef INITIALIZE_SETTINGS
2473
2474     settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2475     settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2476     settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2477     settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2478     settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2479     settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2480     settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));    
2481     settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2482     settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2483     settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2484     settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2485     if (m_page->isSessionIDSet())
2486         settings.setPrivateBrowsingEnabled(m_page->sessionID().isEphemeral());
2487     else
2488         settings.setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
2489     settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2490     settings.setJavaScriptExperimentsEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptExperimentsEnabledKey()));
2491     settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2492     settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2493     settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2494     settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2495     settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2496 #if ENABLE(WEB_ARCHIVE)
2497     settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2498 #endif
2499     settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2500     settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2501     settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2502     settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2503     settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2504     settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2505     settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2506     settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2507     settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2508     settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2509     settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2510
2511     settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2512     settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2513     settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2514     settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2515     settings.setScreenFontSubstitutionEnabled(store.getBoolValueForKey(WebPreferencesKey::screenFontSubstitutionEnabledKey())
2516 #if PLATFORM(COCOA)
2517         || WebProcess::shared().shouldForceScreenFontSubstitution()
2518 #endif
2519     );
2520     settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2521     settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2522     settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2523     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2524     settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2525
2526     settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2527     settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2528     settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2529     settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2530     settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2531     settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2532     settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2533     settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2534     RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2535     RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2536 #if ENABLE(CSS_GRID_LAYOUT)
2537     settings.setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
2538 #endif
2539     settings.setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
2540     settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2541     settings.setMultithreadedWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::multithreadedWebGLEnabledKey()));
2542     settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2543     settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2544     settings.setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
2545     settings.setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
2546     settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2547     settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2548     settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2549 #if ENABLE(SMOOTH_SCROLLING)
2550     settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2551 #endif
2552     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2553     settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2554
2555 #if ENABLE(SQL_DATABASE)
2556     DatabaseManager::manager().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2557 #endif
2558
2559 #if ENABLE(FULLSCREEN_API)
2560     settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2561 #endif
2562
2563 #if USE(AVFOUNDATION)
2564     settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2565 #endif
2566
2567 #if PLATFORM(COCOA)
2568     settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2569 #endif
2570
2571 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2572     settings.setVideoPluginProxyEnabled(false);
2573 #endif
2574
2575 #if PLATFORM(IOS)
2576     settings.setAVKitEnabled(true);
2577 #endif
2578
2579 #if ENABLE(IOS_TEXT_AUTOSIZING)
2580     settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey()));
2581 #endif
2582
2583 #if ENABLE(WEB_AUDIO)
2584     settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2585 #endif
2586
2587 #if ENABLE(MEDIA_STREAM)
2588     settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2589 #endif
2590
2591 #if ENABLE(IMAGE_CONTROLS)
2592     settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey()));
2593 #endif
2594
2595     settings.setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2596     settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2597     settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2598     settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2599     settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2600     settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2601
2602 #if ENABLE(VIDEO_TRACK)
2603     settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2604     settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2605     settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2606 #endif
2607
2608 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2609     settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2610 #endif
2611
2612     settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2613     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2614     settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2615
2616     settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2617
2618     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2619
2620     settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2621     settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2622     settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2623     settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2624     settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2625
2626 #if ENABLE(TEXT_AUTOSIZING)
2627     settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2628 #endif
2629
2630     settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2631     settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2632
2633     settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2634     settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2635     settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2636
2637 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2638     settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2639 #endif
2640 #if ENABLE(PAGE_VISIBILITY_API)
2641     settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2642 #endif
2643
2644     settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2645     settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2646     settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2647
2648     settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2649
2650 #if ENABLE(MEDIA_SOURCE)
2651     settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2652 #endif
2653
2654     settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey()));
2655
2656     settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey()));
2657     settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey()));
2658     settings.setAlwaysUseBaselineOfPrimaryFont(store.getBoolValueForKey(WebPreferencesKey::alwaysUseBaselineOfPrimaryFontKey()));
2659     settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey()));
2660     settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey()));
2661
2662     settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey()));
2663     settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey()));
2664     
2665     settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey()))));
2666     settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey()));
2667
2668     settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey()));
2669
2670     if (store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey()))
2671         m_processSuppressionDisabledByWebPreference.stop();
2672     else
2673         m_processSuppressionDisabledByWebPreference.start();
2674
2675     platformPreferencesDidChange(store);
2676
2677     if (m_drawingArea)
2678         m_drawingArea->updatePreferences(store);
2679 }
2680
2681 #if PLATFORM(COCOA)
2682 void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction)
2683 {
2684     layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize());
2685     layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor());
2686     layerTransaction.setRenderTreeSize(corePage()->renderTreeSize());
2687     layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor());
2688 #if PLATFORM(IOS)
2689     layerTransaction.setLastVisibleContentRectUpdateID(m_lastVisibleContentRectUpdateID);
2690     layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess());
2691     layerTransaction.setMinimumScaleFactor(minimumPageScaleFactor());
2692     layerTransaction.setMaximumScaleFactor(maximumPageScaleFactor());
2693     layerTransaction.setAllowsUserScaling(allowsUserScaling());
2694 #endif
2695 }
2696 #endif
2697
2698     
2699 #if ENABLE(INSPECTOR)
2700 WebInspector* WebPage::inspector()
2701 {
2702     if (m_isClosed)
2703         return 0;
2704     if (!m_inspector)
2705         m_inspector = WebInspector::create(this, m_inspectorClient);
2706     return m_inspector.get();
2707 }
2708 #endif
2709     
2710 #if PLATFORM(IOS)
2711 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
2712 {
2713     if (!m_videoFullscreenManager)
2714         m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
2715     return m_videoFullscreenManager.get();
2716 }
2717 #endif
2718
2719 #if ENABLE(FULLSCREEN_API)
2720 WebFullScreenManager* WebPage::fullScreenManager()
2721 {
2722     if (!m_fullScreenManager)
2723         m_fullScreenManager = WebFullScreenManager::create(this);
2724     return m_fullScreenManager.get();
2725 }
2726 #endif
2727
2728 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2729 {
2730     if (m_notificationPermissionRequestManager)
2731         return m_notificationPermissionRequestManager.get();
2732
2733     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2734     return m_notificationPermissionRequestManager.get();
2735 }
2736
2737 #if !PLATFORM(GTK) && !PLATFORM(COCOA)
2738 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2739 {
2740     Node* node = evt->target()->toNode();
2741     ASSERT(node);
2742     Frame* frame = node->document().frame();
2743     ASSERT(frame);
2744
2745     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2746     if (!keyEvent)
2747         return false;
2748
2749     Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
2750
2751     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2752         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2753         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2754         // (e.g. Tab that inserts a Tab character, or Enter).
2755         return !command.isTextInsertion() && command.execute(evt);
2756     }
2757
2758     if (command.execute(evt))
2759         return true;
2760
2761     // Don't allow text insertion for nodes that cannot edit.
2762     if (!frame->editor().canEdit())
2763         return false;
2764
2765     // Don't insert null or control characters as they can result in unexpected behaviour
2766     if (evt->charCode() < ' ')
2767         return false;
2768
2769     return frame->editor().insertText(evt->keyEvent()->text(), evt);
2770 }
2771 #endif
2772
2773 #if ENABLE(DRAG_SUPPORT)
2774
2775 #if PLATFORM(GTK)
2776 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2777 {
2778     if (!m_page) {
2779         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2780         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2781         data->deref();
2782         return;
2783     }
2784
2785     switch (action) {
2786     case DragControllerActionEntered:
2787         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData)));
2788         break;
2789
2790     case DragControllerActionUpdated:
2791         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData)));
2792         break;
2793
2794     case DragControllerActionExited:
2795         m_page->dragController().dragExited(dragData);
2796         break;
2797
2798     case DragControllerActionPerformDrag: {
2799         m_page->dragController().performDrag(dragData);
2800         break;
2801     }
2802
2803     default:
2804         ASSERT_NOT_REACHED();
2805     }
2806     // DragData does not delete its platformData so we need to do that here.
2807     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2808     data->deref();
2809 }
2810
2811 #else
2812 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)
2813 {
2814     if (!m_page) {
2815         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2816         return;
2817     }
2818
2819     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2820     switch (action) {
2821     case DragControllerActionEntered:
2822         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData)));
2823         break;
2824
2825     case DragControllerActionUpdated:
2826         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData)));
2827         break;
2828         
2829     case DragControllerActionExited:
2830         m_page->dragController().dragExited(dragData);
2831         break;
2832         
2833     case DragControllerActionPerformDrag: {
2834         ASSERT(!m_pendingDropSandboxExtension);
2835
2836         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2837         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
2838             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
2839                 m_pendingDropExtensionsForFileUpload.append(extension);
2840         }
2841
2842         m_page->dragController().performDrag(dragData);
2843
2844         // If we started loading a local file, the sandbox extension tracker would have adopted this
2845         // pending drop sandbox extension. If not, we'll play it safe and clear it.
2846         m_pendingDropSandboxExtension = nullptr;
2847
2848         m_pendingDropExtensionsForFileUpload.clear();
2849         break;
2850     }
2851
2852     default:
2853         ASSERT_NOT_REACHED();
2854     }
2855 }
2856 #endif
2857
2858 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2859 {
2860     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
2861     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
2862
2863     m_page->dragController().dragEnded();
2864     FrameView* view = m_page->mainFrame().view();
2865     if (!view)
2866         return;
2867     // FIXME: These are fake modifier keys here, but they should be real ones instead.
2868     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2869     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
2870 }
2871
2872 void WebPage::willPerformLoadDragDestinationAction()
2873 {
2874     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2875 }
2876
2877 void WebPage::mayPerformUploadDragDestinationAction()
2878 {
2879     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2880         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
2881     m_pendingDropExtensionsForFileUpload.clear();
2882 }
2883     
2884 #endif // ENABLE(DRAG_SUPPORT)
2885
2886 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2887 {
2888     return m_undoStepMap.get(stepID);
2889 }
2890
2891 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2892 {
2893     m_undoStepMap.set(stepID, entry);
2894 }
2895
2896 void WebPage::removeWebEditCommand(uint64_t stepID)
2897 {
2898     m_undoStepMap.remove(stepID);
2899 }
2900
2901 void WebPage::unapplyEditCommand(uint64_t stepID)
2902 {
2903     WebUndoStep* step = webUndoStep(stepID);
2904     if (!step)
2905         return;
2906
2907     step->step()->unapply();
2908 }
2909
2910 void WebPage::reapplyEditCommand(uint64_t stepID)
2911 {
2912     WebUndoStep* step = webUndoStep(stepID);
2913     if (!step)
2914         return;
2915
2916     m_isInRedo = true;
2917     step->step()->reapply();
2918     m_isInRedo = false;
2919 }
2920
2921 void WebPage::didRemoveEditCommand(uint64_t commandID)
2922 {
2923     removeWebEditCommand(commandID);
2924 }
2925
2926 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2927 {
2928     m_activePopupMenu = menu;
2929 }
2930
2931 #if ENABLE(INPUT_TYPE_COLOR)
2932 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
2933 {
2934     m_activeColorChooser = colorChooser;
2935 }
2936
2937 void WebPage::didEndColorPicker()
2938 {
2939     m_activeColorChooser->didEndChooser();
2940 }
2941
2942 void WebPage::didChooseColor(const WebCore::Color& color)
2943 {
2944     m_activeColorChooser->didChooseColor(color);
2945 }
2946 #endif
2947
2948 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2949 {
2950     m_activeOpenPanelResultListener = openPanelResultListener;
2951 }
2952
2953 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2954 {
2955     return m_page->findString(target, options);
2956 }
2957
2958 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2959 {
2960     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2961 }
2962
2963 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2964 {
2965     m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2966 }
2967
2968 void WebPage::getImageForFindMatch(uint32_t matchIndex)
2969 {
2970     m_findController.getImageForFindMatch(matchIndex);
2971 }
2972
2973 void WebPage::selectFindMatch(uint32_t matchIndex)
2974 {
2975     m_findController.selectFindMatch(matchIndex);
2976 }
2977
2978 void WebPage::hideFindUI()
2979 {
2980     m_findController.hideFindUI();
2981 }
2982
2983 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2984 {
2985     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2986 }
2987
2988 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2989 {
2990     changeSelectedIndex(newIndex);
2991     m_activePopupMenu = 0;
2992 }
2993
2994 void WebPage::changeSelectedIndex(int32_t index)
2995 {
2996     if (!m_activePopupMenu)
2997         return;
2998
2999     m_activePopupMenu->didChangeSelectedIndex(index);
3000 }
3001
3002 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
3003 {
3004     if (!m_activeOpenPanelResultListener)
3005         return;
3006
3007     m_activeOpenPanelResultListener->didChooseFiles(files);
3008     m_activeOpenPanelResultListener = 0;
3009 }
3010
3011 void WebPage::didCancelForOpenPanel()
3012 {
3013     m_activeOpenPanelResultListener = 0;
3014 }
3015
3016 #if ENABLE(WEB_PROCESS_SANDBOX)
3017 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
3018 {
3019     SandboxExtension::create(handle)->consumePermanently();
3020 }
3021 #endif
3022
3023 #if ENABLE(GEOLOCATION)
3024 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
3025 {
3026     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
3027 }
3028 #endif
3029
3030 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
3031 {
3032     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
3033 }
3034
3035 #if !PLATFORM(IOS)
3036 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
3037 {
3038     Frame& frame = m_page->focusController().focusedOrMainFrame();
3039     frame.editor().advanceToNextMisspelling(startBeforeSelection);
3040 }
3041 #endif
3042
3043 void WebPage::changeSpellingToWord(const String& word)
3044 {
3045     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
3046 }
3047
3048 void WebPage::unmarkAllMisspellings()
3049 {
3050     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3051         if (Document* document = frame->document())
3052             document->markers().removeMarkers(DocumentMarker::Spelling);
3053     }
3054 }
3055
3056 void WebPage::unmarkAllBadGrammar()
3057 {
3058     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3059         if (Document* document = frame->document())
3060             document->markers().removeMarkers(DocumentMarker::Grammar);
3061     }
3062 }
3063
3064 #if USE(APPKIT)
3065 void WebPage::uppercaseWord()
3066 {
3067     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
3068 }
3069
3070 void WebPage::lowercaseWord()
3071 {
3072     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
3073 }
3074
3075 void WebPage::capitalizeWord()
3076 {
3077     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
3078 }
3079 #endif
3080     
3081 void WebPage::setTextForActivePopupMenu(int32_t index)
3082 {
3083     if (!m_activePopupMenu)
3084         return;
3085
3086     m_activePopupMenu->setTextForIndex(index);
3087 }
3088
3089 #if PLATFORM(GTK)
3090 void WebPage::failedToShowPopupMenu()
3091 {
3092     if (!m_activePopupMenu)
3093         return;
3094
3095     m_activePopupMenu->client()->popupDidHide();
3096 }
3097 #endif
3098
3099 #if ENABLE(CONTEXT_MENUS)
3100 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3101 {
3102     if (!m_contextMenu)
3103         return;
3104
3105     m_contextMenu->itemSelected(item);
3106     m_contextMenu = 0;
3107 }
3108 #endif
3109
3110 #if ENABLE(IMAGE_CONTROLS)
3111 void WebPage::replaceControlledImage(const ShareableBitmap::Handle& bitmapHandle)
3112 {
3113     RefPtr<ShareableBitmap> bitmap = ShareableBitmap::create(bitmapHandle);
3114     if (bitmap)
3115         m_contextMenu->replaceControlledImage(bitmap->createImage());
3116 }
3117 #endif
3118
3119 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3120 {
3121     bool selectReplacement = true;
3122     bool smartReplace = false;
3123     return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3124 }
3125
3126 #if !PLATFORM(IOS)
3127 void WebPage::clearSelection()
3128 {
3129     m_page->focusController().focusedOrMainFrame().selection().clear();
3130 }
3131 #endif
3132
3133 bool WebPage::mainFrameHasCustomContentProvider() const
3134 {
3135     if (Frame* frame = mainFrame()) {
3136         WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client());
3137         ASSERT(webFrameLoaderClient);
3138         return webFrameLoaderClient->frameHasCustomContentProvider();
3139     }
3140
3141     return false;
3142 }
3143
3144 void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType)
3145 {
3146     m_mimeTypesWithCustomContentProviders.add(mimeType);
3147 }
3148
3149 void WebPage::updateMainFrameScrollOffsetPinning()
3150 {
3151     Frame& frame = m_page->mainFrame();
3152     IntPoint scrollPosition = frame.view()->scrollPosition();
3153     IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3154     IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3155
3156     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3157     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3158     bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3159     bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3160
3161     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3162         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3163         
3164         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3165         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3166         m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3167         m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3168     }
3169 }
3170
3171 void WebPage::mainFrameDidLayout()
3172 {
3173     unsigned pageCount = m_page->pageCount();
3174     if (pageCount != m_cachedPageCount) {
3175         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3176         m_cachedPageCount = pageCount;
3177     }
3178
3179 #if USE(TILED_BACKING_STORE)
3180     if (m_drawingArea && m_drawingArea->layerTreeHost()) {
3181         double red, green, blue, alpha;
3182         m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha);
3183         RGBA32 rgba = makeRGBA32FromFloats(red, green, blue, alpha);
3184         if (m_backgroundColor.rgb() != rgba) {
3185             m_backgroundColor.setRGB(rgba);
3186             m_drawingArea->layerTreeHost()->setBackgroundColor(m_backgroundColor);
3187         }
3188     }
3189 #endif
3190
3191 #if PLATFORM(MAC)
3192     m_viewGestureGeometryCollector.mainFrameDidLayout();
3193 #endif
3194 #if PLATFORM(IOS)
3195     if (FrameView* frameView = mainFrameView()) {
3196         m_viewportConfiguration.setContentsSize(frameView->contentsSize());
3197         viewportConfigurationChanged();
3198     }
3199 #endif
3200 }
3201
3202 void WebPage::addPluginView(PluginView* pluginView)
3203 {
3204     ASSERT(!m_pluginViews.contains(pluginView));
3205
3206     m_pluginViews.add(pluginView);
3207     m_hasSeenPlugin = true;
3208 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3209     LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3210     m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3211 #endif
3212 }
3213
3214 void WebPage::removePluginView(PluginView* pluginView)
3215 {
3216     ASSERT(m_pluginViews.contains(pluginView));
3217
3218     m_pluginViews.remove(pluginView);
3219 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3220     LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3221 #endif
3222 }
3223
3224 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3225 {
3226 #if PLATFORM(COCOA)
3227     m_hasCachedWindowFrame = false;
3228 #endif
3229     send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3230 }
3231
3232 #if PLATFORM(COCOA)
3233 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3234 {
3235     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3236     m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3237     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3238     m_accessibilityPosition = accessibilityViewCoordinates;
3239     
3240     // Tell all our plug-in views that the window and view frames have changed.
3241     for (auto* pluginView : m_pluginViews)
3242         pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3243
3244     m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3245 }
3246 #endif
3247
3248 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3249 {
3250     m_mainFrameIsScrollable = isScrollable;
3251     m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3252
3253     if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3254         frameView->setCanHaveScrollbars(isScrollable);
3255         frameView->setProhibitsScrolling(!isScrollable);
3256     }
3257 }
3258
3259 bool WebPage::windowIsFocused() const
3260 {
3261     return m_page->focusController().isActive();
3262 }
3263
3264 bool WebPage::windowAndWebPageAreFocused() const
3265 {
3266     if (!isVisible())
3267         return false;
3268
3269     return m_page->focusController().isFocused() && m_page->focusController().isActive();
3270 }
3271
3272 void WebPage::didReceiveMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder)
3273 {
3274     if (decoder.messageReceiverName() == Messages::DrawingArea::messageReceiverName()) {
3275         if (m_drawingArea)
3276             m_drawingArea->didReceiveDrawingAreaMessage(connection, decoder);
3277         return;
3278     }
3279
3280 #if USE(TILED_BACKING_STORE)
3281     if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
3282         if (m_drawingArea)
3283             m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
3284         return;
3285     }
3286 #endif
3287     
3288 #if ENABLE(INSPECTOR)
3289     if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
3290         if (WebInspector* inspector = this->inspector())
3291             inspector->didReceiveWebInspectorMessage(connection, decoder);
3292         return;
3293     }
3294 #endif
3295
3296 #if ENABLE(FULLSCREEN_API)
3297     if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
3298         fullScreenManager()->didReceiveMessage(connection, decoder);
3299         return;
3300     }
3301 #endif
3302
3303     didReceiveWebPageMessage(connection, decoder);
3304 }
3305
3306 void WebPage::didReceiveSyncMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder)
3307 {   
3308     didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
3309 }
3310     
3311 InjectedBundleBackForwardList* WebPage::backForwardList()
3312 {
3313     if (!m_backForwardList)
3314         m_backForwardList = InjectedBundleBackForwardList::create(this);
3315     return m_backForwardList.get();
3316 }
3317
3318 #if ENABLE(ASYNC_SCROLLING)
3319 ScrollingCoordinator* WebPage::scrollingCoordinator() const
3320 {
3321     return m_page->scrollingCoordinator();
3322 }
3323 #endif
3324
3325 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3326 {
3327     invalidate();
3328 }
3329
3330 void WebPage::SandboxExtensionTracker::invalidate()
3331 {
3332     m_pendingProvisionalSandboxExtension = nullptr;
3333
3334     if (m_provisionalSandboxExtension) {
3335         m_provisionalSandboxExtension->revoke();
3336         m_provisionalSandboxExtension = nullptr;
3337     }
3338
3339     if (m_committedSandboxExtension) {
3340         m_committedSandboxExtension->revoke();
3341         m_committedSandboxExtension = nullptr;
3342     }
3343 }
3344
3345 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3346 {
3347     setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3348 }
3349
3350 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3351 {
3352     ASSERT_UNUSED(frame, frame->isMainFrame());
3353
3354     setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3355 }
3356
3357 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3358 {
3359     m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;    
3360 }
3361
3362 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3363 {
3364     ASSERT(frame->isMainFrame());
3365
3366     FrameLoader& frameLoader = frame->coreFrame()->loader();
3367     FrameLoadType frameLoadType = frameLoader.loadType();
3368
3369     // If the page is being reloaded, it should reuse whatever extension is committed.
3370     if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
3371         return true;
3372
3373     DocumentLoader* documentLoader = frameLoader.documentLoader();
3374     DocumentLoader* provisionalDocumentLoader = frameLoader.provisionalDocumentLoader();
3375     if (!documentLoader || !provisionalDocumentLoader)
3376         return false;
3377
3378     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3379         return true;
3380
3381     return false;
3382 }
3383
3384 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3385 {
3386     if (!frame->isMainFrame())
3387         return;
3388
3389     // We should only reuse the commited sandbox extension if it is not null. It can be
3390     // null if the last load was for an error page.
3391     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame))
3392         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension;
3393
3394     ASSERT(!m_provisionalSandboxExtension);
3395
3396     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3397     if (!m_provisionalSandboxExtension)
3398         return;
3399
3400     ASSERT(!m_provisionalSandboxExtension || frame->coreFrame()->loader().provisionalDocumentLoader()->url().isLocalFile());
3401
3402     m_provisionalSandboxExtension->consume();
3403 }
3404
3405 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3406 {
3407     if (!frame->isMainFrame())
3408         return;
3409
3410     if (m_committedSandboxExtension)
3411         m_committedSandboxExtension->revoke();
3412
3413     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3414
3415     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started.
3416     // This extension is not cleared, because it does not pertain to the failed load, and will be needed.
3417 }
3418
3419 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3420 {
3421     if (!frame->isMainFrame())
3422         return;
3423
3424     if (!m_provisionalSandboxExtension)
3425         return;
3426
3427     m_provisionalSandboxExtension->revoke();
3428     m_provisionalSandboxExtension = nullptr;
3429
3430     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started
3431     // (notably, if the current one fails because the new one cancels it). This extension is not cleared,
3432     // because it does not pertain to the failed load, and will be needed.
3433 }
3434
3435 bool WebPage::hasLocalDataForURL(const URL& url)
3436 {
3437     if (url.isLocalFile())
3438         return true;
3439
3440     DocumentLoader* documentLoader = m_page->mainFrame().loader().documentLoader();
3441     if (documentLoader && documentLoader->subresource(url))
3442         return true;
3443
3444     return platformHasLocalDataForURL(url);
3445 }
3446
3447 void WebPage::setCustomTextEncodingName(const String& encoding)
3448 {
3449     m_page->mainFrame().loader().reloadWithOverrideEncoding(encoding);
3450 }
3451
3452 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3453 {
3454     WebBackForwardListProxy::removeItem(itemID);
3455 }
3456
3457 #if PLATFORM(COCOA)
3458
3459 bool WebPage::isSpeaking()
3460 {
3461     bool result;
3462     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3463 }
3464
3465 void WebPage::speak(const String& string)
3466 {
3467     send(Messages::WebPageProxy::Speak(string));
3468 }
3469
3470 void WebPage::stopSpeaking()
3471 {
3472     send(Messages::WebPageProxy::StopSpeaking());
3473 }
3474
3475 #endif
3476
3477 #if PLATFORM(MAC)
3478 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3479 {
3480     Document* document = coreFrame->document();
3481     if (!document)
3482         return 0;
3483
3484     if (!document->isPluginDocument())
3485         return 0;
3486
3487     PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
3488     if (!pluginView)
3489         return 0;
3490
3491     return pluginView->pdfDocumentForPrinting();
3492 }
3493 #endif // PLATFORM(MAC)
3494
3495 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3496 {
3497     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3498     if (!frame)
3499         return;
3500
3501     Frame* coreFrame = frame->coreFrame();
3502     if (!coreFrame)
3503         return;
3504
3505 #if PLATFORM(MAC)
3506     if (pdfDocumentForPrintingFrame(coreFrame))
3507         return;
3508 #endif // PLATFORM(MAC)
3509
3510     if (!m_printContext)
3511         m_printContext = adoptPtr(new PrintContext(coreFrame));
3512
3513     drawingArea()->setLayerTreeStateIsFrozen(true);
3514     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3515
3516     float fullPageHeight;
3517     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3518
3519 #if PLATFORM(GTK)
3520     if (!m_printOperation)
3521         m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3522 #endif
3523 }
3524
3525 void WebPage::endPrinting()
3526 {
3527     drawingArea()->setLayerTreeStateIsFrozen(false);
3528     m_printContext = nullptr;
3529 }
3530
3531 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3532 {
3533     Vector<IntRect> resultPageRects;
3534     double resultTotalScaleFactorForPrinting = 1;
3535
3536     beginPrinting(frameID, printInfo);
3537
3538     if (m_printContext) {
3539         resultPageRects = m_printContext->pageRects();
3540         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3541     }
3542 #if PLATFORM(COCOA)
3543     else
3544         computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3545 #endif // PLATFORM(COCOA)
3546
3547     // If we're asked to print, we should actually print at least a blank page.
3548     if (resultPageRects.isEmpty())
3549         resultPageRects.append(IntRect(0, 0, 1, 1));
3550
3551     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3552 }
3553
3554 #if PLATFORM(COCOA)
3555 void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, uint64_t callbackID)
3556 {
3557     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3558     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3559
3560     RefPtr<WebImage> image;
3561
3562 #if USE(CG)
3563     if (coreFrame) {
3564 #if PLATFORM(MAC)
3565         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3566 #else
3567         ASSERT(coreFrame->document()->printing());
3568 #endif
3569
3570         RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(imageSize, ShareableBitmap::SupportsAlpha);
3571         auto graphicsContext = bitmap->createGraphicsContext();
3572
3573         float printingScale = static_cast<float>(imageSize.width()) / rect.width();
3574         graphicsContext->scale(FloatSize(printingScale, printingScale));
3575
3576 #if PLATFORM(MAC)
3577         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3578             ASSERT(!m_printContext);
3579             graphicsContext->scale(FloatSize(1, -1));
3580             graphicsContext->translate(0, -rect.height());
3581             drawPDFDocument(graphicsContext->platformContext(), pdfDocument.get(), printInfo, rect);
3582         } else
3583 #endif
3584         {
3585             m_printContext->spoolRect(*graphicsContext, rect);
3586         }
3587
3588         image = WebImage::create(bitmap.release());
3589     }
3590 #endif
3591
3592     ShareableBitmap::Handle handle;
3593
3594     if (image)
3595         image->bitmap()->createHandle(handle, SharedMemory::ReadOnly);
3596
3597     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
3598 }
3599
3600 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3601 {
3602     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3603     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3604
3605     RetainPtr<CFMutableDataRef> pdfPageData = adoptCF(CFDataCreateMutable(0, 0));
3606
3607 #if USE(CG)
3608     if (coreFrame) {
3609
3610 #if PLATFORM(MAC)
3611         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3612 #else
3613         ASSERT(coreFrame->document()->printing());
3614 #endif
3615
3616         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3617         RetainPtr<CGDataConsumerRef> pdfDataConsumer = adoptCF(CGDataConsumerCreateWithCFData(pdfPageData.get()));
3618
3619         CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3620         RetainPtr<CGContextRef> context = adoptCF(CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3621
3622 #if PLATFORM(MAC)
3623         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3624             ASSERT(!m_printContext);
3625             drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3626         } else
3627 #endif
3628         {
3629             size_t pageCount = m_printContext->pageCount();
3630             for (uint32_t page = first; page < first + count; ++page) {
3631                 if (page >= pageCount)
3632                     break;
3633
3634                 RetainPtr<CFDictionaryRef> pageInfo = adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3635                 CGPDFContextBeginPage(context.get(), pageInfo.get());
3636
3637                 GraphicsContext ctx(context.get());
3638                 ctx.scale(FloatSize(1, -1));
3639                 ctx.translate(0, -m_printContext->pageRect(page).height());
3640                 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
3641
3642                 CGPDFContextEndPage(context.get());
3643             }
3644         }
3645         CGPDFContextClose(context.get());
3646     }
3647 #endif
3648
3649     send(Messages::WebPageProxy::DataCallback(IPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3650 }
3651
3652 #elif PLATFORM(GTK)
3653 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3654 {
3655     beginPrinting(frameID, printInfo);
3656     if (m_printContext && m_printOperation) {
3657         m_printOperation->startPrint(m_printContext.get(), callbackID);
3658         return;
3659     }
3660
3661     send(Messages::WebPageProxy::VoidCallback(callbackID));
3662 }
3663
3664 void WebPage::didFinishPrintOperation(const WebCore::ResourceError& error, uint64_t callbackID)
3665 {
3666     send(Messages::WebPageProxy::PrintFinishedCallback(error, callbackID));
3667     m_printOperation = nullptr;
3668 }
3669 #endif
3670
3671 void WebPage::savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size)
3672 {
3673     send(Messages::WebPageProxy::SavePDFToFileInDownloadsFolder(suggestedFilename, originatingURLString, IPC::DataReference(data, size)));
3674 }
3675
3676 #if PLATFORM(COCOA)
3677 void WebPage::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID)
3678 {
3679     send(Messages::WebPageProxy::SavePDFToTemporaryFolderAndOpenWithNativeApplication(suggestedFilename, originatingURLString, IPC::DataReference(data, size), pdfUUID));
3680 }
3681 #endif
3682
3683 void WebPage::setMediaVolume(float volume)
3684 {
3685     m_page->setMediaVolume(volume);
3686 }
3687
3688 void WebPage::setMayStartMediaWhenInWindow(bool mayStartMedia)
3689 {
3690     if (mayStartMedia == m_mayStartMediaWhenInWindow)
3691         return;
3692
3693     m_mayStartMediaWhenInWindow = mayStartMedia;
3694     if (m_mayStartMediaWhenInWindow && m_page->isInWindow())
3695         m_setCanStartMediaTimer.startOneShot(0);
3696 }
3697
3698 void WebPage::runModal()
3699 {
3700     if (m_isClosed)
3701         return;
3702     if (m_isRunningModal)
3703         return;
3704
3705     m_isRunningModal = true;
3706     send(Messages::WebPageProxy::RunModal());
3707     RunLoop::run();
3708     ASSERT(!m_isRunningModal);
3709 }
3710
3711 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
3712 {
3713     m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
3714 }
3715
3716 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
3717 {
3718     if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
3719         return true;
3720
3721 #if ENABLE(BLOB)
3722     if (request.url().protocolIs("blob"))
3723         return true;
3724 #endif
3725
3726     return platformCanHandleRequest(request);
3727 }
3728
3729 #if USE(TILED_BACKING_STORE)
3730 void WebPage::commitPageTransitionViewport()
3731 {
3732     m_drawingArea->setLayerTreeStateIsFrozen(false);
3733 }
3734 #endif
3735
3736 #if PLATFORM(COCOA)
3737 void WebPage::handleAlternativeTextUIResult(const String& result)
3738 {
3739     Frame& frame = m_page->focusController().focusedOrMainFrame();
3740     frame.editor().handleAlternativeTextUIResult(result);
3741 }
3742 #endif
3743
3744 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3745 {
3746     mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3747 }
3748
3749 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3750 {
3751     mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3752 }
3753
3754 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
3755 {
3756     mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
3757 }
3758
3759 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
3760 {
3761     Frame& frame = m_page->focusController().focusedOrMainFrame();
3762     if (!frame.editor().canEdit())
3763         return;
3764
3765     Vector<CompositionUnderline> underlines;
3766     underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
3767     frame.editor().setComposition(compositionString, underlines, from, from + length);
3768 }
3769
3770 bool WebPage::hasCompositionForTesting()
3771 {
3772     Frame& frame = m_page->focusController().focusedOrMainFrame();
3773     return frame.editor().hasComposition();
3774 }
3775
3776 void WebPage::confirmCompositionForTesting(const String& compositionString)
3777 {
3778     Frame& frame = m_page->focusController().focusedOrMainFrame();
3779     if (!frame.editor().canEdit())
3780         return;
3781
3782     if (compositionString.isNull())
3783         frame.editor().confirmComposition();
3784     frame.editor().confirmComposition(compositionString);
3785 }
3786
3787 void WebPage::numWheelEventHandlersChanged(unsigned numWheelEventHandlers)
3788 {
3789     if (m_numWheelEventHandlers == numWheelEventHandlers)
3790         return;
3791
3792     m_numWheelEventHandlers = numWheelEventHandlers;
3793     recomputeShortCircuitHorizontalWheelEventsState();
3794 }
3795
3796 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
3797 {
3798     if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
3799         return scrollbar->enabled();
3800
3801     return false;
3802 }
3803
3804 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
3805 {
3806     if (FrameView* frameView = mainFrame->view()) {
3807         if (hasEnabledHorizontalScrollbar(frameView))
3808             return true;
3809     }
3810
3811     for (Frame* frame = mainFrame; frame; frame = frame->tree().traverseNext()) {
3812         FrameView* frameView = frame->view();
3813         if (!frameView)
3814             continue;
3815
3816         const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
3817         if (!scrollableAreas)
3818             continue;
3819
3820         for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
3821             ScrollableArea* scrollableArea = *it;
3822             if (!scrollableArea->scrollbarsCanBeActive())
3823                 continue;
3824
3825             if (hasEnabledHorizontalScrollbar(scrollableArea))
3826                 return true;
3827         }
3828     }
3829
3830     return false;
3831 }
3832
3833 void WebPage::recomputeShortCircuitHorizontalWheelEventsState()
3834 {
3835     bool canShortCircuitHorizontalWheelEvents = !m_numWheelEventHandlers;
3836
3837     if (canShortCircuitHorizontalWheelEvents) {
3838         // Check if we have any horizontal scroll bars on the page.
3839         if (pageContainsAnyHorizontalScrollbars(mainFrame()))
3840             canShortCircuitHorizontalWheelEvents = false;
3841     }
3842
3843     if (m_canShortCircuitHorizontalWheelEvents == canShortCircuitHorizontalWheelEvents)
3844         return;
3845
3846     m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents;
3847     send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents));
3848 }
3849
3850 Frame* WebPage::mainFrame() const
3851 {
3852     return m_page ? &m_page->mainFrame() : 0;
3853 }
3854
3855 FrameView* WebPage::mainFrameView() const
3856 {
3857     if (Frame* frame = mainFrame())
3858         return frame->view();
3859     
3860     return 0;
3861 }
3862
3863 void WebPage::setScrollingPerformanceLoggingEnabled(bool enabled)
3864 {
3865     m_scrollingPerformanceLoggingEnabled = enabled;
3866
3867     FrameView* frameView = m_mainFrame->coreFrame()->view();
3868     if (!frameView)
3869         return;
3870
3871     frameView->setScrollingPerformanceLoggingEnabled(enabled);
3872 }
3873
3874 bool WebPage::canPluginHandleResponse(const ResourceResponse& response)
3875 {
3876 #if ENABLE(NETSCAPE_PLUGIN_API)
3877     uint32_t pluginLoadPolicy;
3878     bool allowOnlyApplicationPlugins = !m_mainFrame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin);
3879
3880     uint64_t pluginProcessToken;
3881     String newMIMEType;
3882     String unavailabilityDescription;
3883     if (!sendSync(Messages::WebPageProxy::FindPlugin(response.mimeType(), PluginProcessTypeNormal, response.url().string(), response.url().string(), response.url().string(), allowOnlyApplicationPlugins), Messages::WebPageProxy::FindPlugin::Reply(pluginProcessToken, newMIMEType, pluginLoadPolicy, unavailabilityDescription)))
3884         return false;
3885
3886     return pluginLoadPolicy != PluginModuleBlocked && pluginProcessToken;
3887 #else
3888     UNUSED_PARAM(response);
3889     return false;
3890 #endif
3891 }
3892
3893 bool WebPage::shouldUseCustomContentProviderForResponse(const ResourceResponse& response)
3894 {
3895     // If a plug-in exists that claims to support this response, it should take precedence over the custom content provider.
3896     return m_mimeTypesWithCustomContentProviders.contains(response.mimeType()) && !canPluginHandleResponse(response);
3897 }
3898
3899 #if PLATFORM(COCOA)
3900
3901 void WebPage::insertTextAsync(const String& text, const EditingRange& replacementEditingRange)
3902 {
3903     Frame& frame = m_page->focusController().focusedOrMainFrame();
3904
3905     if (replacementEditingRange.location != notFound) {
3906         RefPtr<Range> replacementRange = rangeFromEditingRange(frame, replacementEditingRange);
3907         if (replacementRange)
3908             frame.selection().setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
3909     }
3910
3911     if (!frame.editor().hasComposition()) {
3912         // An insertText: might be handled by other responders in the chain if we don't handle it.
3913         // One example is space bar that results in scrolling down the page.
3914         frame.editor().insertText(text, nullptr);
3915     } else
3916         frame.editor().confirmComposition(text);
3917 }
3918
3919 void WebPage::getMarkedRangeAsync(uint64_t callbackID)
3920 {
3921     Frame& frame = m_page->focusController().focusedOrMainFrame();
3922
3923     RefPtr<Range> range = frame.editor().compositionRange();
3924     size_t location;
3925     size_t length;
3926     if (!range || !TextIterator::getLocationAndLengthFromRange(frame.selection().rootEditableElementOrDocumentElement(), range.get(), location, length)) {
3927         location = notFound;
3928         length = 0;
3929     }
3930
3931     send(Messages::WebPageProxy::EditingRangeCallback(EditingRange(location, length), callbackID));
3932 }
3933
3934 void WebPage::getSelectedRangeAsync(uint64_t callbackID)
3935 {
3936     Frame& frame = m_page->focusController().focusedOrMainFrame();
3937
3938     size_t location;
3939     size_t length;
3940     RefPtr<Range> range = frame.selection().toNormalizedRange();
3941     if (!range || !TextIterator::getLocationAndLengthFromRange(frame.selection().rootEditableElementOrDocumentElement(), range.get(), location, length)) {
3942         location = notFound;
3943         length = 0;
3944     }
3945
3946     send(Messages::WebPageProxy::EditingRangeCallback(EditingRange(location, length), callbackID));
3947 }
3948
3949 void WebPage::characterIndexForPointAsync(const WebCore::IntPoint& point, uint64_t callbackID)
3950 {
3951     uint64_t index = notFound;
3952
3953     HitTestResult result = m_page->mainFrame().eventHandler().hitTestResultAtPoint(point);
3954     Frame* frame = result.innerNonSharedNode() ? result.innerNodeFrame() : &m_page->focusController().focusedOrMainFrame();
3955     
3956     RefPtr<Range> range = frame->rangeForPoint(result.roundedPointInInnerNodeFrame());
3957     if (range) {
3958         size_t location;
3959         size_t length;
3960         if (TextIterator::getLocationAndLengthFromRange(frame->selection().rootEditableElementOrDocumentElement(), range.get(), location, length))
3961             index = static_cast<uint64_t>(location);
3962     }
3963
3964     send(Messages::WebPageProxy::UnsignedCallback(index, callbackID));
3965 }
3966
3967 void WebPage::firstRectForCharacterRangeAsync(const EditingRange& editingRange, uint64_t callbackID)
3968 {
3969     Frame& frame = m_page->focusController().focusedOrMainFrame();
3970     IntRect result(IntPoint(0, 0), IntSize(0, 0));
3971     
3972     RefPtr<Range> range = rangeFromEditingRange(frame, editingRange);
3973     if (!range) {
3974         send(Messages::WebPageProxy::RectForCharacterRangeCallback(result, EditingRange(notFound, 0), callbackID));
3975         return;
3976     }
3977
3978     ASSERT(range->startContainer());
3979     ASSERT(range->endContainer());
3980
3981     result = frame.view()->contentsToWindow(frame.editor().firstRectForRange(range.get()));
3982
3983     // FIXME: Update actualRange to match the range of first rect.
3984     send(Messages::WebPageProxy::RectForCharacterRangeCallback(result, editingRange, callbackID));
3985 }
3986
3987 void WebPage::setCompositionAsync(const String& text, Vector<CompositionUnderline> underlines, const EditingRange& selection, const EditingRange& replacementEditingRange)
3988 {
3989     Frame& frame = m_page->focusController().focusedOrMainFrame();
3990
3991     if (frame.selection().selection().isContentEditable()) {
3992         RefPtr<Range> replacementRange;
3993         if (replacementEditingRange.location != notFound) {
3994             replacementRange = rangeFromEditingRange(frame, replacementEditingRange);
3995             frame.selection().setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
3996         }
3997
3998         frame.editor().setComposition(text, underlines, selection.location, selection.location + selection.length);
3999     }
4000 }
4001
4002 void WebPage::confirmCompositionAsync()
4003 {
4004     Frame& frame = m_page->focusController().focusedOrMainFrame();
4005     frame.editor().confirmComposition();
4006 }
4007
4008 #endif // PLATFORM(COCOA)
4009
4010 #if PLATFORM(GTK)
4011 static Frame* targetFrameForEditing(WebPage* page)
4012 {
4013     Frame& targetFrame = page->corePage()->focusController().focusedOrMainFrame();
4014
4015     Editor& editor = targetFrame.editor();
4016     if (!editor.canEdit())
4017         return 0;
4018
4019     if (editor.hasComposition()) {
4020         // We should verify the parent node of this IME composition node are
4021         // editable because JavaScript may delete a parent node of the composition
4022         // node. In this case, WebKit crashes while deleting texts from the parent
4023         // node, which doesn't exist any longer.
4024         if (PassRefPtr<Range> range = editor.compositionRange()) {
4025             Node* node = range->startContainer();
4026             if (!node || !node->isContentEditable())
4027                 return 0;
4028         }
4029     }
4030     return &targetFrame;
4031 }
4032
4033 void WebPage::confirmComposition(const String& compositionString, int64_t selectionStart, int64_t selectionLength)
4034 {
4035     Frame* targetFrame = targetFrameForEditing(this);
4036     if (!targetFrame) {
4037         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
4038         return;
4039     }
4040
4041     targetFrame->editor().confirmComposition(compositionString);
4042
4043     if (selectionStart == -1) {
4044         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
4045         return;
4046     }
4047
4048     Element* scope = targetFrame->selection().selection().rootEditableElement();
4049     RefPtr<Range> selectionRange = TextIterator::rangeFromLocationAndLength(scope, selectionStart, selectionLength);
4050     ASSERT_WITH_MESSAGE(selectionRange, "Invalid selection: [%lld:%lld] in text of length %d", static_cast<long long>(selectionStart), static_cast<long long>(selectionLength), scope->innerText().length());
4051
4052     if (selectionRange) {
4053         VisibleSelection selection(selectionRange.get(), SEL_DEFAULT_AFFINITY);
4054         targetFrame->selection().setSelection(selection);
4055     }
4056     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
4057 }
4058
4059 void WebPage::setComposition(const String& text, Vector<CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionLength, uint64_t replacementStart, uint64_t replacementLength)
4060 {
4061     Frame* targetFrame = targetFrameForEditing(this);
4062     if (!targetFrame || !targetFrame->selection().selection().isContentEditable()) {
4063         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
4064         return;
4065     }
4066
4067     if (replacementLength > 0) {
4068         // The layout needs to be uptodate before setting a selection
4069         targetFrame->document()->updateLayout();
4070
4071         Element* scope = targetFrame->selection().selection().rootEditableElement();
4072         RefPtr<Range> replacementRange = TextIterator::rangeFromLocationAndLength(scope, replacementStart, replacementLength);
4073         targetFrame->editor().setIgnoreCompositionSelectionChange(true);
4074         targetFrame->selection().setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
4075         targetFrame->editor().setIgnoreCompositionSelectionChange(false);
4076     }
4077
4078     targetFrame->editor().setComposition(text, underlines, selectionStart, selectionStart + selectionLength);
4079     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
4080 }
4081
4082 void WebPage::cancelComposition()
4083 {
4084     if (Frame* targetFrame = targetFrameForEditing(this))
4085         targetFrame->editor().cancelComposition();
4086     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
4087 }
4088 #endif
4089
4090 void WebPage::didChangeSelection()
4091 {
4092     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
4093 }
4094
4095 void WebPage::setMinimumLayoutSize(const IntSize& minimumLayoutSize)
4096 {
4097     if (m_minimumLayoutSize == minimumLayoutSize)
4098         return;
4099
4100     m_minimumLayoutSize = minimumLayoutSize;
4101     if (minimumLayoutSize.width() <= 0) {
4102         corePage()->mainFrame().view()->enableAutoSizeMode(false, IntSize(), IntSize());
4103         return;
4104     }
4105
4106     int minimumLayoutWidth = minimumLayoutSize.width();
4107     int minimumLayoutHeight = std::max(minimumLayoutSize.height(), 1);
4108
4109     int maximumSize = std::numeric_limits<int>::max();
4110
4111     corePage()->mainFrame().view()->enableAutoSizeMode(true, IntSize(minimumLayoutWidth, minimumLayoutHeight), IntSize(maximumSize, maximumSize));
4112 }
4113
4114 void WebPage::setAutoSizingShouldExpandToViewHeight(bool shouldExpand)
4115 {
4116     if (m_autoSizingShouldExpandToViewHeight == shouldExpand)
4117         return;
4118
4119     m_autoSizingShouldExpandToViewHeight = shouldExpand;
4120
4121     corePage()->mainFrame().view()->setAutoSizeFixedMinimumHeight(shouldExpand ? m_viewSize.height() : 0);
4122 }
4123
4124 bool WebPage::isSmartInsertDeleteEnabled()
4125 {
4126     return m_page->settings().smartInsertDeleteEnabled();
4127 }
4128
4129 void WebPage::setSmartInsertDeleteEnabled(bool enabled)
4130 {
4131     if (m_page->settings().smartInsertDeleteEnabled() != enabled) {
4132         m_page->settings().setSmartInsertDeleteEnabled(enabled);
4133         setSelectTrailingWhitespaceEnabled(!enabled);
4134     }
4135 }
4136
4137 bool WebPage::isSelectTrailingWhitespaceEnabled()
4138 {
4139     return m_page->settings().selectTrailingWhitespaceEnabled();
4140 }
4141
4142 void WebPage::setSelectTrailingWhitespaceEnabled(bool enabled)
4143 {
4144     if (m_page->settings().selectTrailingWhitespaceEnabled() != enabled) {
4145         m_page->settings().setSelectTrailingWhitespaceEnabled(enabled);
4146         setSmartInsertDeleteEnabled(!enabled);
4147     }
4148 }
4149
4150 bool WebPage::canShowMIMEType(const String& MIMEType) const
4151 {
4152     if (MIMETypeRegistry::canShowMIMEType(MIMEType))
4153         return true;
4154
4155     if (m_mimeTypesWithCustomContentProviders.contains(MIMEType))
4156         return true;
4157
4158     const PluginData& pluginData = m_page->pluginData();
4159     if (pluginData.supportsMimeType(MIMEType, PluginData::AllPlugins) && corePage()->mainFrame().loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin))
4160         return true;
4161
4162     // We can use application plugins even if plugins aren't enabled.
4163     if (pluginData.supportsMimeType(MIMEType, PluginData::OnlyApplicationPlugins))
4164         return true;
4165
4166     return false;
4167 }
4168
4169 void WebPage::addTextCheckingRequest(uint64_t requestID, PassRefPtr<TextCheckingRequest> request)
4170 {
4171     m_pendingTextCheckingRequestMap.add(requestID, request);
4172 }
4173
4174 void WebPage::didFinishCheckingText(uint64_t requestID, const Vector<TextCheckingResult>& result)
4175 {
4176     RefPtr<TextCheckingRequest> request = m_pendingTextCheckingRequestMap.take(requestID);
4177     if (!request)
4178         return;
4179