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