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