b19b7098eda3f4d47c7f99f13efacabaa6e5b0d0
[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, true);
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         setViewStateInternal(parameters.viewState, true);
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     setViewStateInternal(viewState, false);
2073
2074     if (wantsDidUpdateViewState)
2075         m_sendDidUpdateViewStateTimer.startOneShot(0);
2076 }
2077
2078 void WebPage::setViewStateInternal(ViewState::Flags viewState, bool isInitialState)
2079 {
2080     ViewState::Flags changed = m_viewState ^ viewState;
2081     m_viewState = viewState;
2082
2083     m_drawingArea->viewStateDidChange(changed);
2084     m_page->setViewState(viewState, isInitialState);
2085     for (auto* pluginView : m_pluginViews)
2086         pluginView->viewStateDidChange(changed);
2087
2088     if (changed & ViewState::IsInWindow)
2089         updateIsInWindow();
2090 }
2091
2092 void WebPage::setLayerHostingMode(unsigned layerHostingMode)
2093 {
2094     m_layerHostingMode = static_cast<LayerHostingMode>(layerHostingMode);
2095
2096     m_drawingArea->setLayerHostingMode(m_layerHostingMode);
2097
2098     for (auto* pluginView : m_pluginViews)
2099         pluginView->setLayerHostingMode(m_layerHostingMode);
2100 }
2101
2102 uint64_t WebPage::sessionID() const
2103 {
2104     if (m_sessionID)
2105         return m_sessionID;
2106
2107     return m_page->settings().privateBrowsingEnabled() ? SessionTracker::legacyPrivateSessionID : SessionTracker::defaultSessionID;
2108 }
2109
2110 void WebPage::setSessionID(uint64_t sessionID)
2111 {
2112     m_sessionID = sessionID;
2113     if (SessionTracker::isEphemeralID(sessionID))
2114         WebProcess::shared().ensurePrivateBrowsingSession(sessionID);
2115 }
2116
2117 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
2118 {
2119     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2120     if (!frame)
2121         return;
2122     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
2123 }
2124
2125 void WebPage::didStartPageTransition()
2126 {
2127     m_drawingArea->setLayerTreeStateIsFrozen(true);
2128 }
2129
2130 void WebPage::didCompletePageTransition()
2131 {
2132 #if USE(TILED_BACKING_STORE)
2133     if (m_mainFrame->coreFrame()->view()->delegatesScrolling())
2134         // Wait until the UI process sent us the visible rect it wants rendered.
2135         send(Messages::WebPageProxy::PageTransitionViewportReady());
2136     else
2137 #endif
2138         
2139     m_drawingArea->setLayerTreeStateIsFrozen(false);
2140 }
2141
2142 void WebPage::show()
2143 {
2144     send(Messages::WebPageProxy::ShowPage());
2145 }
2146
2147 void WebPage::setUserAgent(const String& userAgent)
2148 {
2149     m_userAgent = userAgent;
2150 }
2151
2152 void WebPage::suspendActiveDOMObjectsAndAnimations()
2153 {
2154     m_page->suspendActiveDOMObjectsAndAnimations();
2155 }
2156
2157 void WebPage::resumeActiveDOMObjectsAndAnimations()
2158 {
2159     m_page->resumeActiveDOMObjectsAndAnimations();
2160 }
2161
2162 IntPoint WebPage::screenToWindow(const IntPoint& point)
2163 {
2164     IntPoint windowPoint;
2165     sendSync(Messages::WebPageProxy::ScreenToWindow(point), Messages::WebPageProxy::ScreenToWindow::Reply(windowPoint));
2166     return windowPoint;
2167 }
2168     
2169 IntRect WebPage::windowToScreen(const IntRect& rect)
2170 {
2171     IntRect screenRect;
2172     sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
2173     return screenRect;
2174 }
2175
2176 IntRect WebPage::windowResizerRect() const
2177 {
2178     if (m_windowResizerSize.isEmpty())
2179         return IntRect();
2180
2181     IntSize frameViewSize;
2182     if (Frame* coreFrame = m_mainFrame->coreFrame()) {
2183         if (FrameView* view = coreFrame->view())
2184             frameViewSize = view->size();
2185     }
2186
2187     return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(), 
2188                    m_windowResizerSize.width(), m_windowResizerSize.height());
2189 }
2190
2191 KeyboardUIMode WebPage::keyboardUIMode()
2192 {
2193     bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
2194     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2195 }
2196
2197 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2198 {
2199     // NOTE: We need to be careful when running scripts that the objects we depend on don't
2200     // disappear during script execution.
2201
2202     // Retain the SerializedScriptValue at this level so it (and the internal data) lives
2203     // long enough for the DataReference to be encoded by the sent message.
2204     RefPtr<SerializedScriptValue> serializedResultValue;
2205     IPC::DataReference dataReference;
2206
2207     JSLockHolder lock(JSDOMWindow::commonVM());
2208     if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) {
2209         if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
2210             dataReference = serializedResultValue->data();
2211     }
2212
2213     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2214 }
2215
2216 void WebPage::getContentsAsString(uint64_t callbackID)
2217 {
2218     String resultString = m_mainFrame->contentsAsString();
2219     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2220 }
2221
2222 #if ENABLE(MHTML)
2223 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2224 {
2225     IPC::DataReference dataReference;
2226
2227     RefPtr<SharedBuffer> buffer = useBinaryEncoding
2228         ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2229         : MHTMLArchive::generateMHTMLData(m_page.get());
2230
2231     if (buffer)
2232         dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2233
2234     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2235 }
2236 #endif
2237
2238 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2239 {
2240     String resultString = renderTreeExternalRepresentation();
2241     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2242 }
2243
2244 static Frame* frameWithSelection(Page* page)
2245 {
2246     for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2247         if (frame->selection().isRange())
2248             return frame;
2249     }
2250
2251     return 0;
2252 }
2253
2254 void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID)
2255 {
2256     IPC::DataReference dataReference;
2257
2258 #if PLATFORM(MAC)
2259     RefPtr<LegacyWebArchive> archive;
2260     RetainPtr<CFDataRef> data;
2261
2262     Frame* frame = frameWithSelection(m_page.get());
2263     if (frame) {
2264         archive = LegacyWebArchive::createFromSelection(frame);
2265         data = archive->rawDataRepresentation();
2266         dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2267     }
2268 #endif
2269
2270     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2271 }
2272
2273 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2274 {
2275     String resultString = m_mainFrame->selectionAsString();
2276     if (resultString.isEmpty())
2277         resultString = m_mainFrame->contentsAsString();
2278     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2279 }
2280
2281 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2282 {
2283     String resultString;
2284     if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
2285        resultString = frame->source();
2286
2287     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2288 }
2289
2290 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2291 {
2292     IPC::DataReference dataReference;
2293
2294     RefPtr<ResourceBuffer> buffer;
2295     RefPtr<SharedBuffer> pdfResource;
2296     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2297         if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame())) {
2298             if ((pdfResource = pluginView->liveResourceData()))
2299                 dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(pdfResource->data()), pdfResource->size());
2300         }
2301
2302         if (dataReference.isEmpty()) {
2303             if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader()) {
2304                 if ((buffer = loader->mainResourceData()))
2305                     dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2306             }
2307         }
2308     }
2309
2310     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2311 }
2312
2313 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
2314 {
2315     DocumentLoader* loader = frame->loader().documentLoader();
2316     if (!loader)
2317         return 0;
2318
2319     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2320     if (!subresource)
2321         return 0;
2322
2323     return subresource->data();
2324 }
2325
2326 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2327 {
2328     IPC::DataReference dataReference;
2329     URL resourceURL(URL(), resourceURLString);
2330
2331     RefPtr<SharedBuffer> buffer;
2332     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2333         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2334         if (!buffer) {
2335             // Try to get the resource data from the cache.
2336             buffer = cachedResponseDataForURL(resourceURL);
2337         }
2338
2339         if (buffer)
2340             dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2341     }
2342
2343     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2344 }
2345
2346 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2347 {
2348     IPC::DataReference dataReference;
2349
2350 #if PLATFORM(MAC)
2351     RetainPtr<CFDataRef> data;
2352     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2353         if ((data = frame->webArchiveData(0, 0)))
2354             dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2355     }
2356 #else
2357     UNUSED_PARAM(frameID);
2358 #endif
2359
2360     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2361 }
2362
2363 void WebPage::forceRepaintWithoutCallback()
2364 {
2365     m_drawingArea->forceRepaint();
2366 }
2367
2368 void WebPage::forceRepaint(uint64_t callbackID)
2369 {
2370     if (m_drawingArea->forceRepaintAsync(callbackID))
2371         return;
2372
2373     forceRepaintWithoutCallback();
2374     send(Messages::WebPageProxy::VoidCallback(callbackID));
2375 }
2376
2377 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2378 {
2379     WebPreferencesStore::removeTestRunnerOverrides();
2380     updatePreferences(store);
2381 }
2382
2383 void WebPage::updatePreferences(const WebPreferencesStore& store)
2384 {
2385     Settings& settings = m_page->settings();
2386
2387     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2388     m_asynchronousPluginInitializationEnabled = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledKey());
2389     m_asynchronousPluginInitializationEnabledForAllPlugins = store.getBoolValueForKey(WebPreferencesKey::asynchronousPluginInitializationEnabledForAllPluginsKey());
2390     m_artificialPluginInitializationDelayEnabled = store.getBoolValueForKey(WebPreferencesKey::artificialPluginInitializationDelayEnabledKey());
2391
2392     m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey());
2393
2394 #if PLATFORM(MAC)
2395     m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey());
2396 #endif
2397
2398     // FIXME: This should be generated from macro expansion for all preferences,
2399     // but we currently don't match the naming of WebCore exactly so we are
2400     // handrolling the boolean and integer preferences until that is fixed.
2401
2402 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings.set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2403
2404     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2405
2406 #undef INITIALIZE_SETTINGS
2407
2408     settings.setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2409     settings.setScriptMarkupEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptMarkupEnabledKey()));
2410     settings.setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2411     settings.setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2412     settings.setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2413     settings.setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2414     settings.setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));    
2415     settings.setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2416     settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2417     settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2418     settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2419     if (m_sessionID)
2420         settings.setPrivateBrowsingEnabled(SessionTracker::isEphemeralID(m_sessionID));
2421     else
2422         settings.setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
2423     settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2424     settings.setJavaScriptExperimentsEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptExperimentsEnabledKey()));
2425     settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2426     settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2427     settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2428     settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2429     settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2430 #if ENABLE(WEB_ARCHIVE)
2431     settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2432 #endif
2433     settings.setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2434     settings.setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2435     settings.setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2436     settings.setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2437     settings.setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2438     settings.setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2439     settings.setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2440     settings.setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2441     settings.setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2442     settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2443     settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2444
2445     settings.setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2446     settings.setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2447     settings.setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2448     settings.setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2449     settings.setScreenFontSubstitutionEnabled(store.getBoolValueForKey(WebPreferencesKey::screenFontSubstitutionEnabledKey())
2450 #if PLATFORM(MAC)
2451         || WebProcess::shared().shouldForceScreenFontSubstitution()
2452 #endif
2453     );
2454     settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2455     settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2456     settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2457     settings.setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2458     settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2459
2460     settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2461     settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2462     settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2463     settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2464     settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2465     settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2466     settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2467     settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2468     RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2469     RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey()));
2470     settings.setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
2471     settings.setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
2472     settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2473     settings.setMultithreadedWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::multithreadedWebGLEnabledKey()));
2474     settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey()));
2475     settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2476     settings.setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
2477     settings.setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
2478     settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2479     settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2480     settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2481 #if ENABLE(SMOOTH_SCROLLING)
2482     settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2483 #endif
2484     settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2485     settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey()));
2486
2487 #if ENABLE(SQL_DATABASE)
2488     DatabaseManager::manager().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2489 #endif
2490
2491 #if ENABLE(FULLSCREEN_API)
2492     settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2493 #endif
2494
2495 #if USE(AVFOUNDATION)
2496     settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2497 #endif
2498
2499 #if PLATFORM(MAC)
2500     settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2501 #endif
2502
2503 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2504     settings.setVideoPluginProxyEnabled(false);
2505 #endif
2506
2507 #if ENABLE(WEB_AUDIO)
2508     settings.setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2509 #endif
2510
2511 #if ENABLE(MEDIA_STREAM)
2512     settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey()));
2513 #endif
2514
2515     settings.setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2516     settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2517     settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey()));
2518     settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2519     settings.setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2520     settings.setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2521
2522 #if ENABLE(VIDEO_TRACK)
2523     settings.setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2524     settings.setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2525     settings.setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2526 #endif
2527
2528 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2529     settings.setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2530 #endif
2531
2532     settings.setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2533     settings.setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2534     settings.setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2535
2536     settings.setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2537
2538     settings.setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2539
2540     settings.setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2541     settings.setSnapshotAllPlugIns(store.getBoolValueForKey(WebPreferencesKey::snapshotAllPlugInsKey()));
2542     settings.setAutostartOriginPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::autostartOriginPlugInSnapshottingEnabledKey()));
2543     settings.setPrimaryPlugInSnapshotDetectionEnabled(store.getBoolValueForKey(WebPreferencesKey::primaryPlugInSnapshotDetectionEnabledKey()));
2544     settings.setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2545
2546 #if ENABLE(TEXT_AUTOSIZING)
2547     settings.setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2548 #endif
2549
2550     settings.setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2551     settings.setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2552
2553     settings.setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2554     settings.setSelectTrailingWhitespaceEnabled(store.getBoolValueForKey(WebPreferencesKey::selectTrailingWhitespaceEnabledKey()));
2555     settings.setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2556
2557 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2558     settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey()));
2559 #endif
2560 #if ENABLE(PAGE_VISIBILITY_API)
2561     settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey()));
2562 #endif
2563
2564     settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey()));
2565     settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey()));
2566     settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey()));
2567
2568     settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey()));
2569
2570 #if ENABLE(MEDIA_SOURCE)
2571     settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey()));
2572 #endif
2573
2574     if (store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey())) {
2575         if (m_processSuppressionDisabledByWebPreference.isActive())
2576             m_processSuppressionDisabledByWebPreference.endActivity();
2577     } else {
2578         if (!m_processSuppressionDisabledByWebPreference.isActive())
2579             m_processSuppressionDisabledByWebPreference.beginActivity();
2580     }
2581
2582     platformPreferencesDidChange(store);
2583
2584     if (m_drawingArea)
2585         m_drawingArea->updatePreferences(store);
2586 }
2587
2588 #if ENABLE(INSPECTOR)
2589 WebInspector* WebPage::inspector()
2590 {
2591     if (m_isClosed)
2592         return 0;
2593     if (!m_inspector)
2594         m_inspector = WebInspector::create(this, m_inspectorClient);
2595     return m_inspector.get();
2596 }
2597 #endif
2598     
2599 #if PLATFORM(IOS)
2600 WebVideoFullscreenManager* WebPage::videoFullscreenManager()
2601 {
2602     if (!m_videoFullscreenManager)
2603         m_videoFullscreenManager = WebVideoFullscreenManager::create(this);
2604     return m_videoFullscreenManager.get();
2605 }
2606 #endif
2607
2608 #if ENABLE(FULLSCREEN_API)
2609 WebFullScreenManager* WebPage::fullScreenManager()
2610 {
2611     if (!m_fullScreenManager)
2612         m_fullScreenManager = WebFullScreenManager::create(this);
2613     return m_fullScreenManager.get();
2614 }
2615 #endif
2616
2617 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2618 {
2619     if (m_notificationPermissionRequestManager)
2620         return m_notificationPermissionRequestManager.get();
2621
2622     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2623     return m_notificationPermissionRequestManager.get();
2624 }
2625
2626 #if !PLATFORM(GTK) && !PLATFORM(MAC)
2627 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2628 {
2629     Node* node = evt->target()->toNode();
2630     ASSERT(node);
2631     Frame* frame = node->document().frame();
2632     ASSERT(frame);
2633
2634     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2635     if (!keyEvent)
2636         return false;
2637
2638     Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
2639
2640     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2641         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2642         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2643         // (e.g. Tab that inserts a Tab character, or Enter).
2644         return !command.isTextInsertion() && command.execute(evt);
2645     }
2646
2647     if (command.execute(evt))
2648         return true;
2649
2650     // Don't allow text insertion for nodes that cannot edit.
2651     if (!frame->editor().canEdit())
2652         return false;
2653
2654     // Don't insert null or control characters as they can result in unexpected behaviour
2655     if (evt->charCode() < ' ')
2656         return false;
2657
2658     return frame->editor().insertText(evt->keyEvent()->text(), evt);
2659 }
2660 #endif
2661
2662 #if ENABLE(DRAG_SUPPORT)
2663
2664 #if PLATFORM(GTK)
2665 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2666 {
2667     if (!m_page) {
2668         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2669         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2670         data->deref();
2671         return;
2672     }
2673
2674     switch (action) {
2675     case DragControllerActionEntered:
2676         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData)));
2677         break;
2678
2679     case DragControllerActionUpdated:
2680         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData)));
2681         break;
2682
2683     case DragControllerActionExited:
2684         m_page->dragController().dragExited(dragData);
2685         break;
2686
2687     case DragControllerActionPerformDrag: {
2688         m_page->dragController().performDrag(dragData);
2689         break;
2690     }
2691
2692     default:
2693         ASSERT_NOT_REACHED();
2694     }
2695     // DragData does not delete its platformData so we need to do that here.
2696     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2697     data->deref();
2698 }
2699
2700 #else
2701 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)
2702 {
2703     if (!m_page) {
2704         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2705         return;
2706     }
2707
2708     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2709     switch (action) {
2710     case DragControllerActionEntered:
2711         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData)));
2712         break;
2713
2714     case DragControllerActionUpdated:
2715         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData)));
2716         break;
2717         
2718     case DragControllerActionExited:
2719         m_page->dragController().dragExited(dragData);
2720         break;
2721         
2722     case DragControllerActionPerformDrag: {
2723         ASSERT(!m_pendingDropSandboxExtension);
2724
2725         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2726         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
2727             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
2728                 m_pendingDropExtensionsForFileUpload.append(extension);
2729         }
2730
2731         m_page->dragController().performDrag(dragData);
2732
2733         // If we started loading a local file, the sandbox extension tracker would have adopted this
2734         // pending drop sandbox extension. If not, we'll play it safe and clear it.
2735         m_pendingDropSandboxExtension = nullptr;
2736
2737         m_pendingDropExtensionsForFileUpload.clear();
2738         break;
2739     }
2740
2741     default:
2742         ASSERT_NOT_REACHED();
2743     }
2744 }
2745 #endif
2746
2747 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2748 {
2749     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController().dragOffset().x(), clientPosition.y() + m_page->dragController().dragOffset().y());
2750     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController().dragOffset().x(), globalPosition.y() + m_page->dragController().dragOffset().y());
2751
2752     m_page->dragController().dragEnded();
2753     FrameView* view = m_page->mainFrame().view();
2754     if (!view)
2755         return;
2756     // FIXME: These are fake modifier keys here, but they should be real ones instead.
2757     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2758     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation);
2759 }
2760
2761 void WebPage::willPerformLoadDragDestinationAction()
2762 {
2763     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2764 }
2765
2766 void WebPage::mayPerformUploadDragDestinationAction()
2767 {
2768     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2769         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
2770     m_pendingDropExtensionsForFileUpload.clear();
2771 }
2772     
2773 #endif // ENABLE(DRAG_SUPPORT)
2774
2775 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2776 {
2777     return m_undoStepMap.get(stepID);
2778 }
2779
2780 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2781 {
2782     m_undoStepMap.set(stepID, entry);
2783 }
2784
2785 void WebPage::removeWebEditCommand(uint64_t stepID)
2786 {
2787     m_undoStepMap.remove(stepID);
2788 }
2789
2790 void WebPage::unapplyEditCommand(uint64_t stepID)
2791 {
2792     WebUndoStep* step = webUndoStep(stepID);
2793     if (!step)
2794         return;
2795
2796     step->step()->unapply();
2797 }
2798
2799 void WebPage::reapplyEditCommand(uint64_t stepID)
2800 {
2801     WebUndoStep* step = webUndoStep(stepID);
2802     if (!step)
2803         return;
2804
2805     m_isInRedo = true;
2806     step->step()->reapply();
2807     m_isInRedo = false;
2808 }
2809
2810 void WebPage::didRemoveEditCommand(uint64_t commandID)
2811 {
2812     removeWebEditCommand(commandID);
2813 }
2814
2815 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2816 {
2817     m_activePopupMenu = menu;
2818 }
2819
2820 #if ENABLE(INPUT_TYPE_COLOR)
2821 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
2822 {
2823     m_activeColorChooser = colorChooser;
2824 }
2825
2826 void WebPage::didEndColorPicker()
2827 {
2828     m_activeColorChooser->didEndChooser();
2829 }
2830
2831 void WebPage::didChooseColor(const WebCore::Color& color)
2832 {
2833     m_activeColorChooser->didChooseColor(color);
2834 }
2835 #endif
2836
2837 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2838 {
2839     m_activeOpenPanelResultListener = openPanelResultListener;
2840 }
2841
2842 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2843 {
2844     return m_page->findString(target, options);
2845 }
2846
2847 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2848 {
2849     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2850 }
2851
2852 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2853 {
2854     m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2855 }
2856
2857 void WebPage::getImageForFindMatch(uint32_t matchIndex)
2858 {
2859     m_findController.getImageForFindMatch(matchIndex);
2860 }
2861
2862 void WebPage::selectFindMatch(uint32_t matchIndex)
2863 {
2864     m_findController.selectFindMatch(matchIndex);
2865 }
2866
2867 void WebPage::hideFindUI()
2868 {
2869     m_findController.hideFindUI();
2870 }
2871
2872 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2873 {
2874     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2875 }
2876
2877 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2878 {
2879     changeSelectedIndex(newIndex);
2880     m_activePopupMenu = 0;
2881 }
2882
2883 void WebPage::changeSelectedIndex(int32_t index)
2884 {
2885     if (!m_activePopupMenu)
2886         return;
2887
2888     m_activePopupMenu->didChangeSelectedIndex(index);
2889 }
2890
2891 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
2892 {
2893     if (!m_activeOpenPanelResultListener)
2894         return;
2895
2896     m_activeOpenPanelResultListener->didChooseFiles(files);
2897     m_activeOpenPanelResultListener = 0;
2898 }
2899
2900 void WebPage::didCancelForOpenPanel()
2901 {
2902     m_activeOpenPanelResultListener = 0;
2903 }
2904
2905 #if ENABLE(WEB_PROCESS_SANDBOX)
2906 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
2907 {
2908     SandboxExtension::create(handle)->consumePermanently();
2909 }
2910 #endif
2911
2912 #if ENABLE(GEOLOCATION)
2913 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
2914 {
2915     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
2916 }
2917 #endif
2918
2919 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
2920 {
2921     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
2922 }
2923
2924 #if !PLATFORM(IOS)
2925 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
2926 {
2927     Frame& frame = m_page->focusController().focusedOrMainFrame();
2928     frame.editor().advanceToNextMisspelling(startBeforeSelection);
2929 }
2930 #endif
2931
2932 void WebPage::changeSpellingToWord(const String& word)
2933 {
2934     replaceSelectionWithText(&m_page->focusController().focusedOrMainFrame(), word);
2935 }
2936
2937 void WebPage::unmarkAllMisspellings()
2938 {
2939     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2940         if (Document* document = frame->document())
2941             document->markers().removeMarkers(DocumentMarker::Spelling);
2942     }
2943 }
2944
2945 void WebPage::unmarkAllBadGrammar()
2946 {
2947     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2948         if (Document* document = frame->document())
2949             document->markers().removeMarkers(DocumentMarker::Grammar);
2950     }
2951 }
2952
2953 #if USE(APPKIT)
2954 void WebPage::uppercaseWord()
2955 {
2956     m_page->focusController().focusedOrMainFrame().editor().uppercaseWord();
2957 }
2958
2959 void WebPage::lowercaseWord()
2960 {
2961     m_page->focusController().focusedOrMainFrame().editor().lowercaseWord();
2962 }
2963
2964 void WebPage::capitalizeWord()
2965 {
2966     m_page->focusController().focusedOrMainFrame().editor().capitalizeWord();
2967 }
2968 #endif
2969     
2970 void WebPage::setTextForActivePopupMenu(int32_t index)
2971 {
2972     if (!m_activePopupMenu)
2973         return;
2974
2975     m_activePopupMenu->setTextForIndex(index);
2976 }
2977
2978 #if PLATFORM(GTK)
2979 void WebPage::failedToShowPopupMenu()
2980 {
2981     if (!m_activePopupMenu)
2982         return;
2983
2984     m_activePopupMenu->client()->popupDidHide();
2985 }
2986 #endif
2987
2988 #if ENABLE(CONTEXT_MENUS)
2989 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
2990 {
2991     if (!m_contextMenu)
2992         return;
2993
2994     m_contextMenu->itemSelected(item);
2995     m_contextMenu = 0;
2996 }
2997 #endif
2998
2999 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3000 {
3001     bool selectReplacement = true;
3002     bool smartReplace = false;
3003     return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace);
3004 }
3005
3006 void WebPage::clearSelection()
3007 {
3008     m_page->focusController().focusedOrMainFrame().selection().clear();
3009 }
3010
3011 void WebPage::updateMainFrameScrollOffsetPinning()
3012 {
3013     Frame& frame = m_page->mainFrame();
3014     IntPoint scrollPosition = frame.view()->scrollPosition();
3015     IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition();
3016     IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition();
3017
3018     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3019     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3020     bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
3021     bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
3022
3023     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
3024         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
3025         
3026         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3027         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3028         m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
3029         m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
3030     }
3031 }
3032
3033 void WebPage::mainFrameDidLayout()
3034 {
3035     unsigned pageCount = m_page->pageCount();
3036     if (pageCount != m_cachedPageCount) {
3037         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3038         m_cachedPageCount = pageCount;
3039     }
3040
3041 #if USE(TILED_BACKING_STORE)
3042     if (m_drawingArea && m_drawingArea->layerTreeHost()) {
3043         double red, green, blue, alpha;
3044         m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha);
3045         RGBA32 rgba = makeRGBA32FromFloats(red, green, blue, alpha);
3046         if (m_backgroundColor.rgb() != rgba) {
3047             m_backgroundColor.setRGB(rgba);
3048             m_drawingArea->layerTreeHost()->setBackgroundColor(m_backgroundColor);
3049         }
3050     }
3051 #endif
3052
3053 #if PLATFORM(MAC) && !PLATFORM(IOS)
3054     m_viewGestureGeometryCollector.mainFrameDidLayout();
3055 #endif
3056 #if PLATFORM(IOS)
3057     if (FrameView* frameView = mainFrameView()) {
3058         m_viewportConfiguration.setContentsSize(frameView->contentsSize());
3059         viewportConfigurationChanged();
3060     }
3061 #endif
3062 }
3063
3064 void WebPage::addPluginView(PluginView* pluginView)
3065 {
3066     ASSERT(!m_pluginViews.contains(pluginView));
3067
3068     m_pluginViews.add(pluginView);
3069     m_hasSeenPlugin = true;
3070 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3071     LOG(Plugins, "Primary Plug-In Detection: triggering detection from addPluginView(%p)", pluginView);
3072     m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3073 #endif
3074 }
3075
3076 void WebPage::removePluginView(PluginView* pluginView)
3077 {
3078     ASSERT(m_pluginViews.contains(pluginView));
3079
3080     m_pluginViews.remove(pluginView);
3081 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3082     LOG(Plugins, "Primary Plug-In Detection: removePluginView(%p)", pluginView);
3083 #endif
3084 }
3085
3086 void WebPage::sendSetWindowFrame(const FloatRect& windowFrame)
3087 {
3088 #if PLATFORM(MAC)
3089     m_hasCachedWindowFrame = false;
3090 #endif
3091     send(Messages::WebPageProxy::SetWindowFrame(windowFrame));
3092 }
3093
3094 #if PLATFORM(MAC)
3095 void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates)
3096 {
3097     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3098     m_windowFrameInUnflippedScreenCoordinates = windowFrameInUnflippedScreenCoordinates;
3099     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3100     m_accessibilityPosition = accessibilityViewCoordinates;
3101     
3102     // Tell all our plug-in views that the window and view frames have changed.
3103     for (auto* pluginView : m_pluginViews)
3104         pluginView->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
3105
3106     m_hasCachedWindowFrame = !m_windowFrameInUnflippedScreenCoordinates.isEmpty();
3107 }
3108 #endif
3109
3110 void WebPage::setMainFrameIsScrollable(bool isScrollable)
3111 {
3112     m_mainFrameIsScrollable = isScrollable;
3113     m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
3114
3115     if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
3116         frameView->setCanHaveScrollbars(isScrollable);
3117         frameView->setProhibitsScrolling(!isScrollable);
3118     }
3119 }
3120
3121 bool WebPage::windowIsFocused() const
3122 {
3123     return m_page->focusController().isActive();
3124 }
3125
3126 bool WebPage::windowAndWebPageAreFocused() const
3127 {
3128     if (!isVisible())
3129         return false;
3130
3131     return m_page->focusController().isFocused() && m_page->focusController().isActive();
3132 }
3133
3134 void WebPage::didReceiveMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder)
3135 {
3136     if (decoder.messageReceiverName() == Messages::DrawingArea::messageReceiverName()) {
3137         if (m_drawingArea)
3138             m_drawingArea->didReceiveDrawingAreaMessage(connection, decoder);
3139         return;
3140     }
3141
3142 #if USE(TILED_BACKING_STORE)
3143     if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
3144         if (m_drawingArea)
3145             m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
3146         return;
3147     }
3148 #endif
3149     
3150 #if ENABLE(INSPECTOR)
3151     if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
3152         if (WebInspector* inspector = this->inspector())
3153             inspector->didReceiveWebInspectorMessage(connection, decoder);
3154         return;
3155     }
3156 #endif
3157
3158 #if ENABLE(FULLSCREEN_API)
3159     if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
3160         fullScreenManager()->didReceiveMessage(connection, decoder);
3161         return;
3162     }
3163 #endif
3164
3165     didReceiveWebPageMessage(connection, decoder);
3166 }
3167
3168 void WebPage::didReceiveSyncMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder)
3169 {   
3170     didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
3171 }
3172     
3173 InjectedBundleBackForwardList* WebPage::backForwardList()
3174 {
3175     if (!m_backForwardList)
3176         m_backForwardList = InjectedBundleBackForwardList::create(this);
3177     return m_backForwardList.get();
3178 }
3179
3180 #if ENABLE(ASYNC_SCROLLING)
3181 ScrollingCoordinator* WebPage::scrollingCoordinator() const
3182 {
3183     return m_page->scrollingCoordinator();
3184 }
3185 #endif
3186
3187 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3188 {
3189     invalidate();
3190 }
3191
3192 void WebPage::SandboxExtensionTracker::invalidate()
3193 {
3194     m_pendingProvisionalSandboxExtension = nullptr;
3195
3196     if (m_provisionalSandboxExtension) {
3197         m_provisionalSandboxExtension->revoke();
3198         m_provisionalSandboxExtension = nullptr;
3199     }
3200
3201     if (m_committedSandboxExtension) {
3202         m_committedSandboxExtension->revoke();
3203         m_committedSandboxExtension = nullptr;
3204     }
3205 }
3206
3207 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3208 {
3209     setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3210 }
3211
3212 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3213 {
3214     ASSERT_UNUSED(frame, frame->isMainFrame());
3215
3216     setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3217 }
3218
3219 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3220 {
3221     m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;    
3222 }
3223
3224 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3225 {
3226     ASSERT(frame->isMainFrame());
3227
3228     FrameLoader& frameLoader = frame->coreFrame()->loader();
3229     FrameLoadType frameLoadType = frameLoader.loadType();
3230
3231     // If the page is being reloaded, it should reuse whatever extension is committed.
3232     if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
3233         return true;
3234
3235     DocumentLoader* documentLoader = frameLoader.documentLoader();
3236     DocumentLoader* provisionalDocumentLoader = frameLoader.provisionalDocumentLoader();
3237     if (!documentLoader || !provisionalDocumentLoader)
3238         return false;
3239
3240     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3241         return true;
3242
3243     return false;
3244 }
3245
3246 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3247 {
3248     if (!frame->isMainFrame())
3249         return;
3250
3251     // We should only reuse the commited sandbox extension if it is not null. It can be
3252     // null if the last load was for an error page.
3253     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame))
3254         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension;
3255
3256     ASSERT(!m_provisionalSandboxExtension);
3257
3258     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3259     if (!m_provisionalSandboxExtension)
3260         return;
3261
3262     ASSERT(!m_provisionalSandboxExtension || frame->coreFrame()->loader().provisionalDocumentLoader()->url().isLocalFile());
3263
3264     m_provisionalSandboxExtension->consume();
3265 }
3266
3267 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3268 {
3269     if (!frame->isMainFrame())
3270         return;
3271
3272     if (m_committedSandboxExtension)
3273         m_committedSandboxExtension->revoke();
3274
3275     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3276
3277     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started.
3278     // This extension is not cleared, because it does not pertain to the failed load, and will be needed.
3279 }
3280
3281 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3282 {
3283     if (!frame->isMainFrame())
3284         return;
3285
3286     if (!m_provisionalSandboxExtension)
3287         return;
3288
3289     m_provisionalSandboxExtension->revoke();
3290     m_provisionalSandboxExtension = nullptr;
3291
3292     // We can also have a non-null m_pendingProvisionalSandboxExtension if a new load is being started
3293     // (notably, if the current one fails because the new one cancels it). This extension is not cleared,
3294     // because it does not pertain to the failed load, and will be needed.
3295 }
3296
3297 bool WebPage::hasLocalDataForURL(const URL& url)
3298 {
3299     if (url.isLocalFile())
3300         return true;
3301
3302     DocumentLoader* documentLoader = m_page->mainFrame().loader().documentLoader();
3303     if (documentLoader && documentLoader->subresource(url))
3304         return true;
3305
3306     return platformHasLocalDataForURL(url);
3307 }
3308
3309 void WebPage::setCustomTextEncodingName(const String& encoding)
3310 {
3311     m_page->mainFrame().loader().reloadWithOverrideEncoding(encoding);
3312 }
3313
3314 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3315 {
3316     WebBackForwardListProxy::removeItem(itemID);
3317 }
3318
3319 #if PLATFORM(MAC)
3320
3321 bool WebPage::isSpeaking()
3322 {
3323     bool result;
3324     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3325 }
3326
3327 void WebPage::speak(const String& string)
3328 {
3329     send(Messages::WebPageProxy::Speak(string));
3330 }
3331
3332 void WebPage::stopSpeaking()
3333 {
3334     send(Messages::WebPageProxy::StopSpeaking());
3335 }
3336
3337 #endif
3338
3339 #if PLATFORM(MAC) && !PLATFORM(IOS)
3340 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3341 {
3342     Document* document = coreFrame->document();
3343     if (!document)
3344         return 0;
3345
3346     if (!document->isPluginDocument())
3347         return 0;
3348
3349     PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
3350     if (!pluginView)
3351         return 0;
3352
3353     return pluginView->pdfDocumentForPrinting();
3354 }
3355 #endif // PLATFORM(MAC)
3356
3357 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3358 {
3359     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3360     if (!frame)
3361         return;
3362
3363     Frame* coreFrame = frame->coreFrame();
3364     if (!coreFrame)
3365         return;
3366
3367 #if PLATFORM(MAC) && !PLATFORM(IOS)
3368     if (pdfDocumentForPrintingFrame(coreFrame))
3369         return;
3370 #endif // PLATFORM(MAC)
3371
3372     if (!m_printContext)
3373         m_printContext = adoptPtr(new PrintContext(coreFrame));
3374
3375     drawingArea()->setLayerTreeStateIsFrozen(true);
3376     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3377
3378     float fullPageHeight;
3379     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3380
3381 #if PLATFORM(GTK)
3382     if (!m_printOperation)
3383         m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3384 #endif
3385 }
3386
3387 void WebPage::endPrinting()
3388 {
3389     drawingArea()->setLayerTreeStateIsFrozen(false);
3390 #if PLATFORM(GTK)
3391     m_printOperation = 0;
3392 #endif
3393     m_printContext = nullptr;
3394 }
3395
3396 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3397 {
3398     Vector<IntRect> resultPageRects;
3399     double resultTotalScaleFactorForPrinting = 1;
3400
3401     beginPrinting(frameID, printInfo);
3402
3403     if (m_printContext) {
3404         resultPageRects = m_printContext->pageRects();
3405         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3406     }
3407 #if PLATFORM(MAC)
3408     else
3409         computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3410 #endif // PLATFORM(MAC)
3411
3412     // If we're asked to print, we should actually print at least a blank page.
3413     if (resultPageRects.isEmpty())
3414         resultPageRects.append(IntRect(0, 0, 1, 1));
3415
3416     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3417 }
3418
3419 #if PLATFORM(MAC)
3420 void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, uint64_t callbackID)
3421 {
3422     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3423     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3424
3425     RefPtr<WebImage> image;
3426
3427 #if USE(CG)
3428     if (coreFrame) {
3429 #if PLATFORM(MAC) && !PLATFORM(IOS)
3430         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3431 #else
3432         ASSERT(coreFrame->document()->printing());
3433 #endif
3434
3435         RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(imageSize, ShareableBitmap::SupportsAlpha);
3436         auto graphicsContext = bitmap->createGraphicsContext();
3437
3438         float printingScale = static_cast<float>(imageSize.width()) / rect.width();
3439         graphicsContext->scale(FloatSize(printingScale, printingScale));
3440
3441 #if PLATFORM(MAC) && !PLATFORM(IOS)
3442         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3443             ASSERT(!m_printContext);
3444             graphicsContext->scale(FloatSize(1, -1));
3445             graphicsContext->translate(0, -rect.height());
3446             drawPDFDocument(graphicsContext->platformContext(), pdfDocument.get(), printInfo, rect);
3447         } else
3448 #endif
3449         {
3450             m_printContext->spoolRect(*graphicsContext, rect);
3451         }
3452
3453         image = WebImage::create(bitmap.release());
3454     }
3455 #endif
3456
3457     ShareableBitmap::Handle handle;
3458
3459     if (image)
3460         image->bitmap()->createHandle(handle, SharedMemory::ReadOnly);
3461
3462     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
3463 }
3464
3465 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3466 {
3467     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3468     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3469
3470     RetainPtr<CFMutableDataRef> pdfPageData = adoptCF(CFDataCreateMutable(0, 0));
3471
3472 #if USE(CG)
3473     if (coreFrame) {
3474
3475 #if PLATFORM(MAC) && !PLATFORM(IOS)
3476         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3477 #else
3478         ASSERT(coreFrame->document()->printing());
3479 #endif
3480
3481         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3482         RetainPtr<CGDataConsumerRef> pdfDataConsumer = adoptCF(CGDataConsumerCreateWithCFData(pdfPageData.get()));
3483
3484         CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3485         RetainPtr<CGContextRef> context = adoptCF(CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3486
3487 #if PLATFORM(MAC) && !PLATFORM(IOS)
3488         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3489             ASSERT(!m_printContext);
3490             drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3491         } else
3492 #endif
3493         {
3494             size_t pageCount = m_printContext->pageCount();
3495             for (uint32_t page = first; page < first + count; ++page) {
3496                 if (page >= pageCount)
3497                     break;
3498
3499                 RetainPtr<CFDictionaryRef> pageInfo = adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3500                 CGPDFContextBeginPage(context.get(), pageInfo.get());
3501
3502                 GraphicsContext ctx(context.get());
3503                 ctx.scale(FloatSize(1, -1));
3504                 ctx.translate(0, -m_printContext->pageRect(page).height());
3505                 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
3506
3507                 CGPDFContextEndPage(context.get());
3508             }
3509         }
3510         CGPDFContextClose(context.get());
3511     }
3512 #endif
3513
3514     send(Messages::WebPageProxy::DataCallback(IPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3515 }
3516
3517 #elif PLATFORM(GTK)
3518
3519 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3520 {
3521     beginPrinting(frameID, printInfo);
3522     if (m_printContext && m_printOperation) {
3523         m_printOperation->startPrint(m_printContext.get(), callbackID);
3524         return;
3525     }
3526
3527     send(Messages::WebPageProxy::VoidCallback(callbackID));
3528 }
3529 #endif
3530
3531 void WebPage::savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size)
3532 {
3533     send(Messages::WebPageProxy::SavePDFToFileInDownloadsFolder(suggestedFilename, originatingURLString, IPC::DataReference(data, size)));
3534 }
3535
3536 #if PLATFORM(MAC)
3537 void WebPage::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID)
3538 {
3539     send(Messages::WebPageProxy::SavePDFToTemporaryFolderAndOpenWithNativeApplication(suggestedFilename, originatingURLString, IPC::DataReference(data, size), pdfUUID));
3540 }
3541 #endif
3542
3543 void WebPage::setMediaVolume(float volume)
3544 {
3545     m_page->setMediaVolume(volume);
3546 }
3547
3548 void WebPage::setMayStartMediaWhenInWindow(bool mayStartMedia)
3549 {
3550     if (mayStartMedia == m_mayStartMediaWhenInWindow)
3551         return;
3552
3553     m_mayStartMediaWhenInWindow = mayStartMedia;
3554     if (m_mayStartMediaWhenInWindow && m_page->isInWindow())
3555         m_setCanStartMediaTimer.startOneShot(0);
3556 }
3557
3558 void WebPage::runModal()
3559 {
3560     if (m_isClosed)
3561         return;
3562     if (m_isRunningModal)
3563         return;
3564
3565     m_isRunningModal = true;
3566     send(Messages::WebPageProxy::RunModal());
3567     RunLoop::run();
3568     ASSERT(!m_isRunningModal);
3569 }
3570
3571 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
3572 {
3573     m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
3574 }
3575
3576 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
3577 {
3578     if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
3579         return true;
3580
3581 #if ENABLE(BLOB)
3582     if (request.url().protocolIs("blob"))
3583         return true;
3584 #endif
3585
3586     return platformCanHandleRequest(request);
3587 }
3588
3589 #if USE(TILED_BACKING_STORE)
3590 void WebPage::commitPageTransitionViewport()
3591 {
3592     m_drawingArea->setLayerTreeStateIsFrozen(false);
3593 }
3594 #endif
3595
3596 #if PLATFORM(MAC)
3597 void WebPage::handleAlternativeTextUIResult(const String& result)
3598 {
3599     Frame& frame = m_page->focusController().focusedOrMainFrame();
3600     frame.editor().handleAlternativeTextUIResult(result);
3601 }
3602 #endif
3603
3604 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3605 {
3606     mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3607 }
3608
3609 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3610 {
3611     mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3612 }
3613
3614 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
3615 {
3616     mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
3617 }
3618
3619 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
3620 {
3621     Frame& frame = m_page->focusController().focusedOrMainFrame();
3622     if (!frame.editor().canEdit())
3623         return;
3624
3625     Vector<CompositionUnderline> underlines;
3626     underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
3627     frame.editor().setComposition(compositionString, underlines, from, from + length);
3628 }
3629
3630 bool WebPage::hasCompositionForTesting()
3631 {
3632     Frame& frame = m_page->focusController().focusedOrMainFrame();
3633     return frame.editor().hasComposition();
3634 }
3635
3636 void WebPage::confirmCompositionForTesting(const String& compositionString)
3637 {
3638     Frame& frame = m_page->focusController().focusedOrMainFrame();
3639     if (!frame.editor().canEdit())
3640         return;
3641
3642     if (compositionString.isNull())
3643         frame.editor().confirmComposition();
3644     frame.editor().confirmComposition(compositionString);
3645 }
3646
3647 void WebPage::numWheelEventHandlersChanged(unsigned numWheelEventHandlers)
3648 {
3649     if (m_numWheelEventHandlers == numWheelEventHandlers)
3650         return;
3651
3652     m_numWheelEventHandlers = numWheelEventHandlers;
3653     recomputeShortCircuitHorizontalWheelEventsState();
3654 }
3655
3656 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
3657 {
3658     if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
3659         return scrollbar->enabled();
3660
3661     return false;
3662 }
3663
3664 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
3665 {
3666     if (FrameView* frameView = mainFrame->view()) {
3667         if (hasEnabledHorizontalScrollbar(frameView))
3668             return true;
3669     }
3670
3671     for (Frame* frame = mainFrame; frame; frame = frame->tree().traverseNext()) {
3672         FrameView* frameView = frame->view();
3673         if (!frameView)
3674             continue;
3675
3676         const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
3677         if (!scrollableAreas)
3678             continue;
3679
3680         for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
3681             ScrollableArea* scrollableArea = *it;
3682             if (!scrollableArea->scrollbarsCanBeActive())
3683                 continue;
3684
3685             if (hasEnabledHorizontalScrollbar(scrollableArea))
3686                 return true;
3687         }
3688     }
3689
3690     return false;
3691 }
3692
3693 void WebPage::recomputeShortCircuitHorizontalWheelEventsState()
3694 {
3695     bool canShortCircuitHorizontalWheelEvents = !m_numWheelEventHandlers;
3696
3697     if (canShortCircuitHorizontalWheelEvents) {
3698         // Check if we have any horizontal scroll bars on the page.
3699         if (pageContainsAnyHorizontalScrollbars(mainFrame()))
3700             canShortCircuitHorizontalWheelEvents = false;
3701     }
3702
3703     if (m_canShortCircuitHorizontalWheelEvents == canShortCircuitHorizontalWheelEvents)
3704         return;
3705
3706     m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents;
3707     send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents));
3708 }
3709
3710 Frame* WebPage::mainFrame() const
3711 {
3712     return m_page ? &m_page->mainFrame() : 0;
3713 }
3714
3715 FrameView* WebPage::mainFrameView() const
3716 {
3717     if (Frame* frame = mainFrame())
3718         return frame->view();
3719     
3720     return 0;
3721 }
3722
3723 void WebPage::setVisibilityStatePrerender()
3724 {
3725     if (m_page)
3726         m_page->setIsPrerender();
3727 }
3728
3729 void WebPage::setScrollingPerformanceLoggingEnabled(bool enabled)
3730 {
3731     m_scrollingPerformanceLoggingEnabled = enabled;
3732
3733     FrameView* frameView = m_mainFrame->coreFrame()->view();
3734     if (!frameView)
3735         return;
3736
3737     frameView->setScrollingPerformanceLoggingEnabled(enabled);
3738 }
3739
3740 bool WebPage::canPluginHandleResponse(const ResourceResponse& response)
3741 {
3742 #if ENABLE(NETSCAPE_PLUGIN_API)
3743     uint32_t pluginLoadPolicy;
3744     bool allowOnlyApplicationPlugins = !m_mainFrame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin);
3745
3746     uint64_t pluginProcessToken;
3747     String newMIMEType;
3748     String unavailabilityDescription;
3749     if (!sendSync(Messages::WebPageProxy::FindPlugin(response.mimeType(), PluginProcessTypeNormal, response.url().string(), response.url().string(), response.url().string(), allowOnlyApplicationPlugins), Messages::WebPageProxy::FindPlugin::Reply(pluginProcessToken, newMIMEType, pluginLoadPolicy, unavailabilityDescription)))
3750         return false;
3751
3752     return pluginLoadPolicy != PluginModuleBlocked && pluginProcessToken;
3753 #else
3754     UNUSED_PARAM(response);
3755     return false;
3756 #endif
3757 }
3758
3759 #if PLATFORM(GTK)
3760 static Frame* targetFrameForEditing(WebPage* page)
3761 {
3762     Frame& targetFrame = page->corePage()->focusController().focusedOrMainFrame();
3763
3764     Editor& editor = targetFrame.editor();
3765     if (!editor.canEdit())
3766         return 0;
3767
3768     if (editor.hasComposition()) {
3769         // We should verify the parent node of this IME composition node are
3770         // editable because JavaScript may delete a parent node of the composition
3771         // node. In this case, WebKit crashes while deleting texts from the parent
3772         // node, which doesn't exist any longer.
3773         if (PassRefPtr<Range> range = editor.compositionRange()) {
3774             Node* node = range->startContainer();
3775             if (!node || !node->isContentEditable())
3776                 return 0;
3777         }
3778     }
3779     return &targetFrame;
3780 }
3781
3782 void WebPage::confirmComposition(const String& compositionString, int64_t selectionStart, int64_t selectionLength)
3783 {
3784     Frame* targetFrame = targetFrameForEditing(this);
3785     if (!targetFrame) {
3786         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3787         return;
3788     }
3789
3790     targetFrame->editor().confirmComposition(compositionString);
3791
3792     if (selectionStart == -1) {
3793         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3794         return;
3795     }
3796
3797     Element* scope = targetFrame->selection().selection().rootEditableElement();
3798     RefPtr<Range> selectionRange = TextIterator::rangeFromLocationAndLength(scope, selectionStart, selectionLength);
3799     ASSERT_WITH_MESSAGE(selectionRange, "Invalid selection: [%lld:%lld] in text of length %d", static_cast<long long>(selectionStart), static_cast<long long>(selectionLength), scope->innerText().length());
3800
3801     if (selectionRange) {
3802         VisibleSelection selection(selectionRange.get(), SEL_DEFAULT_AFFINITY);
3803         targetFrame->selection().setSelection(selection);
3804     }
3805     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3806 }
3807
3808 void WebPage::setComposition(const String& text, Vector<CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementStart, uint64_t replacementLength)
3809 {
3810     Frame* targetFrame = targetFrameForEditing(this);
3811     if (!targetFrame || !targetFrame->selection().selection().isContentEditable()) {
3812         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3813         return;
3814     }
3815
3816     if (replacementLength > 0) {
3817         // The layout needs to be uptodate before setting a selection
3818         targetFrame->document()->updateLayout();
3819
3820         Element* scope = targetFrame->selection().selection().rootEditableElement();
3821         RefPtr<Range> replacementRange = TextIterator::rangeFromLocationAndLength(scope, replacementStart, replacementLength);
3822         targetFrame->editor().setIgnoreCompositionSelectionChange(true);
3823         targetFrame->selection().setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
3824         targetFrame->editor().setIgnoreCompositionSelectionChange(false);
3825     }
3826
3827     targetFrame->editor().setComposition(text, underlines, selectionStart, selectionEnd);
3828     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3829 }
3830
3831 void WebPage::cancelComposition()
3832 {
3833     if (Frame* targetFrame = targetFrameForEditing(this))
3834         targetFrame->editor().cancelComposition();
3835     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3836 }
3837 #endif
3838
3839 void WebPage::didChangeSelection()
3840 {
3841     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3842 }
3843
3844 void WebPage::setMainFrameInViewSourceMode(bool inViewSourceMode)
3845 {
3846     m_mainFrame->coreFrame()->setInViewSourceMode(inViewSourceMode);
3847 }
3848
3849 void WebPage::setMinimumLayoutSize(const IntSize& minimumLayoutSize)
3850 {
3851     if (m_minimumLayoutSize == minimumLayoutSize)
3852         return;
3853
3854     m_minimumLayoutSize = minimumLayoutSize;
3855     if (minimumLayoutSize.width() <= 0) {
3856         corePage()->mainFrame().view()->enableAutoSizeMode(false, IntSize(), IntSize());
3857         return;
3858     }
3859
3860     int minimumLayoutWidth = minimumLayoutSize.width();
3861     int minimumLayoutHeight = std::max(minimumLayoutSize.height(), 1);
3862
3863     int maximumSize = std::numeric_limits<int>::max();
3864
3865     corePage()->mainFrame().view()->enableAutoSizeMode(true, IntSize(minimumLayoutWidth, minimumLayoutHeight), IntSize(maximumSize, maximumSize));
3866 }
3867
3868 void WebPage::setAutoSizingShouldExpandToViewHeight(bool shouldExpand)
3869 {
3870     if (m_autoSizingShouldExpandToViewHeight == shouldExpand)
3871         return;
3872
3873     m_autoSizingShouldExpandToViewHeight = shouldExpand;
3874
3875     corePage()->mainFrame().view()->setAutoSizeFixedMinimumHeight(shouldExpand ? m_viewSize.height() : 0);
3876 }
3877
3878 bool WebPage::isSmartInsertDeleteEnabled()
3879 {
3880     return m_page->settings().smartInsertDeleteEnabled();
3881 }
3882
3883 void WebPage::setSmartInsertDeleteEnabled(bool enabled)
3884 {
3885     if (m_page->settings().smartInsertDeleteEnabled() != enabled) {
3886         m_page->settings().setSmartInsertDeleteEnabled(enabled);
3887         setSelectTrailingWhitespaceEnabled(!enabled);
3888     }
3889 }
3890
3891 bool WebPage::isSelectTrailingWhitespaceEnabled()
3892 {
3893     return m_page->settings().selectTrailingWhitespaceEnabled();
3894 }
3895
3896 void WebPage::setSelectTrailingWhitespaceEnabled(bool enabled)
3897 {
3898     if (m_page->settings().selectTrailingWhitespaceEnabled() != enabled) {
3899         m_page->settings().setSelectTrailingWhitespaceEnabled(enabled);
3900         setSmartInsertDeleteEnabled(!enabled);
3901     }
3902 }
3903
3904 bool WebPage::canShowMIMEType(const String& MIMEType) const
3905 {
3906     if (MIMETypeRegistry::canShowMIMEType(MIMEType))
3907         return true;
3908
3909     const PluginData& pluginData = m_page->pluginData();
3910     if (pluginData.supportsMimeType(MIMEType, PluginData::AllPlugins) && corePage()->mainFrame().loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin))
3911         return true;
3912
3913     // We can use application plugins even if plugins aren't enabled.
3914     if (pluginData.supportsMimeType(MIMEType, PluginData::OnlyApplicationPlugins))
3915         return true;
3916
3917     return false;
3918 }
3919
3920 void WebPage::addTextCheckingRequest(uint64_t requestID, PassRefPtr<TextCheckingRequest> request)
3921 {
3922     m_pendingTextCheckingRequestMap.add(requestID, request);
3923 }
3924
3925 void WebPage::didFinishCheckingText(uint64_t requestID, const Vector<TextCheckingResult>& result)
3926 {
3927     RefPtr<TextCheckingRequest> request = m_pendingTextCheckingRequestMap.take(requestID);
3928     if (!request)
3929         return;
3930
3931     request->didSucceed(result);
3932 }
3933
3934 void WebPage::didCancelCheckingText(uint64_t requestID)
3935 {
3936     RefPtr<TextCheckingRequest> request = m_pendingTextCheckingRequestMap.take(requestID);
3937     if (!request)
3938         return;
3939
3940     request->didCancel();
3941 }
3942
3943 void WebPage::didCommitLoad(WebFrame* frame)
3944 {
3945     if (!frame->isMainFrame())
3946         return;
3947
3948     // If previous URL is invalid, then it's not a real page that's being navigated away from.
3949     // Most likely, this is actually the first load to be committed in this page.
3950     if (frame->coreFrame()->loader().previousURL().isValid())
3951         reportUsedFeatures();
3952
3953     // Only restore the scale factor for standard frame loads (of the main frame).
3954     if (frame->coreFrame()->loader().loadType() == FrameLoadTypeStandard) {
3955         Page* page = frame->coreFrame()->page();
3956         if (page && page->pageScaleFactor() != 1)
3957             scalePage(1, IntPoint());
3958     }
3959 #if PLATFORM(IOS)
3960     m_userHasChangedPageScaleFactor = false;
3961
3962     if (frame->coreFrame()->document()->isTextDocument())
3963         m_viewportConfiguration.setDefaultConfiguration(ViewportConfiguration::plainTextParameters());
3964     else
3965         m_viewportConfiguration.setDefaultConfiguration(ViewportConfiguration::webpageParameters());
3966
3967     m_viewportConfiguration.setViewportArguments(ViewportArguments());
3968     m_viewportConfiguration.setContentsSize(m_viewportConfiguration.minimumLayoutSize());
3969     viewportConfigurationChanged();
3970 #endif
3971
3972 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3973     resetPrimarySnapshottedPlugIn();
3974 #endif
3975
3976     WebProcess::shared().updateActivePages();
3977
3978     updateMainFrameScrollOffsetPinning();
3979 }
3980
3981 void WebPage::didFinishLoad(WebFrame* frame)
3982 {
3983 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3984     if (!frame->isMainFrame())
3985         return;
3986
3987     m_readyToFindPrimarySnapshottedPlugin = true;
3988     LOG(Plugins, "Primary Plug-In Detection: triggering detection from didFinishLoad (marking as ready to detect).");
3989     m_determinePrimarySnapshottedPlugInTimer.startOneShot(0);
3990 #else
3991     UNUSED_PARAM(frame);
3992 #endif
3993 }
3994
3995 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
3996 static int primarySnapshottedPlugInSearchLimit = 3000;
3997 static float primarySnapshottedPlugInSearchBucketSize = 1.1;
3998 static int primarySnapshottedPlugInMinimumWidth = 400;
3999 static int primarySnapshottedPlugInMinimumHeight = 300;
4000 static unsigned maxPrimarySnapshottedPlugInDetectionAttempts = 2;
4001 static int deferredPrimarySnapshottedPlugInDetectionDelay = 3;
4002
4003 #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
4004 void WebPage::determinePrimarySnapshottedPlugInTimerFired()
4005 {
4006     if (!m_page)
4007         return;
4008     
4009     Settings& settings = m_page->settings();
4010     if (!settings.snapshotAllPlugIns() && settings.primaryPlugInSnapshotDetectionEnabled())
4011         determinePrimarySnapshottedPlugIn();
4012 }
4013 #endif
4014
4015 void WebPage::determinePrimarySnapshottedPlugIn()
4016 {
4017     if (!m_page->settings().plugInSnapshottingEnabled())
4018         return;
4019
4020     LOG(Plugins, "Primary Plug-In Detection: began.");
4021
4022     if (!m_readyToFindPrimarySnapshottedPlugin) {
4023         LOG(Plugins, "Primary Plug-In Detection: exiting - not ready to find plugins.");
4024         return;
4025     }
4026
4027     if (!m_hasSeenPlugin) {
4028         LOG(Plugins, "Primary Plug-In Detection: exiting - we never saw a plug-in get added to the page.");
4029         return;
4030     }
4031
4032     if (m_didFindPrimarySnapshottedPlugin) {
4033         LOG(Plugins, "Primary Plug-In Detection: exiting - we've already found a primary plug-in.");
4034         return;
4035     }
4036
4037     ++m_numberOfPrimarySnapshotDetectionAttempts;
4038
4039     MainFrame& mainFrame = corePage()->mainFrame();
4040     if (!mainFrame.view())
4041         return;
4042     if (!mainFrame.view()->renderView())
4043         return;
4044     RenderView& mainRenderView = *mainFrame.view()->renderView();
4045
4046     IntRect searchRect = IntRect(IntPoint(), corePage()->mainFrame().view()->contentsSize());
4047     searchRect.intersect(IntRect(IntPoint(), IntSize(primarySnapshottedPlugInSearchLimit, primarySnapshottedPlugInSearchLimit)));
4048
4049     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::AllowChildFrameContent | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent);
4050
4051     HTMLPlugInImageElement* candidatePlugIn = nullptr;
4052     unsigned candidatePlugInArea = 0;
4053
4054     for (Frame* frame = &mainFrame; frame; frame = frame->tree().traverseNext()) {
4055         if (!frame->loader().subframeLoader().containsPlugins())
4056             continue;
4057         if (!frame->document() || !frame->view())
4058             continue;
4059         for (auto& plugInImageElement : descendantsOfType<HTMLPlugInImageElement>(*frame->document())) {
4060             if (plugInImageElement.displayState() == HTMLPlugInElement::Playing)
4061                 continue;
4062
4063             IntRect plugInRectRelativeToView = plugInImageElement.clientRect();
4064             if (plugInRectRelativeToView.isEmpty())
4065                 continue;
4066             IntSize scrollOffset = mainFrame.view()->scrollOffsetRelativeToDocument();
4067             IntRect plugInRectRelativeToTopDocument(plugInRectRelativeToView.location() + scrollOffset, plugInRectRelativeToView.size());
4068             if (!plugInRectRelativeToTopDocument.intersects(searchRect))
4069                 continue;
4070
4071             HitTestResult hitTestResult(plugInRectRelativeToTopDocument.center());
4072             mainRenderView.hitTest(request, hitTestResult);
4073
4074             Element* element = hitTestResult.innerElement();
4075             if (element != &plugInImageElement)
4076                 continue;
4077
4078             auto renderer = plugInImageElement.renderer();
4079             if (!renderer || !renderer->isBox())
4080                 continue;
4081             auto& renderBox = toRenderBox(*renderer);
4082             if (renderBox.contentWidth() < primarySnapshottedPlugInMinimumWidth || renderBox.contentHeight() < primarySnapshottedPlugInMinimumHeight)
4083                 continue;
4084
4085             LayoutUnit contentArea = renderBox.contentWidth() * renderBox.contentHeight();
4086             if (contentArea > candidatePlugInArea * primarySnapshottedPlugInSearchBucketSize) {
4087                 candidatePlugIn = &plugInImageElement;
4088                 candidatePlugInArea = contentArea;
4089             }
4090         }
4091     }
4092     if (!candidatePlugIn) {
4093         LOG(Plugins, "Primary Plug-In Detection: fail - did not find a candidate plug-in.");
4094         if (m_numberOfPrimarySnapshotDetectionAttempts < maxPrimarySnapshottedPlugInDetectionAttempts) {
4095             LOG(Plugins, "Primary Plug-In Detection: will attempt again in %ds.", deferredPrimarySnapshottedPlugInDetectionDelay);
4096             m_determinePrimarySnapshottedPlugInTimer.startOneShot(deferredPrimarySnapshottedPlugInDetectionDelay);
4097         }
4098         return;
4099     }
4100
4101     LOG(Plugins, "Primary Plug-In Detection: success - found a candidate plug-in - inform it.");
4102     m_didFindPrimarySnapshottedPlugin = true;
4103     m_primaryPlugInPageOrigin = m_page->mainFrame().document()->baseURL().host();
4104     m_primaryPlugInOrigin = candidatePlugIn->loadedUrl().host();
4105     m_primaryPlugInMimeType = candidatePlugIn->loadedMimeType();
4106
4107     candidatePlugIn->setIsPrimarySnapshottedPlugIn(true);
4108 }
4109
4110 void WebPage::resetPrimarySnapshottedPlugIn()
4111 {
4112     m_readyToFindPrimarySnapshottedPlugin = false;
4113     m_didFindPrimarySnapshottedPlugin = false;
4114     m_numberOfPrimarySnapshotDetectionAttempts = 0;
4115     m_hasSeenPlugin = false;
4116 }
4117
4118 bool WebPage::matchesPrimaryPlugIn(const String& pageOrigin, const String& pluginOrigin, const String& mimeType) const
4119 {
4120     if (!m_didFindPrimarySnapshottedPlugin)
4121         return false;
4122
4123     return (pageOrigin == m_primaryPlugInPageOrigin && pluginOrigin == m_primaryPlugInOrigin && mimeType == m_primaryPlugInMimeType);
4124 }
4125 #endif // ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC)
4126
4127 PassRefPtr<Range> WebPage::currentSelectionAsRange()
4128 {
4129     Frame* frame = frameWithSelection(m_page.get());
4130     if (!frame)
4131         return 0;
4132
4133     return frame->selection().toNormalizedRange();
4134 }
4135
4136 void WebPage::reportUsedFeatures()
4137 {
4138     Vector<String> namedFeatures;
4139     m_loaderClient.featuresUsedInPage(this, namedFeatures);
4140 }
4141
4142 unsigned WebPage::extendIncrementalRenderingSuppression()
4143 {
4144     unsigned token = m_maximumRenderingSuppressionToken + 1;
4145     while (!HashSet<unsigned>::isValidValue(token) || m_activeRenderingSuppressionTokens.contains(token))
4146         token++;
4147
4148     m_activeRenderingSuppressionTokens.add(token);
4149     m_page->mainFrame().view()->setVisualUpdatesAllowedByClient(false);
4150
4151     m_maximumRenderingSuppressionToken = token;
4152
4153     return token;
4154 }
4155
4156 void WebPage::stopExtendingIncrementalRenderingSuppression(unsigned token)
4157 {
4158     if (!m_activeRenderingSuppressionTokens.remove(token))
4159         return;
4160
4161     m_page->mainFrame().view()->setVisualUpdatesAllowedByClient(!shouldExtendIncrementalRenderingSuppression());
4162 }
4163     
4164 void WebPage::setScrollPinningBehavior(uint32_t pinning)
4165 {
4166     m_scrollPinningBehavior = static_cast<ScrollPinningBehavior>(pinning);
4167     m_page->mainFrame().view()->setScrollPinningBehavior(m_scrollPinningBehavior);
4168 }
4169
4170 PassRefPtr<DocumentLoader> WebPage::createDocumentLoader(Frame& frame, const ResourceRequest& request, const SubstituteData& substituteData)
4171 {
4172     RefPtr<WebDocumentLoader> documentLoader = WebDocumentLoader::create(request, substituteData);
4173
4174     if (m_pendingNavigationID) {
4175         ASSERT(frame.isMainFrame());