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