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