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