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