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